问:
Wrapping a map with instance or static method
I have a java.util.Map<String, Object> object which different types of values in it. I don't want to cast whereever I do a get operation over this. To do this, I created different classes wrapping this map and these classes provide different get methods which return values for different keys.

There are two options for this:

```<code>public class Wrapper1 {
    private final Map<String, Object> map;

    public Wrapper1(Map<String, Object> map) {
        this.map=map;
    }

    public MyObject getMyObject() {
        return (MyObject)this.map.get("someKey");
    }
}
</code>```

```<code>public class Wrapper2 {
    private Wrapper2() {
    }

    public static MyObject getMyObject(Map<String, Object> map) {
        return (MyObject)map.get("someKey");
    }
}
</code>```

As you see, in first one I'm creating an instance of Wrapper1 and access MyObject instance by instance method. In second, I give the map to a static method and access same MyObject instance.

Which one will you prefer more and why?
Also if this is a bad practice, please let me know.
Thank you.

答:
This is still bad practice as you still do castings in there.

If you want to store different types in the map then the chance is high that all of these objects share a common behaviour. In this case all of these should implement the interface that defines this behaviour so that you can store them typesafe and without casting in the same map.

If they dont share the same behaviour then why store all in the same map? They will have different meanings and therefore should be saved in different maps or you create a class that has different maps of these types as members.

The last case is that you are given the array and you can't change the way the objects are saved. In this case I would actually prefer a combination of both your options. Put the static method into the class above. In this way you can commonly use the static function for getting your object without first creating an instance. If you know that you will need to call this method often, you can create an object passing the map and you will not have to always pass the map each time you want to get your object. This is related to using the fabric method pattern or  currying / partial application used in functional programming (in which case the static method alone would be sufficient).

Note however that it would be good to somehow check if the object you get from your map satisfies your expectations (if possible) and otherwise throw an exception.


问:
Should methods returning a hashmap of string to object be avoided?
In my current code I have felt the desire multuple times to have helper methods that generate a collection of objects and return them as a map of string to object, with the string being some unique id like the objects label.  Many of my objects have gaurenteed unique labels since these labels are used via restful interface when querying the object.

The reason I want to do this is efficency.  I may have a decent sized collection and I know that the method calling whatever private helper method I wrote will definately want to search for specific objects within my collection, so returning them as a map allows the calling method to run in O(n) instead of O(n^2).

However, I feel that the return is not self documenting.  The key is just a string, there is nothing that makes it obvious that the string is specifically the objects label.  Obviously I will have comments to that effect, but ideally self documenting code is writen so well one doesn't have to go to method delarations to figure something out.

So I have a few questions:

1) Is the fact that i find myself needing to return maps a code-smell in itself? (other then possibly premature-optimization, which I know I may be a little guilty of, but I don't feel too bad about worrying about the big O of a method)

2) Is this generally acceptable, or should I be looking into a cleaner approch?  For instance should I have be making some map object that auto-maps any object by label?  What about places that I want to return a map where the key is a different key, should I make a wrapping object for all of them?  or is my map good enough?

EDIT:

More detail was asked, so to clarify my specific situation.  I am working within java.  While I may have unique strings they aren't known until compile time and enums are not a good fit, or I would have used them!  I'm not using reflection or any other systems to dynamically generate data, the methods and their meaning is pretty much standard each time.  Usually using the equivalent of a UUID of the objects (which in this case is a string which is used throughout the domain), or the label, which is a guaranteed unique string used to reference the object in question for a restful call.

答:
Should methods returning a hashmap of string to object be avoided?

Yes, if you're using a statically typed language, object should be avoided. It means that you have to cast to do anything meaningful with the result, which means you have to modify any handling code when you add a new type. No good.

And string should be avoided as the key to a function/dictionary. Strings are easy to mistype/misspell. The strings often have implied contracts associated with them: if I ask for "foo", I want to get a Bar back. As soon as you don't get Bar stuff blows up - at runtime. No good.

Is the fact that i find myself needing to return maps a code-smell in itself?

For maps this generic, yes - for statically typed languages. It means that you want something to do anything which is about the worst violation of the single responsibility principle you can have. It also makes your contracts implied, which moves the errors from compile time to runtime, increasing the cost of fixing them and the risk that they make it to production.

Is this generally acceptable, or should I be looking into a cleaner approach?

You should always look for a cleaner approach, but in not a few cases you really do need something this generic. If you're doing serialization, you really need some string to object map... The goal here is to isolate the lack of typing as much as possible. Have a few classes that know about the possible strings and implied contracts. Push the design so that these classes change infrequently. Blow up loudly and promptly when the contracts are violated.

...and all of this goes out the window if you're working in a dynamic language. Pretty much everything there is already a map from string to object (which is another map of string to object), so the best you can do is play along and test like a madman.

ContentLicense: CC BY-SA 3.0


问:
WCF service - best way to accept requests from a client and do background work?
For a project at work, I was tasked to create a WCF service that will receive email messages from client and queue them on a database, while at the same time the service will check the DB every 30 minutes or so to check if there are any new email messages queued, and send them automatically with the appropriate credentials.

To accomplish this, my boss told me to do it with threads: while the main thread is in charge of taking requests from clients, a background thread will be in charge of checking the DB for as long as the service is alive, and send the queued emails. After asking on StackOverflow, however, I was told that for this kind of scenario two services is a better option, a WCF service that takes requests and a different Windows Service that does the background work.

So my question is, what is the best option for implementing this kind of scenario? And is doing this with just threads possible, but ill-advised? I would like to hear more opinions before checking with my boss about the best way to accomplish this.

答:
If you host your WCF service on IIS:

Running long tasks from a web application which uses IIS is a bad idea:

IIS recycles AppDomains at regular intervals; this may not be what you want if you're in the middle of a long task.

IIS recycles AppDomain when files such as web.config are updated.

It may negatively impact performance.

So yes, if you need a background task, use a Windows Service instead.

Sources:

ASP.NET long running task. Thread is being aborted exception

You can start the long-running process in its own application domain.

In the past, when I've needed this capability, I create a Windows Service for this purpose. [...]

What causes an application pool in IIS to recycle?

[...] this can be recycled by a number of effects e.g. time - every 'n' hours, lack of requests, memory use etc. [...]

Can I use threads to carry out long-running jobs on IIS?

[...] In addition to reducing resources available to IIS/ASP.NET to process requests, you also have issues with the thread being killed when the AppDomain is recycled, and then you have to deal with persistence of the task while it is in-flight, as well as starting the work back up when the AppDomain comes back up. [...]

How should I perform a long-running task in ASP.NET 4?

Preferentially, avoid having long tasks executing in such an environment.

Delegate long running tasks out to a stable system service [...]

Windows services are designed to be long running, and if something goes wrong you've generally got more to worry about than your individual service.

If you run your WCF service as a Windows Service:

Separating Windows Service hosting your WCF application from the Windows Service which does the background processing can have two benefits:

If one of the services crashes, the second one is not affected. This is a minor benefit, since if one of the services crashes, you may have more urgent concerns.

You may host each service on a dedicated server. This benefit is also probably minor, unless you're processing a lot of information.

As for using a single service and two threads, I don't see any blocking issue as when the service is hosted on IIS.


问:
How should a JEE application store credentials for logging in to an external system?
I am in a situation where I have a Web Application (WAR) that is accessing a REST service provided by another application. The REST service uses Basic HTTP Authentication.

So that means the application calling the REST service needs to store user credentials somehow. To further complicate things, this is an enterprise, so there are different 'regions' the application moves through which will have different credentials for the same service (think local development, development region, integration region, user test region, production, etc...)

My first instinct is that the credentials should be stored by the JEE container and the application should ask the container for the credentials (probably via JNDI?). I'm beginning to read about Java Authentication and Authorization Service (JAAS) but I'm not sure if that is the appropriate solution to this problem.

How should a JEE application store credentials for logging in to an external system?

A few more details about my WAR. It is a Spring-Integration project that has no front-end. The container I am working with is Websphere. I am using JEE 5 and Spring 4.0.1.

To this point I have not needed to consider spring-security... does this situation mean I should re-evaluate that decision?

答:
You could store the credentials in a database.  Assuming there are multiple databases to map to your regions (local, dev, integration, etc..)

Or you could store the credentials in a configuration file.  when you create your builds you'd have to specify which configuration file to utilize.


问:
Why is there no 'subclasses-only' access modifier in Java?
In Java, there are four available access modifiers for methods:

public - any class can use this method.

protected - classes in the same package and subclasses in any package can use this method.

private - only this class can use this method.

no modifier ("package private") - only classes in the same package can use this method.

What happens often is that I want to have useful methods in a superclass, that all subclasses can use. But it wouldn't make sense for other classes to access this method, and in a sense it would break encapsulation.

So I have to declare these useful methods in the superclass public or protected, which exposes them to all other classes at least in the package. Even though they're only meant to be used by the subclasses.

Is there a reason why there isn't a subclasses-only access modifier in Java? It seems very odd to me. Am I missing something?

Also, a subclasses-only access modifier would also be useful for when you want to expose variables only to subclasses. Which to me happens a lot.

答:
This already exists.  It is protected.

You have control over what classes exist within the package.  If there is no other class in the package and a given variable or method is protected, it is 'subclasses only'.

That said, once again, you have control over what classes exist within the package.  You can chose to just not use the protected methods or variables.


答:
Because you can emulate the subclasses-only modifier by using the protected modifier and enforcing that only the parent class and its subclasses are in the same package.

It's indeed a good practice, because the packages not only help to organize big projects in terms of cohesion, but they also show that the classes in the same package might have some level of coupling.

Title: Why is there no 'subclasses-only' access modifier in Java?

Body:
In Java, there are four available access modifiers for methods:

public - any class can use this method.

protected - classes in the same package and subclasses in any package can use this method.

private - only this class can use this method.

no modifier ("package private") - only classes in the same package can use this method.

What happens often is that I want to have useful methods in a superclass, that all subclasses can use. But it wouldn't make sense for other classes to access this method, and in a sense it would break encapsulation.

So I have to declare these useful methods in the superclass public or protected, which exposes them to all other classes at least in the package. Even though they're only meant to be used by the subclasses.

Is there a reason why there isn't a subclasses-only access modifier in Java? It seems very odd to me. Am I missing something?

Also, a subclasses-only access modifier would also be useful for when you want to expose variables only to subclasses. Which to me happens a lot.


问:
Front-End Business Rules / JSON
I am working on a project that now needs business rules. One design discussed is to make API calls (based on the form we are on) which responds with business rules for form input. I am unsure if this is the best way. The business rules are in JSON, but the business rules server actually has a business rules engine (so the engine crunches the rules and spits out JSON).

Some background:

In our web app, various forms exist, such as for logging in, registering, editing a profile, etc. Maybe 25-30 forms. They are content managed.

For any of these forms, various rules exist to show or hide fields, or present error messages on the form based on logic such as a field name being too long, too short, or not meeting a regular expression. Other things such as required field validators, etc, exist.

The idea was to have everything centralized in a different environment (as mentioned above...on the business rules server).

I am concerned about making so many calls to a server to get simple rules like a first name being required, or showing or hiding a button based on if a person sells a certain number of widgets, etc.

Perhaps a better solution would be to have this rules engine publish to our server, and we just call the local server rather than make API calls from the front end each time.

What does everyone think? Is it natural to make API calls from our .net forms (using jquery) to get our rules for each form, each time?

Thanks!

答:
You will have to answer several questions in order to know what will work best. These are in no particular order.

Are your business rules static based on the question/field being shown/hidden?

If they are static, you can cache the business rules locally (on the page or server as appropriate). If they aren't, can you determine what the output difference is and then cache that?  Also, how often do the rules change?

Can the value(s) selected/entered affect another field's business rules?

If I choose a truck instead of a car, will I still be allowed to select a hatchback type of vehicle? Should an electric motor driven vehicle have a choice for numbers of cylinders for the engine?

Does your validation change based on values selected/entered?

Selecting car manufacturer A sets your VIN validation to some number of letters, followed by some number of digits, where manufacturer B has letters, numbers, a couple of glyphs, and more numbers.

Does your data change based on values selected/entered?

Cascading dropdowns are very common for this type of item; manufacturers listed in the first dropdown, models in the second.

Where will the application be run?

If it will be on your network, it is possible that your throughput will be sufficiently fast that you don't need to consider caching. You may also have caching routers between you and the business rule server that will limit the number of calls to the business rule server.

How many users will be using the application?

If this number is small enough, then the added expense of caching will probably not be worth it.

How much network overhead will the application add?

You are going to have to measure this. It will depend on more factors than I can list here easily. Ask yourself if the trade off in bandwidth is worth the difference in added complexity of your application.

Title: Front-End Business Rules / JSON


答:
Acess control can be thought of as the result of a coversation with an imaginary developer who is working with your class about the class methods and properies...

YOU: Say you want to do x, you call the method doX..
  DEV: Tell me more..what are the arguments?

This is public...

YOU: Inside doX I call ...
  DEV: Whoa, too much information, I don't care about that. I just want to know how to use it.  Tell me something else.

This is private...

YOU: When subclassing, I have doX and doY call doIt which does..
  DEV: Yeah, I gonna subclass, tell me more...

This is protected...

YOU: I'm leaving on on vacation in an hour, I'll be gone for the next 6 months. The Boss says this puppy is yours! Bye.
  DEV: Wait don't go yet, tell me everything...

This is package.

YOU: The method doItWhen is only called by this class and it hasn't changed in ten years. It...
  DEV: Whoa, we're down to 50 minutes.  Next property, and talk faster.

This is protected private...


问:
Should I omit the parameter "e" when using EventHandler<EventArgs>?
Whenever I am defining my own events, I use a pattern such as the following (which I believe is how the MSDN recommends doing it):

```<code>public class MyEventClass
{
    private bool _value; // Backing variable
    public bool Value
    {
        get { return _value; }
        set
        {
            if (value != _value) // Only raise event if value is changed/different
            {
                _value = value;
                OnValueChanged(EventArgs.Empty);
            }
        }
    }

    public event EventHandler ValueChanged; // Anything can subscribe to the event
    protected void OnValueChanged(EventArgs e) // Only this and children can invoke event
    {
        if (ValueChanged != null)
            ValueChanged(this, e);
    }
}
</code>```

Thus, the client code just needs to subscribe to the event and it automagically works.

However, it feels cumbersome to pass the EventArgs e parameter, in particular with a class that uses EventHandler to raise its events, since the base EventArgs has no data to it, only EventArgs.Empty.

Would it be considered a faux pas to change it to this?

```<code>protected void OnValueChanged()
{
    if (ValueChanged != null)
        ValueChanged(this, EventArgs.Empty);
}
</code>```

答:
Is it wrong? No.  Will it cause people to complain about your code? No.

Will it sidetrack some busy developer for a couple of minutes while he tries to find out what the parameters are and whether they will help solve his problem? Could be..

Will it make your class easier to use...?

Standards and patterns are useful because they are easily recognized and used (or ignored).  Deviating from conventions should be done for a purpose, not just because you can.  This applies whether it is bracket style, parameter names or argument list.  Do it for a reason, not just because it compiles.


答:
Java originally had such a modifier. It was written private protected but removed in Java 1.0.

I assume that was a judgment call that the extra complexity wasn't worth the cost.

Every language feature has a cost: in teaching it to new programmers; in documentation; in implementing it in the compiler, JVM, and dev tools; in reasoning about program correctness; in constraining future language evolution; and more. Language features interact with each other, potentially with N2 interactions.

What percent of Java programmers have read through the Java language spec and VM spec? I bet it's a small percentage, which argues for an even simpler language for the sake of understandability and engineering products that we can depend on

The benefit of the private protected feature was small since the package is the main unit of modularity.


问:
Find second largest element in a array?
The problem is to solve it in n+logn−2 (base 2) no of comparisons.

My algorithm is taking some extra space less then (O(n*n)). How can i reduce this extra space without increasing the complexity.

```<code>    comparisionarray=[][] (2D array )

    //a function to find the largest.
    findlargest(a,b)
       if(len(a)==1 and  len(b)==1)
          append b to array at ath index in comparisonarray.
          append b to array at bth index comparisionarray.
          return max(a,b)
       else
          return max(findlargest(1stHalfof(a),2ndHalfof(a)),findlargest(1stHalfof(b),2ndHalfof(b))

    input= input_array()
    largest=findlargest(1stHalfof(input),2ndHalfof(input))
    subarray=[array at index largest in comparisionarray]
    2ndlargest=findlargest(1stHalfof(subarray),2ndHalfof(subarray))
    print(2ndlargest)
</code>```

Edit:  It can be done in minimum n+logn−2 comparisons. That is the only condition . This answer on math.stackexchange.com proves it. It has been generalized for nth largest element

Seems that there is a solution at this link stackoverflow. But i am not sure about the extra space and time complexity.

答:
You want a http://en.m.wikipedia.org/wiki/Priority_queue of size 2. This easily generalizes to larger queues.

The usual implementation is an array form of a "heap" http://en.m.wikipedia.org/wiki/Heap_(data_structure) . (This is not a memory allocator kind of "heap".)

Title: Find second largest element in a array?


问:
Do you have to have boxing of primitives in OO language?
Is boxing of primitives required in OO languages to keep them consistent with the rest of the object system (generics etc.)?

Or is it avoidable - is it possible to avoid any additional performance cost of having both primitives and objects in a language?

One solution I can come up on the spot is having references big enough to store values of every possible primitive type.

Are there other (better) solutions and are there implemented in popular languages?

答:
VB6 included "variant" types which could store primitives or object references, so it's certainly possible.  The semantics of VB6 variant types were absolutely horrible, and I would not suggest any language try to emulate them.

Otherwise, while it might in some rare cases be useful to define an aggregate type which holds an object reference and something like an int64 whose bits could be interpreted as needed to represent any primitive type, one generally can't do anything useful with a variant type unless one knows what it's supposed to be, and if one knows what a type is supposed to be one doesn't really need a variant.  In a framework like .NET which has "real" generic types, boxing is seldom needed and in those contexts where it is needed, it would probably be more helpful to have all types receive a layer of boxing (so that a reference of type Animal which identifies a Cat, would be boxed as "Boxed reference of type Animal which identifies a Cat").


问:
Decreasing vars in Scala programs
I have been studying scala for the past week or so and the ideologies associated with it and functional programming in general. As expected, the leap from imperative to functional programming is not as easy as I had hoped. For example, I converted a programming exercise that I did in Java into Scala. What I found was that it was near impossible for me to switch from mutable variables into the Scala style of immutable vals.

For the TL;DR people, my main question is, how does one decrease the var usage in a functional program? For the sake of a use case, I'll provide some sample code:

```<code>import scala.io._
object Bowling {
  def main(args: Array[String]): Unit = {
    val input = Source.fromFile("bowling.in").getLines
    for(testCase <- input) {
      val numberOfRows = augmentString(testCase).toInt
      var index = 0
      var a = 1
      var sum = 0
      while(index < numberOfRows) {
        sum += a
        a += 4
        index += 1
      }
      println(sum)
    }
  }
}
</code>```

EDIT:
I'm accepting Karl's answer because of its conciseness though I do really appreciate Ptharien's code example and Doval's explanation of functional concepts as a whole.

答:
An immediate conversion of your sample code to "var-less", but still not all that functional, style would be the following:

```<code>import scala.io._
object Bowling {
  def main(args: Array[String]): Unit = {
    val input = Source.fromFile("bowling.in").getLines
    for(testCase <- input) {
      val numberOfRows = augmentString(testCase).toInt
      val (_, sum) = 1 to numberOfRows foldr ((1, 0)) { (_, v) => v match {
        case (a, sum) => (a + 4, sum + a)
      } }
      println(sum)
    }
  }
}
</code>```

Making a more actually functional version would be a much farther-reaching transformation, and would probably depend on exactly what the point of the program is.  I'll put this answer out there as is, and work on an edit that hopefully demonstrates this more complete refactoring.

EDIT:  Here is how I would write this program more generally functionally (while still remaining within the confines of Scala's standard library):

```<code>import scala.io._
object Bowling extends App {
  Source.fromFile("bowling.in").getLines map { _.toInt } map { testCase =>
    1 to testCase foldr ((1, 0)) { (_, v) => v match {
      case (a, sum) => (a + 4, sum + a)
    } }
  } map { _._2 } foreach { println _ }
}
</code>```

Don't worry about understanding how to do this all at once; it takes practice, and a week or two is nowhere near enough time to understand a completely different programming paradigm than you're used to.  Expect to take several months before you feel like you actually understand the basics of functional programming, although you can certainly write Scala in the "Java minus semicolons" style in the interim.  :)

Title: Decreasing vars in Scala programs

Body:
An immediate conversion of your sample code to "var-less", but still not all that functional, style would be the following:

import scala.io._
object Bowling {
  def main(args: Array[String]): Unit = {
    val input = Source.fromFile("bowling.in").getLines
    for(testCase <- input) {
      val numberOfRows = augmentString(testCase).toInt
      val (_, sum) = 1 to numberOfRows foldr ((1, 0)) { (_, v) => v match {
        case (a, sum) => (a + 4, sum + a)
      } }
      println(sum)
    }
  }
}

Making a more actually functional version would be a much farther-reaching transformation, and would probably depend on exactly what the point of the program is.  I'll put this answer out there as is, and work on an edit that hopefully demonstrates this more complete refactoring.

EDIT:  Here is how I would write this program more generally functionally (while still remaining within the confines of Scala's standard library):

import scala.io._
object Bowling extends App {
  Source.fromFile("bowling.in").getLines map { _.toInt } map { testCase =>
    1 to testCase foldr ((1, 0)) { (_, v) => v match {
      case (a, sum) => (a + 4, sum + a)
    } }
  } map { _._2 } foreach { println _ }
}

Don't worry about understanding how to do this all at once; it takes practice, and a week or two is nowhere near enough time to understand a completely different programming paradigm than you're used to.  Expect to take several months before you feel like you actually understand the basics of functional programming, although you can certainly write Scala in the "Java minus semicolons" style in the interim.  :)


问:
Previous programmer died unexpectedly; how do I pick up where he left off?
I have recently taken a job finishing the development of a .Net application. The delivery of the application is two years behind schedule. The previous developer died before I had a chance to meet him.

I have been given copies of directories from the deceased's laptops. There are many directories of code (including seemingly duplicate directories), two SQL Server databases, and some Visual Studio project files. A quick wc shows about 300,000 lines of .Net code.

There is no source control, no documentation, no licenses for third party controls, no unit tests, no build scripts, no release scripts, no install, and no real software development process to speak of. Maybe some of these things did exist, but I can't find them.

I am an experienced software developer, but I have never been in a situation quite like this. Lastly, I have budget to buy tools as necessary, but not more staff.

What would be your 90-day plan to get this project moving again? Obviously I have months or years of work ahead of me; what should be my priorities?

答:
I have a small history of taking control back of loosely managed projects and my approach is the same every time

Integrate progressively from scratch. Take what you understand from what the project do. Take with you the best code snippets and mock everything else. Once you're looking good enough, trash old code.

You know you don't have enough time to read everything, you know you don't want everything, you just have to do what you can from what you can start of. Try to figure out what 90% of this have to burn.

Also ask around you about the code, sometimes code knowledge can pop out, you never know. This man had to talk to people, sometimes. Anything you can learn is potential help for refactoring.


问:
project with 2 types of interfaces performing different jobs, should they use the same BLL and DAL?
I am working on a project that has two interface (web and desktop), they are not performing the same tasks but they use the same BLL and DAL, the web part using 100% of the BLL and DAL, while the desktop only needs to know about 20% of the BLL and DAL.

Do you think it is a good idea to let the desktop use the same BLL and DAL as the web, which consequently will lead to distributing thos BLL and DAL with the desktop application? Or you think I'd better create new BLL and DAL projects just to serve the desktop app? But in this case I will fall in the trap of maintaining two copies of the same code!

答:
Perhaps your problem its that you have only one model, big applications are normally composed or various decoupled models, in Domain Driven Design this concept is called Bounded Context.

In a system designed like that your desktop application probably use several of this BC's and your web application use all, this way you can distribute the desktop app with only the needed BC's.

Off course duplication its the worse you can do, better think in ways of modularize your model and distribute only the modules (BC's) you really need in each case, but its much better your current situation than the situation of having 20% of your code duplicated.


问:
How are the skills used in typical interview questions applied in the real job?
For SQL and C# app dev jobs, the interviewers usually ask questions about tree,graph and linked list traversals using pure C and pointers.  In the 3 years I've spent in my job, I've never had to actually

find the path to the 1st node to the right of a given node which is a multiple of
  the given node

for example

I can see that these skills might be used in jobs where you need to write compilers, drivers and work on the OS kernel.  Other than those, where else are these skills used?

答:
They're not. Many interviews are done by people who don't know how to look for skillful developers, and don't know what questions they should or shouldn't ask.

Most interviewers don't ask technical questions at all, and are more concentrated on meaningless but measurable things, such as the number of projects you've participated to (more is better for those interviewers) or the college degree (higher is better for them). They're happy to hire a person who wasted five years in college learning nothing and then spent ten years doing dozens of e-commerce websites, but they won't hire a person who abandoned college after a few years and was working on a few large technically challenging projects.

Asking at least theoretical questions is better then asking none. This has a benefit of verifying that the person has enough theoretical knowledge, and is not a coder who may have a few years experience with programming, but doesn't really understand what's happening under the hood. Developers who don't have this theoretical knowledge usually ¹ don't know the difference between a list, a linked list a lookup or a hash set, and use them interchangeably.

Good (technical) questions, bad questions

During interviews, you may encounter questions ranging from very good to extremely bad:

(Harmful) "What is the length in lines of the longest working program you have written in that language?"

This question is plainly wrong. I already explained why in another answer. The company where interviewers ask such questions has strong chances to evaluate the productivity of developers in LOC/month. If I have to give an advice: you don't need such job.

This example is different from meaningless but measurable things I've quoted at the beginning of my answer. Here, the interviewer also shows that he doesn't have even the most basic understanding of the metrics by picking one which is well-known for being harmful.

(Bad) "Who is Dennis Ritchie?"

Having at least some culture is indeed very useful, but asking those question misses the point. If the company searches for talented developers who are able to handle software development projects and write code, the fact that they don't know the name of the person who created C and Unix shouldn't matter too much.

(Good) "What are the new features of .NET 4.5?"

This question is much more interesting than the one about Dennis Ritchie. If the candidate can't talk about new features in .NET 4.5, why does he calls himself C# developer? The lack of such knowledge:

Shows that the person may not be really interested in neither the programming language, nor the .NET community,

Indicates that the person may lack some crucial knowledge about the features of C#/.NET other developers use if not daily, at least frequently.

See also the answer by Jerry Coffin which contains a more detailed analysis of this sort of questions.

(Average) "Which one is faster, SSD or RAM?"

This might be useful and shows if the person has enough hardware knowledge, but still, a candidate who can't answer this question shouldn't be rejected.

(Average) "How stack and queue are implemented?"

This is the sort of questions you talk about. They are theoretical, maybe even too theoretical, but knowing what's happening under the hood may help writing better code.

I wouldn't reject a candidate who can't answer this question, but will check more carefully if he really knows the stuff, for example by asking a related but less theoretical question:

(Good) "How can you walk through a tree without using recursion?"

If the candidate answers this question, talking about FILO/FIFO and about the benefits and drawbacks of using a stack versus a recursion for tree traversal, it doesn't really matter that he was unable to answer the previous question.

Asking this question is also a good way to detect candidates who spent years doing their CS degree, but have no field experience.

How to ask good technical questions?

kojiro's comment is interesting and deserves a longer answer:

Sometimes you need to hire someone precisely because they should know more about a subject than you, so by definition you're underqualified to do the interview. You can't reliably get help even doing the interview for the same reason. The best you can do is try to ask questions based on wherever your understanding intersects with the problem domain and hope you get lucky.

Finding good questions may be challenging, especially when you hire your very first developer or when you hire a developer who is expected to be more skilled than all the developers who actually work in the company.

Here are three hints which can help:

Find a friend/colleague you believe to be skilled and ask him to do the reviews. This requires a lot of trust, but can benefit your company a lot.

Find a consultant you believe to be skilled and ask him to assist you or do the technical part of the interview.

Type " interview questions" in Google. It works pretty well, and usually explain possible answers. Example:

Python: those ten questions seem quite good. They are maybe a bit basic, but will help filtering 95% candidates you don't want to hire anyway.

SQL by Dave Pinal, excellent as usual.

C#: a bit too basic, but again, they'll filter 95% candidates,

JavaScript: the questions are more open-ended, which may not be the good thing for technical questions if you want the interview to be short and keep more time for open-ended non-technical questions. The list still helps filtering easily the candidates who don't understand basic concepts in JavaScript.

The drawback of this approach is that the candidate may use the same technique in order to train for the interview. If he reviewed every question of the first website he found in Google, he may score well, without actually having the required skills.

¹ There are some developers who won't be able to explain what a B-tree is (aside that it's "some data structure"), but are still able to develop correctly.


答:
Theoretical objects are used for convenience because you are supposed to know what an average tree/graph/list implementation is about thus know how to solve a random traversal problem, but these questions are not about the theoretical objects at all.

They are about being able to work with abstracted model, understanding an abstract problem and solve it with an algorithm of whatever kind. This is pure development skill there, so it sure counts. This is why these question makes sense, not because they are supposed to be accurate real life situations.

Title: How are the skills used in typical interview questions applied in the real job?

Body:
For SQL and C# app dev jobs, the interviewers usually ask questions about tree,graph and linked list traversals using pure C and pointers.  In the 3 years I've spent in my job, I've never had to actually

find the path to the 1st node to the right of a given node which is a multiple of
  the given node

for example

I can see that these skills might be used in jobs where you need to write compilers, drivers and work on the OS kernel.  Other than those, where else are these skills used?


答:
The skills required to do these tasks are rarely important. The skills demonstrated in the approach to answering the question and in the subsequent dialogue are the whole point.

When I interview developers I look for (a) smart (b) gets things done (c) will fit in. There is a base level of technical knowledge required to fill any role, which has to go with a willingness to learn and acquire new skills. The interview is about checking those boxes.

My preference is to read code written by an applicant. I don't like canned interview questions, but they provide something to talk about in the absence of code. I prefer to ask about RAII or IOC or the implementation of IDisposable rather than list and collections, but anything will do as long as we can get it technical enough.

The worst fear of the interviewer is of hiring someone who actually doesn't know much about coding. You have to talk about something other than work experience to weed out the fakes.


问:
How to divide OO project into packages?
I'm a hobbyist programmer working on my own projects. I use Java.

Until recently my average project was only 1000 LoC. My latest project however is bigger and is starting to exceed 1500 LoC. I estimate it will reach about 2000.

I've never organized my classes into packages. All of them were always in the default package and it worked fine.

However as my projects grow and the amount of classes gets bigger, I'm starting to feel unorganized.

My question is: how exactly does one divide his/her classes into packages? What I mean is, by what criteria do you divide classes?

Is it by the 'part' of the app? Aka GUI classes in one package, business logic in the other, networking, etc.? Or maybe high-level classes versus lower level classes? Aka classes that do concrete, specific work in packages of their own, and 'architectural' classes that tie it all together in their own packages? Or maybe you simply divide by the criteria of 'what feels right and organized' specifically to you?

For example, I'm working on an app that makes music. It is basically divided into two main systems: the system that makes the music, and the system that displays the GUI and controls the other system (i.e. a button press in that system activates the other system).

The music-creation system is also divided into two systems: for creating melodies and for creating chord progressions. And the chord-progression generation part, among other things contains a group of classes that serve as interchangable algorithms for a Strategy pattern involved (i.e. classes used for a specific implementation detail).

There are of course higher-level and lower-level classes involved in every system. For example the progression-generation system contains a ProgressionGenerator class, which is high-level and ties the entire system together. It also has a Chord class which is far more low level (i.e. takes care of playing specific notes).

The way I would organize this into classes is like so:

The music-creation system into one package, the GUI system that controls the other system into another package.

Than the melody-creation into a subpackage of the music-creation pakcage and the progression-creation into a different subpackage.

And inside the progression-creation subpackage, another subpackage contataing the classes used for that Strategy pattern involved somewhere in that system.

Does this sound like a good approach for organizing things into packagages? By what criteria do you divide the classes into packages? By 'what feels right', or by more technical terms?

答:
There is no one answer to your question and it depends on the architecture of your application. This question might get closed.

2000 Lines of code is actually pretty small. How you divide your program into classes is the same question as how do I do object oriented programming. You should probably start with Wikipedia and then buy a book on the subject or find a course online.

In terms of guidelines you could start with SOLID and Packaging Principles

From Packaging Principles, the Reuse-release equivalence principle (REP) states:

REP essentially means that the package must be created with reusable classes.

That is, If you don't need to reuse, then don't need to package them independently from your application.

Title: How to divide OO project into packages?


答:
In general, I tend to organize by responsibility/function. But it totally depends on your concrete project, and architecture, and there is no single definite answer/guideline here. Not to mention that personal taste also plays a large role here.

My suggestion: Look how other people/organizations are doing it. Take advantage of Open Source. Look for Java projects on github, for example, and browse their source. You'll get a feel for different approaches, and can decide which ones you like.

Title: How to divide OO project into packages?

Body:
I'm a hobbyist programmer working on my own projects. I use Java.

Until recently my average project was only 1000 LoC. My latest project however is bigger and is starting to exceed 1500 LoC. I estimate it will reach about 2000.

I've never organized my classes into packages. All of them were always in the default package and it worked fine.

However as my projects grow and the amount of classes gets bigger, I'm starting to feel unorganized.

My question is: how exactly does one divide his/her classes into packages? What I mean is, by what criteria do you divide classes?

Is it by the 'part' of the app? Aka GUI classes in one package, business logic in the other, networking, etc.? Or maybe high-level classes versus lower level classes? Aka classes that do concrete, specific work in packages of their own, and 'architectural' classes that tie it all together in their own packages? Or maybe you simply divide by the criteria of 'what feels right and organized' specifically to you?

For example, I'm working on an app that makes music. It is basically divided into two main systems: the system that makes the music, and the system that displays the GUI and controls the other system (i.e. a button press in that system activates the other system).

The music-creation system is also divided into two systems: for creating melodies and for creating chord progressions. And the chord-progression generation part, among other things contains a group of classes that serve as interchangable algorithms for a Strategy pattern involved (i.e. classes used for a specific implementation detail).

There are of course higher-level and lower-level classes involved in every system. For example the progression-generation system contains a ProgressionGenerator class, which is high-level and ties the entire system together. It also has a Chord class which is far more low level (i.e. takes care of playing specific notes).

The way I would organize this into classes is like so:

The music-creation system into one package, the GUI system that controls the other system into another package.

Than the melody-creation into a subpackage of the music-creation pakcage and the progression-creation into a different subpackage.

And inside the progression-creation subpackage, another subpackage contataing the classes used for that Strategy pattern involved somewhere in that system.

Does this sound like a good approach for organizing things into packagages? By what criteria do you divide the classes into packages? By 'what feels right', or by more technical terms?


答:
I am not sure if this would be an answer to everybody, but it solved the issue for me.

I used the same DLL and BAL layers for the two GUIs, then used an assembly pruner application to prune the classes that were not used by the desktop application out of the DAL and BLL assemblies.

Example of these pruning application is RegGate SmartAssembly that offers the pruning feature among many other features.

Title: project with 2 types of interfaces performing different jobs, should they use the same BLL and DAL?

Body:
I am working on a project that has two interface (web and desktop), they are not performing the same tasks but they use the same BLL and DAL, the web part using 100% of the BLL and DAL, while the desktop only needs to know about 20% of the BLL and DAL.

Do you think it is a good idea to let the desktop use the same BLL and DAL as the web, which consequently will lead to distributing thos BLL and DAL with the desktop application? Or you think I'd better create new BLL and DAL projects just to serve the desktop app? But in this case I will fall in the trap of maintaining two copies of the same code!


问:
Accessing a remote server from desktop application
Web applications (.jsp / Java) have the advantage that they can be run from any client browser by putting a single URL into the address bar, and off you go.
However, the average web application is slow, clunky, and maintaining the code behind it is hell on earth.

Conversely, a typical desktop application (Java / c#) can have a slick interface, snappy response, and the code behind it is often much neater, compartmentalised, and often a pleasure to work with.

Is there a way or technique to connect to a remote server through a Java / c# desktop application, that can be distributed to any Windows computer, that doesn't first require the computer to connect to the remote server through a VPN, as a separate user procedure? (Usernames /passwords / connection details will obviously need to be stored in a config file associated with the application).

The remote server would be hosting a 'communal'(?) SQLServer database, and I suppose, possibly some files.

答:
Yes you can.

You can set up a webservices API that connects to your database, thus keeping the database connection secure and wholly within your network. This is instead of the web server that would normally serve the web site to the users.

The desktop clients then connect to the webservices to communicate with the database. You could have the standard CRUD methods for your objects or you could wrap them up in more intelligent layers that do validation and verification of the data.

You just need to publish the desktop client installer on the web somewhere where everyone (or where at least those you want access) can see it. You can prevent unauthorised access quite easily - you either generate the user accounts and mail out the details or you vet the requests for access as they come in.

You can even make the application self updating so that the user is always on the latest version.


答:
Organize and model your classes so you can GET THE BENEFITS of OOP and SOLID, etc.

Encapsulation and data hiding.  There are many ways to organize things into classes that are tightly bound to each other and still satisfy the 'official' definition of OOP.  OOP languages and design principles make it easier and give you the tools to achieve encapsulation and data hiding, and it fact make it difficult to create quite such a tightly bound, dependent mess.  Try to understand WHY you would want to do it the OOP way, by understanding, WHAT the OOP methods might give you, in the future.

Polymorphism and reuse.  Again there are a million way to extract some abstraction out of almost any 'thing' or concept.  The point of OOP is that you can achieve a benefit from this philosophizing.  You can get re-use, generalization, less code for more functionality.  Less maintenance, etc.

Those are some good ones.  Look at the rest of the OOP and SOLID and decide whether you can really achieve a benefit, and let that lead you to a natural organization strategy.

Also, there are many times when OOP principles do not really help you; at least in the current size and maturity of your product;  they simply make things more complicated.  But this adherance, 'in principle', may make your product more future-proof.  A good example would be something like Dependency-Inversion/Injection, or maybe something like Factory patterns.  Often overkill, but when you app grows, you thank the heavenly stars you put that hook (DI, Factory) in there in version 1.

Title: How to divide OO project into packages?


问:
Is allocating objects from a memory-pool a security anti-pattern?
In the wake of the heartbleed bug, OpenSSL has been rightly critizised for using its own freelist.  With plain-old malloc, the bug would have almost certainly been found long ago.

However, some kind of malloc wrapping is actually very common.  For example when I have a big object that owns many small, fixed sized objects, I often allocate them from an array.

```<code>/* BigObj is allocated with `malloc`, but LittleObj using `alloc_little`. */
typedef struct {

    /* bigObj stuff here */

    int nlittle;
    LittleObj littles[MAX_LITTLE];
} BigObj;

LittleObj *alloc_little(BigObj *big)
{
    if(big->nlittle == MAX_LITTLE)
        return NULL;
    return = big->littles + big->nlittle++;
}
</code>```

alloc_little is faster than malloc(), but the main reason is simplicity.   There is no free_little to call, because the LittleObjs just remain valid until the BigObj is destroyed.

So is this an anti-pattern?  If so, can I mitigate the risks, or should I just abandon it? Similar questions go for any kind of memory pool, such as GNU Obstacks and the talloc used in Samba.

答:
No, absolutely not. And proposing malloc() as the solution is just terrible.

Complex pieces of system software almost always have special memory requirements, and very often the solution involves implementing one or more customer memory allocators. Reusing objects off a free list is one good strategy. Others include memory pools, slab allocators, stack allocators, reference counting and even garbage collection.

C/C++ happens to be an exceptionally fine tool for implementing memory allocators, but it provides very little protection from bad decisions or bad execution. The mistake in OpenSSL was not the decision to use a free list, but doing it so badly.

I would say the main risk mitigation strategy, after making good choices and writing good code, is exhaustive unit testing, including failure modes and performance. Don't leave home without it.

OwnerDisplayName: Adrian Ratnapala


答:
You're asking about primitive types and objects, but I don't think that's a useful distinction here. Instead, you should be thinking about reference types and value types:

Value types: always exactly of the specified type (can't be a derived type instead); can't use virtual function dispatch; lifetime tied to the scope of the variable (usually allocated on the stack)

Reference types: can be the specified type or a derived type; can use virtual function dispatch; lifetime not tied to the scope of the variable (usually allocated on the heap)

If you look at these differences, you realize that both kind of types have some merit: value types are more performant, while reference types are more flexible, especially if you want to use OOP features like inheritance or virtual functions.

This is why many languages (including C++, C# and Java) offer both of them in one form or another (though the form varies widely).

Now we have two kinds of types, but we would also like to have a unified type system. And that means having a type, where variables of this type can contain values of any type. This requirement means that the type (called Object in C# and Java) has to be a reference type. And to convert a value type to this Object type, you have to “box” it: create a copy of the value that acts like a reference type.

To sum up: a language has to support boxing, if you want to have reference types, value types and a unified type system.

Title: Do you have to have boxing of primitives in OO language?

Body:
Is boxing of primitives required in OO languages to keep them consistent with the rest of the object system (generics etc.)?

Or is it avoidable - is it possible to avoid any additional performance cost of having both primitives and objects in a language?

One solution I can come up on the spot is having references big enough to store values of every possible primitive type.

Are there other (better) solutions and are there implemented in popular languages?


答:
Read some of Joel's answers below.

Especially note something like Schmiel the painter.  On the job, you may never have to rewrite a linked list, but you certainly should know under the hood how it works, so that you can avoid Schmiel.

Basically, if you are going to the doctor, you would want that doctor to have studied anatomy.  Even though her is just prescribing you some AntiHistamine, a doctor will have learned in medical school that certain medications are bad for people with a 'chronic fractios diamadabada to the inferior femur' or whatever.  This kind of in-depth knowledge of EVERYTHING in that specialty can sometimes make the different between life and death, and in Information Technology between life and death of the product, or a job.

http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html

http://www.joelonsoftware.com/articles/fog0000000319.html

"...spend at least a semester getting close to the machine or you'll never be able to create efficient code in higher level languages. ..."

"...you're programming based on superstition, as far as I'm concerned: a medical doctor who doesn't know basic anatomy, passing out prescriptions based on what the pharma sales babe said would work."

http://www.joelonsoftware.com/articles/CollegeAdvice.html


答:
The reality is that most of the day-to-day tasks most of the developers do in their professional life are trivial; That means some of the questions you face in a job interview might never face you in reality, but that doesn't mean there is no point for asking those questions.

Let say there is an open position in your company and you're currently interviewing people. You have already 20-30 developers in the queue. So how would you choose the best candidate for that position? Let say the most challenging task they have to done in that job is to open a file from file system, read the data line by line, slightly modify it and put it back in to the original file.

Are you going to ask them how would you open a file? I bet you can't see a really big difference between the answers. So you have to come up with a solution to distinguish between the developers who only know how to open a file and those how can develop a bad-ass real-time application. Even tho you don't want them to build such an application, but still you want to hire the best candidate.

Like any other thing in our life, there are some points that you realize you need to go and learn more. If you don't know what is a linked-list, to me as a programmer, that literally means you haven't really reached that point in your professional life to feel that you need to go and learn that specific thing. Why? Simply because you never involved in a project big enough to require you to improve your skills up to that level. If you're in an entry-level, you could say I don't really have any working experience for this specific job, but still if you know it that means you're self-motivated enough to put yourself on the cut above average at least.


问:
How to handle unexpected schema changes to production database
Is it a common or normal practice to encounter schema changes, especially renamed or removed columns, in a production database, without having been notified of the change?  If unexpected schema changes are anticipated in the production database, how are they guarded against, other than basic exception handling?

I've worked mainly with credit union software, DoD software, high volume e-commerce web applications, real estate systems, robotics, and more recently CMMS, GIS, and SCADA systems.  Although the '90s and early 2000s were more of the wild west, everything I have been involved with over the last 10 years or so has required change management.  Modifications to a production database without change control is not allowed by policy and by security controls.

Comments in the accepted answer to this question - Why is “Select * from table” considered bad practice make me wonder how much of this is academic and how much is reality.

答:
If I may be so bold ;)

The problem isn't really about unexpected schema changes to production, though that's certainly a symptom.

In reality it is:

"Why aren't different members of my organization communicating about changes that affect each other"

Once you view it that way then it makes more sense to look at:

current processes of code and database changes

current process for notifying others

current process for running tests for such changes

current methods used to communicate (email, IM, Project tracker, etc.)

etc.


答: These questions are for screening out people that can't program. Sometimes people who can't program but know a lot of trivia apply for development jobs, and having them write something that's useful and non-trivial is too time-consuming for an interview.</p>


问:
How long does a Comp Sci degree last?
I keep hearing from people that if I don't become a programmer soon after graduation my degree will be a useless piece of paper, they claim it will become outdated.  I kind of find this hard to believe considering what I was taught at a fairly good school has been standard practice for some time.

So is this a true belief in industry?  That somehow I become less desirable after a year or two, even though the graduates who comes after me pretty much get the same identical education.

答:
Nonsense

ask them why they think that

ContentLicense: CC BY-SA 2.5

Title: How long does a Comp Sci degree last?

Body:
Nonsense

ask them why they think that


问:
Should you always pass the bare minimum data needed into a function in cases like this
Let's say I have a function IsAdmin that checks whether a user is an admin. Let's also say that the admin checking is done by matching user id, name and password against some sort of rule (not important).

In my head there are then two possible function signatures for this:

```<code>public bool IsAdmin(User user);
public bool IsAdmin(int id, string name, string password);
</code>```

I most often go for the second type of signature, thinking that:

The function signature gives the reader a lot more info

The logic contained inside the function doesn't have to know about the User class

It usually results in slightly less code inside the function

However I sometimes question this approach, and also realize that at some point it would become unwieldy. If for example a function would map between ten different object fields into a resulting bool I would obviously send in the entire object. But apart from a stark example like that I can't see a reason to pass in the actual object.

I would appreciate any arguments for either style, as well as any general observations you might offer.

I program in both object oriented and functional styles, so the question should be seen as regarding any and all idioms.

答:
Disclaimers:

For my reply, I'm going to focus on the style issue and forget about wether an ID, login and plain password is a good set of parameters to use, from the security point of view.  You should be able to extrapolate my answer to whatever basic set of data you're using to figure out about the user's privileges...

I also consider user.isAdmin() to be equivalent to IsAdmin(User user).  That's a choice for you to make.

Reply:

My recommendation is to either user only:

```<code>public bool IsAdmin(User user);
</code>```

Or use both, along the lines of:

```<code>public bool IsAdmin(User user); // calls the private method below
private bool IsAdmin(int id, string name, string password);
</code>```

Reasons for the public method:

When writing public methods it's usually a good idea to think about how they will be used.

For this particular case, the reason why you'd usually call this method is to figure out if a certain user is an administrator.  That's a method you need.  You really don't want each caller to have to pick the right parameters to send over (and risk mistakes due to code duplication).

Reasons for the private method:

The private method receiving only the minimum set of required parameters can be a good thing sometimes.  Sometimes not so much.

One of the good things about splitting these methods is that you can call the private version from several public methods in the same class.  For example if you wanted (for whatever reason) to have slightly different logic for Localuser and RemoteUser (maybe there's a setting to turn on/off remote admins?):

```<code>public bool IsAdmin(Localuser user); // Just call private method
public bool IsAdmin(RemoteUser user); // Check if setting is on, then call private method
private bool IsAdmin(int id, string name, string password);
</code>```

Additionally, if for any reason you need to make the private method public... you can.  It's as easy as just changing private to public.  It may not seem like that big of an advantage for this case, but sometimes it really is.

Also, when unit-testing you'll be able to make much more atomic tests.  It's usually very nice not to have to create a full user object to run tests on this method.  And if you want full coverage, you can test both calls.

Body:
Disclaimers:

For my reply, I'm going to focus on the style issue and forget about wether an ID, login and plain password is a good set of parameters to use, from the security point of view.  You should be able to extrapolate my answer to whatever basic set of data you're using to figure out about the user's privileges...

I also consider user.isAdmin() to be equivalent to IsAdmin(User user).  That's a choice for you to make.

Reply:

My recommendation is to either user only:

public bool IsAdmin(User user);

Or use both, along the lines of:

public bool IsAdmin(User user); // calls the private method below
private bool IsAdmin(int id, string name, string password);

Reasons for the public method:

When writing public methods it's usually a good idea to think about how they will be used.

For this particular case, the reason why you'd usually call this method is to figure out if a certain user is an administrator.  That's a method you need.  You really don't want each caller to have to pick the right parameters to send over (and risk mistakes due to code duplication).

Reasons for the private method:

The private method receiving only the minimum set of required parameters can be a good thing sometimes.  Sometimes not so much.

One of the good things about splitting these methods is that you can call the private version from several public methods in the same class.  For example if you wanted (for whatever reason) to have slightly different logic for Localuser and RemoteUser (maybe there's a setting to turn on/off remote admins?):

public bool IsAdmin(Localuser user); // Just call private method
public bool IsAdmin(RemoteUser user); // Check if setting is on, then call private method
private bool IsAdmin(int id, string name, string password);

Additionally, if for any reason you need to make the private method public... you can.  It's as easy as just changing private to public.  It may not seem like that big of an advantage for this case, but sometimes it really is.

Also, when unit-testing you'll be able to make much more atomic tests.  It's usually very nice not to have to create a full user object to run tests on this method.  And if you want full coverage, you can test both calls.


问:
Being a good mentee - a protégé
The complement of the Being a good mentor question.

I work with many very senior people that have vast amounts of knowledge and wisdom in Software, Engineering and our business domain.

What are some tips for gaining as much knowledge from them?  I don't want to take up too much of their time, but also want to take full advantage of this since it really could help develop my skills.

What are some good questions to get the conversation rolling in a sit down mentor/mentee session?  Some of the people providing mentorship have little experience in this area, so it would help to be able to lead some of these discussions.

答:
Don't take what they say for granted.  Question all of their advice and (politely) point out any potential problems you see in it.  More experienced programmers make mistakes and have biases just like everyone else.  A good mentor will be patient with you and won't get upset at you for this.

Besides that, the why is more important than the what.  Most bits of advice have exceptions, and you won't learn how to handle those exceptions without knowing why they exist.

And don't stop with your mentor.  Treat managers and other programers the same way.  If people get frustrated with this, ask yourself:  what are they afraid of?

The important thing is not to stop questioning. Curiosity has its own reason for existing. One cannot help but be in awe when he contemplates the mysteries of eternity, of life, of the marvelous structure of reality. It is enough if one tries merely to comprehend a little of this mystery every day. Never lose a holy curiosity.

  - Albert Einstein

Title: Being a good mentee - a protégé


答:
The general approach is instead of mutating a variable in a loop, put the values into collections and run a series of operations on those collections.  Note that most of the time, functional algorithms don't need index variables.  Look for mathematical relationships that allow you to factor those out.  For example:

```<code>val sums = for(testCase <- input) yield {
  val numberOfRows = testCase.toInt
  val a = 1 until numberOfRows * 4 by 4
  a.sum
}
sums foreach println
</code>```

Just because it's a series of operations on a collection doesn't mean you have to cram all the operations together one after another.  Don't forget to break up lines, name intermediate results, and use named functions instead of lambdas where appropriate.  The compiler essentially optimizes out numberOfRows and a, but putting them in there adds a lot of readability for humans.

Don't avoid for comprehensions just because of their superficial resemblance to mutated for loops.  They are often the key to better readability.

Note I moved the println to outside the for comprehension.  Isolating side effects like that can often make it easier to see a pure functional solution for the rest of the problem.

Also, as an aside, you don't need the augmentString.  It is implicitly added for you.

Title: Decreasing vars in Scala programs

Body:
I have been studying scala for the past week or so and the ideologies associated with it and functional programming in general. As expected, the leap from imperative to functional programming is not as easy as I had hoped. For example, I converted a programming exercise that I did in Java into Scala. What I found was that it was near impossible for me to switch from mutable variables into the Scala style of immutable vals.

For the TL;DR people, my main question is, how does one decrease the var usage in a functional program? For the sake of a use case, I'll provide some sample code:

```<code>import scala.io._
object Bowling {
  def main(args: Array[String]): Unit = {
    val input = Source.fromFile("bowling.in").getLines
    for(testCase <- input) {
      val numberOfRows = augmentString(testCase).toInt
      var index = 0
      var a = 1
      var sum = 0
      while(index < numberOfRows) {
        sum += a
        a += 4
        index += 1
      }
      println(sum)
    }
  }
}
</code>```

EDIT:
I'm accepting Karl's answer because of its conciseness though I do really appreciate Ptharien's code example and Doval's explanation of functional concepts as a whole.

Body:
The general approach is instead of mutating a variable in a loop, put the values into collections and run a series of operations on those collections.  Note that most of the time, functional algorithms don't need index variables.  Look for mathematical relationships that allow you to factor those out.  For example:

val sums = for(testCase <- input) yield {
  val numberOfRows = testCase.toInt
  val a = 1 until numberOfRows * 4 by 4
  a.sum
}
sums foreach println

Just because it's a series of operations on a collection doesn't mean you have to cram all the operations together one after another.  Don't forget to break up lines, name intermediate results, and use named functions instead of lambdas where appropriate.  The compiler essentially optimizes out numberOfRows and a, but putting them in there adds a lot of readability for humans.

Don't avoid for comprehensions just because of their superficial resemblance to mutated for loops.  They are often the key to better readability.

Note I moved the println to outside the for comprehension.  Isolating side effects like that can often make it easier to see a pure functional solution for the rest of the problem.

Also, as an aside, you don't need the augmentString.  It is implicitly added for you.


问:
How does I/O work for large graph databases?
I should preface this by saying that I'm mostly a front end web developer, trained as a musician, but over the past few years I've been getting more and more into computer science.

So one idea I have as a fun toy project to learn about data structures and C programming was to design and implement my own very simple database that would manage an adjacency list of posts. I don't want SQL (maybe I'll do my own query language? I'm just having fun). It should support ACID. It should be capable of storing 1TB let's say.

So with that, I was trying to think of how a database even stores data, without regard to data structures necessarily. I'm working on linux, and I've read that in that world "everything is a file," including hardware (like /dev/*), so I think that that obviously has to apply to a database, too, and it clearly does--whether it's MySQL or PostgreSQL or Neo4j, the database itself is a collection of files you can see in the filesystem.

That said, there would come a point in scale where loading the entire database into primary memory just wouldn't work, so it doesn't make sense to design it with that mindset (I assume). However, reading from secondary memory would be much slower and regardless some portion of the database has to be in primary memory in order for you to be able to do anything with it. I read this post:

Why use a database instead of just saving your data to disk?

And I found it difficult to understand how other databases, like SQLite or Neo4j, read and write from secondary memory and are still very fast (faster, it would seem, than simply writing files to the filesystem as the above question suggests). It seems the key is indexing. But even indexes need to be stored in secondary memory. They are inherently smaller than the database itself, but indexes in a very large database might be prohibitively large, too.

So my question is how is I/O generally done with large databases like the one I described above that would be at least 1TB storing a big adjacency list? If indexing is more or less the answer, how exactly does indexing work--what data structures should be involved?

答:
This is hard…

To read a block from disk takes a long time, even on a SSD reading a block takes time.   However a block can hold many objects and links to other objects.   So you wish to put object that tend to get accessed at the same time on the same disk/ssd block.

A long time ago I worked on a system used for map production, that stored roads, houses etc as object with links between them.    We created our object ID using prefix that was based on the graphical location of the object (using a gray code), and then stored then in a B+ tree.

(A normal database will be all houses in one table, all roads in anther table, etc.   It will then try to put each table onto a different section of disk.)


问:
Why was REST web srevice named REST?
What does the word Representational State Transfer (REST) mean actually ? Now I don seem to find any relation between its naming and its working, I have understood that it is a architectural style for programming web service and I've read all the hush hush stuff but can't find a reason behind its naming.

What is Representational ? Who's State? and What do we Transfer?

答:
You'll need to ask the guy who came up with the concept of REST, Roy Fielding, or read his published thesis that forms the description of REST with respect to the web.

Its probably best to start at the top and work your way through it.

What do we transfer - a representation of the resource.

In short, we don't transfer an actual object but a representation of it in some form (eg a html table to represent a database table).

A relevant quote is:

Depending on the message control data, a given representation may
  indicate the current state of the requested resource, the desired
  state for the requested resource, or the value of some other resource,
  such as a representation of the input data within a client's query
  form, or a representation of some error condition for a response. For
  example, remote authoring of a resource requires that the author send
  a representation to the server, thus establishing a value for that
  resource that can be retrieved by later requests.

Title: Why was REST web srevice named REST?


答:
There's a couple of insights that will ease your transition from imperative programming to functional programming:

Mutation of some value x can be replaced with creating a modified copy of x. There are persistent versions of most data structures that can do this efficiently by copying only the parts of the structure that changed and sharing the rest.

Loops can be replaced with recursive functions. On languages with tail call optimization, tail recursion won't blow the stack because the compiler can rewrite it as a loop under the hood.

A function that depends on a free variable (i.e. a variable that's not a formal parameter of the function) can be converted into a function that takes the current value of that variable as an argument.

We can combine all 3 rules to rewrite imperative loops functionally. Desugar for loops into while loops, convert the loop body into a recursive function, convert iteration variables into function arguments. So this:

```<code>public void printFirst(int n) {
    for (int i = 0; i < 10; i++) {
        println(i);
    }
}
</code>```

can be converted into this:

```<code>def recursionHelper(i : int, max : int) {
    if (i == max) {
        return;
    } else {
        print(i);
        // Instead of mutating i, create a new value
        recursionHelper(i + 1, max);
    }
}

def printFirst(n : int) {
    recursionHelper(0, n);
}
</code>```

Such translations can be done pretty mechanically. The resulting code probably won't be idiomatic, since the imperative version of the code likely didn't make much use of high-order functions (functions that take other functions as arguments) and lambda expressions (a concise syntax for creating anonymous functions), but it's a good first step towards learning how to think functionally.

Title: Decreasing vars in Scala programs

Body:
There's a couple of insights that will ease your transition from imperative programming to functional programming:

Mutation of some value x can be replaced with creating a modified copy of x. There are persistent versions of most data structures that can do this efficiently by copying only the parts of the structure that changed and sharing the rest.

Loops can be replaced with recursive functions. On languages with tail call optimization, tail recursion won't blow the stack because the compiler can rewrite it as a loop under the hood.

A function that depends on a free variable (i.e. a variable that's not a formal parameter of the function) can be converted into a function that takes the current value of that variable as an argument.

We can combine all 3 rules to rewrite imperative loops functionally. Desugar for loops into while loops, convert the loop body into a recursive function, convert iteration variables into function arguments. So this:

public void printFirst(int n) {
    for (int i = 0; i < 10; i++) {
        println(i);
    }
}

can be converted into this:

def recursionHelper(i : int, max : int) {
    if (i == max) {
        return;
    } else {
        print(i);
        // Instead of mutating i, create a new value
        recursionHelper(i + 1, max);
    }
}

def printFirst(n : int) {
    recursionHelper(0, n);
}

Such translations can be done pretty mechanically. The resulting code probably won't be idiomatic, since the imperative version of the code likely didn't make much use of high-order functions (functions that take other functions as arguments) and lambda expressions (a concise syntax for creating anonymous functions), but it's a good first step towards learning how to think functionally.


答:
I don't think so. A degree will last as long as it exists.

It is well known that people forget quickly [almost] everything they have studied. Jumping into working environment straight after the graduation won't change much. You'll still forget everything soon afterward since you won't be using most of your knowledge anyway. As you know most of the programming jobs it's just simple code&maintenance stuff with little to none CS application.

In that regard, if you were going to devalue a degree after one year, you could it right away. A year in the industry instead of a year off won't help a programmer to hold on to the knowledge obtained.

An entirely different matter is however what value is a degree for a programmer. I think most employers would put value on your practical experience not on your degree, so it comes as irrelevant when exactly you got one.

Title: How long does a Comp Sci degree last?

Body:
I keep hearing from people that if I don't become a programmer soon after graduation my degree will be a useless piece of paper, they claim it will become outdated.  I kind of find this hard to believe considering what I was taught at a fairly good school has been standard practice for some time.

So is this a true belief in industry?  That somehow I become less desirable after a year or two, even though the graduates who comes after me pretty much get the same identical education.


问:
Is it okay to not completely understand code functionality?
As I am currently struggling with learning WCF for a project at work, for the past several days I have been looking at online tutorials and examples on the best way to make a WCF client; and today, when I told my boss I was having a hard time finding good tutorials because some of them would not go into details with their examples (for instance showing a piece of code that works but not explaing why exactly, or making an example with just a few lines instead of at a larger scale), he told me that I should not try to understand them completely, because there are times where a code will just do what it does and I should leave it at that (he gave me the example that when doing calculus, for instance, we use formulas that we don't know how they were conceived or how they work, we just know that they do and we use them).

And this bothered me because I have always been told that it's really important to understand your code, and that just copying and pasting without knowing HOW it works is practically a sin; which is why I always take my time in understanding something before moving forward with it. And it's not like I'm trying to understand how a particular class works at an assembly language level, I just want to know why a set of instructions does the trick, and why another one doesn't, or why both do and under what circumstances. But my boss tells me that I will end up wasting time obsessing over these little details, and I should just skip it. So my question is, is he right? Is it okay to understand your code only to a certain extent and keep going, and have I only been obsessing over little things that don't matter?

答:
Your boss' advice might work fine, but it is risky. There is a danger that in the long term you will get into bigger problems, which could be averted by taking the time to understand things in the first place. If this is a one-time thing, the risk is relatively small. If you build an entire software system this way, you have a ticking time bomb on your hands. What you don't understand, you don't have any hope of fixing or changing without causing bugs.

On the other hand, if you disobey your boss, your own job may be at risk. If you like your job, then in the future, try to resolve technical issues yourself before he has to get involved. I had a boss once who would mess things up whenever he got involved in technical decisions (though he was stellar at sales and customer relations). Most of the technical staff learned to listen to what he would say, then turn around and do something different. As long as the software worked, he would never follow up and check whether his technical advice was actually implemented. The job paid well, but I'm glad I'm not there any more.

If this attitude is pervasive at your place of work, I would at least consider other work options.


答:
Warning: this is written as (sort of) a comment on @MainMa's answer, but 1) it's too long to fit in a comment, and 2) I think it adds a somewhat different perspective on constructive questions so it's a real answer in itself.

In his answer, @MainMa classifies "What are the new features of .NET 4.5?" as a "good" question.

I beg to differ. As he's phrased it, I'd say this is a fairly mediocre question at best. A good question would be more like: "How does the code you write today differ from the code you wrote N years ago?" (for some value of N less than the years of experience listed on the resume, preferably around 3 to 5).

As he's phrased it, the question is about memorization. Has this candidate memorized the feature list completely? By rights, the one who quotes Microsoft's list the most accurately should be the winner.

What you should care about is his programming. How has this affected his code? Which of those features does he really use? More importantly still, does he display good judgement about when to use which new features, and when older ones suffice perfectly well?

Just being able to say "LINQ" tells you virtually nothing useful about the candidate. Being able to say: "LINQ has helped make my code much more compact and readable because I can express concepts X, Y and Z cleanly and directly, where I previously had to jump through the following flaming hoops to do those things." (or something similar) tells you a lot about the candidate, what kind of code he writes, his judgement, flexibility, and so on. It also gives you a great deal more opportunity for follow-up questions about how this person thinks about problems, writes code, thinks about code, and so on. Finally, it gives you a much better idea of whether this is a candidate who really has N years of experience, or somebody who has one year of experience, repeated N times.

Summary: being able to quote a feature list from a few years ago is useless, and tells you little about the candidate that's likely to be of any real use. The candidate's progress as a programmer is likely to be of a great deal more interest, so it's much better to ask about that more directly.


答:
You don't.

Database / schema changes are not things that "just happen". Changes like this are not desired or supported.

Any change that may be needed will have to go through the regular release management and change management process, which includes testing the existing functionality (nothing is broken) as well proving that the change has the desired effect. We have a dev, test, staging and production environment just for this. We do not write code in production.

It may take a bit longer than just changing a database in production, but it is the only way to make sure users don't get confronted with random errors because "someone" changed "something".

You cannot code against a changing database schema. What if the DBA renames a table? What if the DBA drops related records? What if the DBA disables validation, or adds extra validation?

The only valid option is to log errors, and to let the application fail.

I suggest making clear rules with the operations team about these kinds of things. How would they like it if you start renaming servers for them?

In my environment we make schema changes only as part of a release, and we do that with tooling that transforms the schema to the exact form as designed. other changes that may be made in an environment will be undone by this.

Title: How to handle unexpected schema changes to production database

Body:
Is it a common or normal practice to encounter schema changes, especially renamed or removed columns, in a production database, without having been notified of the change?  If unexpected schema changes are anticipated in the production database, how are they guarded against, other than basic exception handling?

I've worked mainly with credit union software, DoD software, high volume e-commerce web applications, real estate systems, robotics, and more recently CMMS, GIS, and SCADA systems.  Although the '90s and early 2000s were more of the wild west, everything I have been involved with over the last 10 years or so has required change management.  Modifications to a production database without change control is not allowed by policy and by security controls.

Comments in the accepted answer to this question - Why is “Select * from table” considered bad practice make me wonder how much of this is academic and how much is reality.


答:
I can see that these skills might be used in jobs where you need to
  write compilers, drivers and work on the OS kernel. Other than those,
  where else are these skills used?

How about writing search engines, web servers, web browsers, word processors, spread sheets, image editors, drawing programs, database servers, bioinformatics, trading programs, games, physics simulators, and so on and so forth.

I will grant you that the majority of software jobs involve pulling data from a database, putting it up on a screen, editing it, scraping it off the screen and putting it back in a database. However, even then, you may eventually run into an application where the constraints can't be satisfied by the built in features of a platform. At that point you can either give up, or reach into your toolbox of algorithms and data structures and take a shot at solving the problem.


问:
What percent of your college course work is unit-tested code?
As a college student do you write unit-test for the project code you write?  Do you know how to properly use TDD?  Have you been taught to use testing frameworks (jUnit for example)?

I've just recently heard that a major company's project team was delivering software to User Acceptance Testing group that had only 7% line code coverage for unit testing.  While that shocks me, it just tells me that this company's software engineering practice are immature.  However I wonder if they could just hire a few recent graduates and raise the bar on the teams practices - assuming that these newly minted programmers were trained in the best practices.

Are you 2008 - 2010 CS graduates using best practices of unit testing your code?

答:
In my university you can't complete a Software Engineering degree without taking a particular subject that focuses on teaching Agile software development methodologies. In that subject you can't claim any feature's implemented without reasonable testing through JUnit and Selenium.

However: TDD was taught but not enforced and due to group work some students could avoid exposing themselves to Selenium and/or JUnit.

OwnerDisplayName: David Koontz


问:
Picking an image from a set of images that is most likely to be compelling to a typical viewer
Given a set of images on a webpage, what's a good way to pick a compelling image that is also representative of the webpage? The use case is displaying an image along with a description of a URL to a page, after a user includes it in a status update.

I've found some techniques to find the most interesting part of a single image. Example: http://berk.es/smartcropper/

So maybe I can use this notion of entropy to compare images in a set?

I am programming in ruby, so a pure ruby solution is preferable, but am open to others.

答:
This is just a quick hash of ideas. I don't have any implementations to share.

Best advice: use side-channel information:

Relative position (layout) of the image on the page.

Look at the scripts attached to that image. Is that clickable (onclick)?

Does it have a title?

Does it have a title that shares important words with the title of the page?

Not-so-best advice: use image information.

Not-so-best because these are known difficult open-ended problems, so a non-scientist will find it painful to implement or even use.

Images with beautiful histogram (e.g. suns, beaches, blue sky)

... any of the research publications mentioned by others in the comments.

COTS (on-the-shelf) solutions:

Images with a face (mugshot). Search for "OpenCV face recognition Ruby" and you'll find some.

Instructions: http://www.sitepoint.com/detecting-faces-with-ruby-ffi-in-a-nutshell/ (No comments on this since I'm not a Ruby programmer)

Advice for the true hackers.

https://harthur.github.io/brain/

This is a submission (as seen on Hacker News) that trains a simple neural network (3 input nodes, 3 nodes in a middle layer) based on whether the user prefers black text or white text against a RGB background.

A similar do-it-yourself approach can be applied to an image histogram picker. However, we wouldn't know how useful the end result would be for your applications.


问:
What's the right OO way to create a counter/inventory class that works for both differentiated and undifferentiated countables?
You are writing a videogame about trading beans. Red beans, black beans, pinto beans, you name it. As everybody knows all beans are the same. You write the "Inventory" class for a trader in that videogame as follows (skipping all the null checks):

```<code>    class BeansInventory{
HashMap<BeanType,Integer> amountsOwned;

public void receive(BeanType typeReceived, int amount)
{amountsOwned.put(typeReceived,amountsOwned.get(typeReceived)+amount)}

public void remove(BeanType typeRemoved, int amount)
{amountsOwned.put(typeRemoved,amountsOwned.get(typeRemoved)-amount)}

public Integer amountOwned(BeanType type)
{amountsOwned.get(type)}
}
</code>```

It works fine for years. Then suddenly somebody else has the great idea to add to the game trading coffee beans. As everybody knows each single coffee bean is completely different from the other. So you can't just add coffee as another bean type. Each coffee bean is its own instance. The coffee inventory class looks something like this:

```<code>class CoffeeInventory{
    HashMap<CoffeType,List<CoffeeBeans>> coffeOwned;

    public void receive(CoffeType typeReceived, CoffeeBeans... beans)
    {coffeOwned.get(typeReceived).addAll(beans)}

    public void remove(CoffeType typeRemoved, CoffeeBeans... beans)
    {coffeOwned.get(typeRemoved).removeAll(beans)}

    public Integer amountOwned(CoffeType type)
    {amountsOwned.get(type).size()}
    }
</code>```

But now you have tons of problems. You have two APIs for the same task. All the trading infrastructure now has to check carefully if it is trading pinto beans or coffee beans and call a different inventory and a different method with a different signature for what is after all the same task: "store this".

So now I have this code that is getting filled of if checks and instanceof and all the other signs of code smell. But I can't figure out a way to use a single simple API. I have no idea what's the right oo thing to do.

答:
Your BeansInventory is different to your CoffeeInventory. Actually I would not even call it "inventory" because it does not store things but rather tracks amounts.
Fruthermore, your CoffeeInventory class does not show any methods to return the stored bean objects but I assume that this is required somewhen so we can't use simple counters there like in the BeansInventory.

So to avoid your checks to distinguish between coffee beans and other beans the clean solution would be to not make a difference btween beans at all!

```<code>class BeansInventory{
  HashMap<BeanType,Integer> amountsOwned;

  public void receive(BeanType typeReceived, int amount) {
       amountsOwned.put(typeReceived,amountsOwned.get(typeReceived)+amount)
  }

  public void receive(BeanType typeReceived, Beans beans) { //beans is a list of beans
       this.receive(typeReceived, beans.size())
  }

  //...
}
</code>```

This way it doesn't matter in which inventory the beans are inserted and on top you don't have to change existing API. Just the handling between the inventories differes, but they behave the same. Of course that means both should implement an Inventory Interface having generic methods like receive(Bean bean), remove(Bean bean), contains(Bean bean) and so on.

You should also regard to make it more generic and start using bean objects for normal beans too. Even if they are maybe all the same. This way you don't have to create a special inventory for beans that all look alike. (it may give you performance advantages though)

Body:
Your BeansInventory is different to your CoffeeInventory. Actually I would not even call it "inventory" because it does not store things but rather tracks amounts.
Fruthermore, your CoffeeInventory class does not show any methods to return the stored bean objects but I assume that this is required somewhen so we can't use simple counters there like in the BeansInventory.

So to avoid your checks to distinguish between coffee beans and other beans the clean solution would be to not make a difference btween beans at all!

class BeansInventory{
  HashMap<BeanType,Integer> amountsOwned;

  public void receive(BeanType typeReceived, int amount) {
       amountsOwned.put(typeReceived,amountsOwned.get(typeReceived)+amount)
  }

  public void receive(BeanType typeReceived, Beans beans) { //beans is a list of beans
       this.receive(typeReceived, beans.size())
  }

  //...
}

This way it doesn't matter in which inventory the beans are inserted and on top you don't have to change existing API. Just the handling between the inventories differes, but they behave the same. Of course that means both should implement an Inventory Interface having generic methods like receive(Bean bean), remove(Bean bean), contains(Bean bean) and so on.

You should also regard to make it more generic and start using bean objects for normal beans too. Even if they are maybe all the same. This way you don't have to create a special inventory for beans that all look alike. (it may give you performance advantages though)