问:
How do I approach a coworker about his or her code quality?
I work on a new venture at a large enterprise software company (3000+ programmers). In my group, we have a bunch of projects and people usually work on several projects over the course of a year.

I just started work on a project that has been previously maintained by a buddy of mine (consultant who's been with us for 3+ years) to add some features. I got into the code, and the quality was really quite poor. Whether it was on the UI frontend or the services backend, the code simply wasn't indented, there were hundreds of lines commented out for no apparent reason, documentation was basically non-existent, coding standards weren't applied consistently (e.g. mixing camelCase and under_scored_variables), variable names were unintelligible, datatype choices were wrong, etc. etc.

I'm very much a non-confrontational person, so I don't want to attack my coworker, but I also don't just wanto to go to my boss and complain about his performance. What are the kinds of things I could say to politely mention that the code is poorly structured?

EDIT:

I want to clarify that while I understand there is an element of "Everyone else's code sucks" to all programmers, when I see something like this (names are chosen on purpose and some details left out/changed in this example):

```<code>public void doCalculate(Object argument) {
  if (argument instanceof String) {
    String argument2 = (String) argument;
    if (argument2 == "DataBase") {
      // do something
    } else {
      long argument3;
      try {
        argument3 = Long.parseLong(argument2);
      } catch (Exception e) {
        argument3 = -1;
      }
      // do something completely unrelated
    }
  }
}
</code>```

I think it's objectively fair to say that this is not a good idea. Furthermore, I'm not dealing with a newbie here (I'm only coding 3 years now). He's got maybe 20 years of experience on me. The advice you guys have given so far is great; just wanna make sure that we're not talking about a "fine line" here.

答:
It is unlikely that the author of the code will come back to fix his code for you out of pure good will, or that your employer will pay him to do that. So, either way, you are scr*wed.

If you believe that the mess the code is in will have a severe detrimental effect on your performance while working on it, be sure to save a backup of the original code somewhere so that you can prove that it was a mess when it was delivered to you. So, if your employer confronts you later about your poor performance, you can cover your ass.

Still, it may look to your employer like an excuse, so try to avoid even that happening if you can.


答:
Think about what good mentioning him that he has a bad coding style would do you or him?

Perhaps it's better to try to improve your company's QA procedures.

ContentLicense: CC BY-SA 3.0

Title: How do I approach a coworker about his or her code quality?

Body:
I work on a new venture at a large enterprise software company (3000+ programmers). In my group, we have a bunch of projects and people usually work on several projects over the course of a year.

I just started work on a project that has been previously maintained by a buddy of mine (consultant who's been with us for 3+ years) to add some features. I got into the code, and the quality was really quite poor. Whether it was on the UI frontend or the services backend, the code simply wasn't indented, there were hundreds of lines commented out for no apparent reason, documentation was basically non-existent, coding standards weren't applied consistently (e.g. mixing camelCase and under_scored_variables), variable names were unintelligible, datatype choices were wrong, etc. etc.

I'm very much a non-confrontational person, so I don't want to attack my coworker, but I also don't just wanto to go to my boss and complain about his performance. What are the kinds of things I could say to politely mention that the code is poorly structured?

EDIT:

I want to clarify that while I understand there is an element of "Everyone else's code sucks" to all programmers, when I see something like this (names are chosen on purpose and some details left out/changed in this example):

```<code>public void doCalculate(Object argument) {
  if (argument instanceof String) {
    String argument2 = (String) argument;
    if (argument2 == "DataBase") {
      // do something
    } else {
      long argument3;
      try {
        argument3 = Long.parseLong(argument2);
      } catch (Exception e) {
        argument3 = -1;
      }
      // do something completely unrelated
    }
  }
}
</code>```

I think it's objectively fair to say that this is not a good idea. Furthermore, I'm not dealing with a newbie here (I'm only coding 3 years now). He's got maybe 20 years of experience on me. The advice you guys have given so far is great; just wanna make sure that we're not talking about a "fine line" here.


问:
Is it bad interview practice to have candidates write a linked-list implementation?
Reading this site and SO I've seen many stories of interview questions and answers saying a candidate had to implement a linked list from scratch. Usually this is a "gimme" exercise for programming role candidates like writing FizzBuzz. The idea is that if the candidate can't do this, they can't program and should be rejected almost immediately.

However, I can't help but think this could be a poor practice for the following reasons:

Modern higher level languages like C# and Python natively use lists extensively; writing your own linked list object would be only required under unusual circumstances and even then probably ill-advised.

Lower level languages like C++ have standard libraries with iterators/list containers and objects.

In light of the first two points, coders can go years without even thinking about implementing a list (linked, doubly-linked, etc) themselves. Some may not even really see such things since college days.

Computing power also isn't the factor it was years ago, so efficiency via pointers isn't the issue it used to be (in general).

A simple web search of something like "linked list example" would bring up plenty of code examples that could just be memorized and spat back out, not really indicating the true competence of the applicant.

I should say that using a linked list to lead to open-ended questions/discussions of candidates' problem solving/critical thinking abilities is mostly likely a really good interview practice. Any way an interviewer can really see what an applicant is like and how they think is massively beneficial.

I think this binary approach of "no linked list code, no job" for programmers working on a desktop or web application is a bit outdated. It could also be quite harmful; a candidate who can't remember how to properly work with the head of a list could be an otherwise excellent coder and co-worker and be lost in the mix. Thoughts?

EDIT: There are many (good) comments suggesting that whether this is a good or bad question to ask depends on the context of the job. I strongly agree, so let me rephrase this question: Implementing a linked-list is a common interview question for a wide range of coding jobs, similar to questions like FizzBuzz or writing a recursive function for calculating factorials. Does this question have enough utility to be used commonly for evaluating programming candidates across the board? Or should considered a bad question to ask except for "Senior Developer, Embedded Linked Lists Team" positions?

答:
I have missed out on jobs purely because my mind blanked on simple puzzles like this. I've also done brilliantly on such puzzles in other interviews -- I know how to implement a linked list in a non-pressure environment. I've never had a complaint about my abilities from someone I've worked with, so maybe I shouldn't think that I've missed out on jobs, I should think that they've missed out on me.

So yeah, I think it's a questionable practice at best, but I do understand it. I have also considered the possibility that it's not the fault of the question but the questioner, for making it a high-pressure situation.

Personally, I prefer to ask open-ended questions about a problem the candidate has already solved -- recently, if possible, and covering both coding and process problems. If they can bring code-samples, fantastic.


答:
Of course most people would never need to implement a linked list, but to implement them from scratch one will probably need to handle pointers correctly. They idea is then that having formed a consistent mental model for pointers correlates with the language proficiency, understanding what happens on some (abstract) machine level and the ability to abstract in general.

I am not saying that this would necessarily be the best measure, but only that there is some correlation.

Title: Is it bad interview practice to have candidates write a linked-list implementation?

Body:
Reading this site and SO I've seen many stories of interview questions and answers saying a candidate had to implement a linked list from scratch. Usually this is a "gimme" exercise for programming role candidates like writing FizzBuzz. The idea is that if the candidate can't do this, they can't program and should be rejected almost immediately.

However, I can't help but think this could be a poor practice for the following reasons:

Modern higher level languages like C# and Python natively use lists extensively; writing your own linked list object would be only required under unusual circumstances and even then probably ill-advised.

Lower level languages like C++ have standard libraries with iterators/list containers and objects.

In light of the first two points, coders can go years without even thinking about implementing a list (linked, doubly-linked, etc) themselves. Some may not even really see such things since college days.

Computing power also isn't the factor it was years ago, so efficiency via pointers isn't the issue it used to be (in general).

A simple web search of something like "linked list example" would bring up plenty of code examples that could just be memorized and spat back out, not really indicating the true competence of the applicant.

I should say that using a linked list to lead to open-ended questions/discussions of candidates' problem solving/critical thinking abilities is mostly likely a really good interview practice. Any way an interviewer can really see what an applicant is like and how they think is massively beneficial.

I think this binary approach of "no linked list code, no job" for programmers working on a desktop or web application is a bit outdated. It could also be quite harmful; a candidate who can't remember how to properly work with the head of a list could be an otherwise excellent coder and co-worker and be lost in the mix. Thoughts?

EDIT: There are many (good) comments suggesting that whether this is a good or bad question to ask depends on the context of the job. I strongly agree, so let me rephrase this question: Implementing a linked-list is a common interview question for a wide range of coding jobs, similar to questions like FizzBuzz or writing a recursive function for calculating factorials. Does this question have enough utility to be used commonly for evaluating programming candidates across the board? Or should considered a bad question to ask except for "Senior Developer, Embedded Linked Lists Team" positions?


答:
When I was giving interviews, I was often asked for linked list implementations and some algorithms centered around linked-lists. I solved most of them, and some of them required me exercise my neurons a bit.

If I was ever taking an interview, I would go for some sort of a linked-list implementation, not to test how good a person is in coding, but to check how much attention a person pays to details. Anyone can write a linked list, but it is the boundary cases that even some good programmers fail at. Don't ask him: Write a code for linked list in C/C++. Ask him to write a generic linked list in C (not C++), etc.

Twist the problem, and put some other conditions on the linked list, and you'll have a good question to ask. Some people are bound to make mistakes then.


问:
What are your initial three steps when you are first presented with a software problem?
I am curious about the very early steps that a programmer's mind takes when it first encounters a problem that it is supposed to solve. How do you start reasoning about it ? What are the first questions you ask yourself ??.

Ok, let me make it more concrete for those of you who think the question is too vague or entirely situation dependent. Pick any of the following   requirements and think out loud about your very first hunches/impressions/tendencies about how to solve it.

1) build a simple word processor with about as much functionality as MS Word Pad

 2) design a single person card game (e.g. Solitaire)

 3) build a scientific calculator

 4) Any  problem of your choosing with similar scale/complexity as the above three

答:
In terms of deciding what to do:

What is the need? Who needs it? Why? How will it make money (or achieve some other goal for non-money projects). How much is available to spend on it. Are the returns likely to justify the likley expenditure.

What are the most valuable features. What are the features that are most unknown; likely to be the most risky (that is to say, most unpredictable). Try to break down the features into the smallest chunks the customer can still recognise (accept) as features. You don't need to identify all the features, just try to get a few that have high value to the customer.

Implement the most risky, most valuable feature (trade off to get maximum value and remove maximum risk at the start of the project).

In terms of deciding how to do it:

Is there any existing code/technology/product/service that already solves the problem, can I use or adapt that?

If not, what are the domain concepts involved and technical constraints on the solution.

Implement the feature trying to achieve the simplest expression of the parts of domain model required for this feature. Decouple the domain model as much as practical from any technical considerations (e.g database technology, OS, client machine vs cloud, etc). I generally use a test driven approach to accomplish this.

OwnerDisplayName: mumtaz

LastEditorDisplayName: mumtaz

ContentLicense: CC BY-SA 2.5


答: One has to define the programming job type. If you are in the business of developing compilers and algorithms, questions about such things should be expected. If you are in line-of-business type applications and you expect the candidate to do CRUD applications, then, may be the knowledge of the concept (without writing a program) is sufficient. Today, the knowledge of different technologies required to get the job done specially in the LOB type of applications supersedes the need for neat algorithms.</p>


答: I think that this is a bad example of an interview question, but for a different reason.  A linked list is such a simple concept that to know what it is is to know how to implement it.  If the person doesn't know what a linked list is, then you have to explain how it works, and in doing so you give away the answer without discovering anything about whether or not they know how to solve problems.  So the question is reducible to "do you already know what a linked list is and how it works?", which tells you nothing useful about their suitability as a programmer.</p>


问:
How to incrementally update a database when deploying a website?
We use JSF over Tomcat along with a backing proprietary DB.

I want to know how the addition of new database fields or/and stored procedures should be handled when we deploy a new version of the application.

We deploy by sending a WAR file to the hosting Team, as such our WAR should be able to
setup the stored procedure when it starts.

What are the possible appropriate strategies to be able to incrementally update the database?

答:
The two standard approaches for database updates that I've seen applied are:

The deployment team running sql scripts provided by the DBA team. The DBA group would provide scripts to update the schema and load any data that were required for that particular release.

Using an automated tool like Liquibase. This system adds a table similar to what @Jalayn proposes, which tracks the changesets (deltas) that should be run for each table. Most standard operations are supported.

In either case, the end result should be the same. However, the approach you take should reflect the principles that your development group prefers - automated vs manual, etc.


问:
How can I learn to effectively write Pythonic code?
Doing a google search for "pythonic" reveals a wide range of interpretations.  The wikipedia page says:

A common neologism in the Python community is pythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms, that its use meshes well with the rest of the language.

It also discusses the term "unpythonic":

In contrast, a mark of unpythonic code is that it attempts to write C++ (or Lisp, Perl, or Java) code in Python—that is, provides a rough transcription rather than an idiomatic translation of forms from another language. The concept of pythonicity is tightly bound to Python's minimalist philosophy of readability and avoiding the "there's more than one way to do it" approach. Unreadable code or incomprehensible idioms are unpythonic.

What does the term "pythonic" mean?  How do I learn to effectively apply it in practice?

答:
```<code>--> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
</code>```

Pythonic code is:

Readable

Simple (as simple as possible, but no simpler)

Well thought-out

Body:
--> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Pythonic code is:

Readable

Simple (as simple as possible, but no simpler)

Well thought-out


答:
I wouldn't consider it a bad interview question.  A lot of data structure understanding and programming starts with a really good understanding of Linked Lists.  That said, there are some caveats:

1) It is a fizz-buzz type question.  You are just validating something very basic: Does the person understand a linked-list. Ask it and move on.

2) There is the challenge with linked lists that the languages that are highly suited to showing your understanding of linked-list concepts (e.g., C) may not the same as the language they will be working with on the job. You can demonstrate basic understanding in any language with structures, of course, but asking a candidate to re-implement a linked list in Erlang without using [] isn't the same challenge and won't tell you the same thing about a candidate's understanding as asking them to do it in C.  Asking them to do it in C if the job is around Java is also missing the point somewhat.

3) With that in mind and the general challenges of "whiteboard programming," when asking this sort of question I'd accept pseudocode or diagrams so long as they demonstrate understanding of the core principles. I don't ask that people write code on a whiteboard that is syntactically and logically perfect, especially if they can then turn around and identify any logical problems when asked to look at it again.  YMMV.


答: Buy a recommended book.  Read it.  It should give you a good basis of using the language and in a mechanism that should meet the community style</p>

Title: How can I learn to effectively write Pythonic code?

Body:
Doing a google search for "pythonic" reveals a wide range of interpretations.  The wikipedia page says:

A common neologism in the Python community is pythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms, that its use meshes well with the rest of the language.

It also discusses the term "unpythonic":

In contrast, a mark of unpythonic code is that it attempts to write C++ (or Lisp, Perl, or Java) code in Python—that is, provides a rough transcription rather than an idiomatic translation of forms from another language. The concept of pythonicity is tightly bound to Python's minimalist philosophy of readability and avoiding the "there's more than one way to do it" approach. Unreadable code or incomprehensible idioms are unpythonic.

What does the term "pythonic" mean?  How do I learn to effectively apply it in practice?


问:
How to populate a private container for unit test?
I have a class that defines a private (well, __container to be exact since it is python) container.  I am using the information within said container as part of the logic of what the class does and have the ability to add/delete the elements of said container.

For unit tests, I need to populate this container with some data. That
data depends on the test done and thus putting it all in setUp() would
be impractical and bloated -- plus it could add unwanted side effects.

Since the data is private, I can only add things via the public
interface of the object.  This runs code that need not be run during a
unit test and in some cases is just a copy and paste from another test.

Currently, I am mocking the whole container but somehow it does not feel that elegant a solution.  Due to Python mocking frame work (mock), this requires the container to be public -- so I can use patch.dict().  I would rather keep that data private.

What pattern can one use to still populate the containers without excercising the public method so I have data to test with?

Is there a way to do this with mock's patch.dict() that I missed?

答:
The convention for private attributes is a single leading underscore; a double leading underscore is for protected (it will use name mangling to keep the attribute unique across subclasses).

```<code>class Test():
    _private = 1
    __protected = dict()
    __container = list()
</code>```

If private is what you really want, just remove one of the leading underscores and then accessing and modifying _container is easy-peasy.

If protected is really what you want, you can still access __container but you'll have to mangle the name yourself if accessing it from outside the class.  Using my Test class above to illustrate:

```<code>t = Test()
t.__Test_container.append("this is how it's done")
</code>```

Body:
The convention for private attributes is a single leading underscore; a double leading underscore is for protected (it will use name mangling to keep the attribute unique across subclasses).

class Test():
    _private = 1
    __protected = dict()
    __container = list()

If private is what you really want, just remove one of the leading underscores and then accessing and modifying _container is easy-peasy.

If protected is really what you want, you can still access __container but you'll have to mangle the name yourself if accessing it from outside the class.  Using my Test class above to illustrate:

t = Test()
t.__Test_container.append("this is how it's done")


答:
If answering the question tells you what you want to know about a candidate, then it's a good interview question.  If it doesn't tell you that, it's a bad question.

Easy questions like FizzBuzz do serve a specific purpose.  If a candidate can't code FizzBuzz, they simply can't code and you can end the interview early.  I'd rate implementing a linked list only slightly harder, but it can start a conversation about data structures in general that will reveal a lot.

Just remember that no single interview question will tell you everything you want to know.  You really need to have a group of questions ready.  You should ask questions in a sequence from easiest to hardest so you can find the limit of what the candidate knows.  If you ask one question and they nail it, you still don't know what else they do or do not know.

Regarding your edit:

Does this question have enough utility to be used commonly for evaluating programming candidates across the board? Or should considered a bad question to ask except for "Senior Developer, Embedded Linked Lists Team" positions?

I think it is a good general purpose question that could be used for evaluating practically any programming candidate.  It just needs to be part of a larger group of questions.  It would be a good ice breaker for many types of position (even if the candidate can't implement a linked list from scratch, maybe they can explain how they've used one before and what the key functions are), or the beginning of a long sequence of more advanced questions for the "Senior Developer, Embedded Linked Lists Team" position.


问:
What are the complexities of memory-unmanaged programming?
Or in other words, what specific problems did automated garbage collection solve? I've never done low-level programming, so I don't know how complicated can freeing resources get.

The kind of bugs that GC addresses seem (at least to an external observer) the kind of things that a programmer that knows well his language, libraries, concepts, idioms, etc, wouldn't do. But I could be wrong: is manual memory handling intrinsically complicated?

答:
I think garbage collection gets a lot of credit for language improvements that have nothing to do with GC, other than being part of one big wave of progress.

The one solid benefit to GC I know of is that you can set an object free in your program and know it will go away when everyone is done with it.  You can pass it to another class's method and not worry about it.  You don't care what other methods it gets passed to, or what other classes reference it.  (Memory leaks are the responsibility of the class referencing an object, not the class that created it.)

Without GC you have to track the entire life cycle of the allocated memory.  Every time you pass an address up or down from the subroutine that created it, you have an out-of-control reference to that memory.  In the bad old days, even with only one thread, recursion and an ornery operating system (Windows NT) made it impossible for me to control access to allocated memory.  I had to rig the free method in my own allocation system to keep memory blocks around for a time until all the references got cleared out.  The holding time was pure guesswork, but it worked.

So that's the only GC benefit I know of, but I couldn't live without it.  I don't think any kind of OOP will fly without it.


答:
Does this question have enough utility to be used commonly for evaluating programming candidates across the board?

No, absolutely not. Depending on how it's phrased, what it will tell you will range from "this candidate knows how to design a linked list" to "this candidate can program a linked list in language X". If you ask for pseudocode, it will tend more toward the first. If you ask for an implementation in a particular language, you will get more into their understanding of the language (especially with C and C++, where you can deal with pointers and references and structs).

I'd even go so far as to say that it's not possible to evaluate all candidates using the same questions. You need to tailor your interview questions to assess the skills that you are looking for in the position.

If the person is going to be in a position to write code, I'd think about including an algorithm and/or data structure question, as long as it was relevant to the position. I'd try to pick something that might have been discussed or used before. I'd also focus on things other than just the implementation of said algorithms and data structures, such as the running time and memory consumption (things like big-O notation). These concepts are relevant to not only creating the data structure, but also choosing which implementation is best suited (such as an ArrayList versus a LinkedList for example).


答:
You start out saying that they're 'gimme' questions, but then you point out that people will understandably not be able to do them. I'm confused.

Here's how I think about it:

There's rarely a need to write one, as you say, so people will have easily forgotten.

They're not incredibly difficult to write.

The concepts used to write them can be considered fundamental.

They're used incredibly often (even if you're unaware of it).

I think that makes them good questions to ask. If you're worried about them pre-studying for the interview, then throw in a list. Have them write it circular and ask what the asymptotic running time of their implementation is. Or have them write another common and/or quick data structure... A binary search tree? A queue (FIFO)? A stack (FILO)? A naive (O(n)) priority queue? Lots of people I know think that a BST is O(log n) just because it's a tree.

If you're looking for someone who will be working at the metal, and needs a very solid foundation in data structures... these may even be far too trivial for the candidates you're looking to hire.

This assumes, of course, that you want a dev who has the basics/fundamentals of data structures and their position would benefit from those fundamentals. If you want someone who can throw together an asp page in seconds, interview for that. The point is not to pick an interview question because everyone else does, but to pick one that measures the skills you're looking for. Personally, I think data structures questions are good, linked list or no.


答:
What if instead of approaching him personally, you approach the team and in a completely neutral way propose on "team" coming up with a coding standard/guidelines as a way for different team members to work more efficiently with each other's code.

Once that is in place, I think the code you have concerns with will bubble up to the top all on its own.

Peer code reviews also help in this area. Coding standards don't have much benefit if no one ever looks at the code.  But peer code reviews have many other benefits, primary one knowledge transfer, so you should push to introduce them in either case.

I'm making an assumption that even if you have 3000+ engineers, you guys have MUCH smaller sub teams that work together as a unit


答:
Ask him to explain his code to you

Tell him you've never seen X programmed that way before, and ask him why he codes it that way. Show him the way you code it, and tell why you do it that way (best practices, better performance, less chance of errors, easier for other programmers to read/maintain, etc).

Be sure to prepare all your arguments in advance, and focus on why your method is best instead of why his method is worst. Afterwards, see if he still supports his method over yours.

If he is open to improvement, he will likely change his way of coding. If he still prefers to use his style of coding over yours, you are not likely to change his opinion.

This is the exact same answer I gave for the question How to tell your boss that his programming style is really bad?. I originally voted to close this question as a duplicate, however enough people thought it was different enough to warrent re-opening it. My answer is still the same though, regardless of if you're talking to a boss or a co-worker.


答:
First, everybody thinks other people's code sucks.

Second, maybe he inherited the code from someone/someplace else OR this was a prototype never intended to be the code used for the actual project but of course that's what ended up being used.

Third, maybe his code really does suck but is it your job to badmouth previous developers? Unless you have built up a reputation that commands respect around the company I suspect if you do whine about the other person's code it is you that will end up looking bad and not your friend. The time for giving people grief about their code is when code reviews are held. At least then it is part of your job responsibilities.

I recommend that if you don't like his code then fix it to your liking. Then the next developer will come along and complain about your code and probably change it back to be more like what your friend did.


答:
Your co-worker is probably not the root cause of the problem in your company. The reason that poor quality code gets into production is the lack of automatically measurable coding standards in your company. In this case, sunlight is the best medicine.

You should talk to your technical lead about implementing automated source code quality metrics in your group. The system should run at least weekly, e-mail everyone on the team a file-by-file list of coding standard violations, and send an executive summary to your boss. The summary should contain the number of violations per project.

In my experience, anything that gets measured and reported to a boss improves over time.


答:
My answer is "It depends".  I would ask this question if a candidate has listed C or C++ on his resume.  Asking to implement a linked list is a good test for the understanding of pointers which is absolutely essential for a C or C++ programmer.

On the other hand, if a candidate does not claim to know C or C++, I would not ask him to implement a linked list, but I would consider asking questions about it.  Explain at a high level how a linked list works.  What is the complexity of adding an element to the head of the list?  The tail of the list?  Inserting an element in the middle of the list?  When would you use a list as opposed to an array?  These are fundamental data structure concepts that, IMHO, every programmer should know.


问:
Make a big deal out of == true?
There is a colleague of mine who constantly writes:

```<code>if (someBool == true)
</code>```

It drives me up the wall!  Should I make a big deal of it or just drop it?

答:
You can try approaching your colleague with the following example:

```<code>if ((x == 3) == true) {
    ...
}
</code>```

He should say that the == true is redundant and should be rewritten as

```<code>if (x == 3) {
    ...
}
</code>```

since x == 3 is already a boolean expression.

Now present him the someBool == true example, but slightly rewritten:

```<code>if ((someBool) == true) {
    ...
}
</code>```

Since someBool is already a boolean, by comparison with the previous example, it should now be clear that the == true is redundant in this example, too. Thus, it should be rewritten as:

```<code>if (someBool) {
    ...
}
</code>```

Title: Make a big deal out of == true?

Body:
You can try approaching your colleague with the following example:

if ((x == 3) == true) {
    ...
}

He should say that the == true is redundant and should be rewritten as

if (x == 3) {
    ...
}

since x == 3 is already a boolean expression.

Now present him the someBool == true example, but slightly rewritten:

if ((someBool) == true) {
    ...
}

Since someBool is already a boolean, by comparison with the previous example, it should now be clear that the == true is redundant in this example, too. Thus, it should be rewritten as:

if (someBool) {
    ...
}


答:
Get some background about what was going on within the company and the team when this project was written. Ask this dev for some feedback on how he thought the project went. Has his style changed? If given the opportunity, what would he do differently?

He may agree with your standards, but just didn't have the luxury of applying them during the creation of this app or just didn't know about them.

Either your group has no standards or code review policy or a serious problem with enforcement. You may be holding an opinion of one.


问:
How can I efficiently approach cookie-based session handling?
Currently our web application uses server-sided sessions. Because of the large amount of memory usage, we want to switch to cookie-based sessions. I have been thinking about several ways:

Idea 1

My first idea was to give the client two cookies: SessionID (a hash) and SessionData (the encrypted data). The SessionID will be used to look up a decryption key for SessionData in an in-memory hashtable.

Because only decryption keys are stored on the server, this should wind up being less memory usage. However it still uses some memory, and the CPU load is increased due to encryption/decryption on every request.

It'd also make the session cluster-dependant, with no graceful failover possible.

Idea 2

My second idea was similar to the fist, but instead of looking up a decryption key in a cache, I'd use a salted version of SessionID to decrypt SessionData.

The upside is that there wouldn't be any in-memory cache or hash table anymore, and that session would be cluster-independent if the salt is the same for all clusters.

However, the tradeoff is that it's much less secure due to a potential danger of decrypting or modifying the SessionData cookie, and that the CPU load is increased due to encryption/decryption on every request.

Is there a better way to go about this problem? Or a way to modify one of these ideas to be a little more palatable?

答:
"No sir, I dont like it"

You're needlessly complicating things.  Consider that by storing information client side, you now also have to be extra careful to validate all that information when it is sent back to you.  Or are you going to simply decrypt and trust it?  What happens if the data is slightly corrupted when its sent back?  You are also potentially increasing your bandwidth usage as each request, whether you want it or not, will be sending the encrypted session data back to you.

A better solution would be to find a way to store your session data more efficiently on the server.  Or store less of it.  Or as Mike N suggested, just add some RAM.


问:
How to react to wrong/not answered questions during interview?
Today I have held my first interview with potential interns.
While this has been mostly open questions, I have had some trivial programming tasks for them:

Write a function that returns true if triangle sides (all integers) a, b and c can represent a right triangle.

FizzBuzz.

Calculate the Nth element of Fibonacci using recursion (if they didn't know what Fibonacci was, I would even write them the definition F(n) = F(n-1) + F(n-2); F(1) = 1; F(0) = 1).

Implement structure List for integer and write function to reverse it.

These are obviously very easy tasks and I was not prepared for someone not to solve them.

How should I act when they struggle with these questions? Should I give up the answer? Give tip by tip (I did that and ended up solving the problem myself)? Or just move on (or maybe just stop) with the interview?

ps. By having problems with questions, I don't mean like having a bug, I mean if they can't even get started. This was a case with Fibonacci and List questions.

答:
I had to look up what you meant by "FizzBuzz"; turns out I'd heard of the game and its rules but not by that name and not in a while. So, don't think you don't have to give ANY information to interviewees.

That said, these are all basic coding problems that I would expect someone interviewing for even an entry-level coding position to be able to think their way through, if they couldn't code an answer by inspection. So we're on the same page there. The answer to your problem is dependent on how they're getting it wrong:

Minor syntax issues: If you're expecting code in a certain language, don't count off too heavily if they miss a semicolon or misspell one use of some identifier. Most IDEs will catch that immediately, and everyone makes typos from time to time. In almost every interview in which I was expected to code something, "pseudo-C-ish" was acceptable as long as the algorithm was communicated properly to the interviewer and the logic was sound.

Minor logic flaw: If the algorithm would behave as expected in most, but not all, of the expected scenarios (say when coding FizzBuzz, 15 would only result in "Fizz" or "Buzz" but not both as it's supposed to), then be the "unit tester" and point out that the algorithm would fail in that instance, and see if they can fix it. They may have overlooked that particular case, or they may have not understood the requirements completely enough. Both are again completely understandable, everyday occurrences in coding, which should be easily overcome by simply providing the additional information or feedback.

Major logic flaws: If the algorithm would not pass most or any test scenarios it was given, point that out too, and see if they can fix it. This is more of an issue; either they misunderstood some very basic requirement of the system, or they overlooked some gaping logic hole. But, if they can fix it given more detail of the problem, without being told exactly where their code is failing, chalk it up to unclear requirements and move on.

Don't know where to start/hard-coded answer to specific cases/can't understand their pseudocode: These are the red flags. If you ask someone to code an algorithm that follows the FizzBuzz rules, explaining those rules to them, and you get a blank stare, the interview is over. By the same token, if they can put SOMETHING on the board but it fails at large portions of the problem space, and you have to hold their hand when illustrating the failure and how to fix it, I would not be proceeding to a second interview.


答:
I'll admit it, I am sometimes that guy. When I am, I will have my reasons, usually time constraint, death-march projects, instructions such as "now, not perfect" etc. Very rarely, it's because of a bad day. I am happy to get asked about any issues, it gives me a chance to become a better developer. Provided a) You are reasonable about what will be changed (ain't that badly broke, agree to don't fix), and b) your not a nut job dictator  who believes your way is the only way.

To approach me about it, do not ask "Why". Why is a fighting word, a challenge, and is ultimately destructive. If you find yourself using Why too much, change it to I.
"Why did you call this x" becomes, "I would have used index, it's more descriptive than x."

The best way is to state what you would have done, or would have preferred. Explain that what you are seeing does not met certain standards, and that you would like to see it improved. My guess is that 99% of the time,  the response will be "so would I, but........"


问:
Managers X Motivation
As a programmer what do you think that is the thing that your manager does that mostly decreases your motivation?

My manager insists in blocking web content (this week was msdn content and Microsoft domain sites) This is so stupid, make me think I am not a reliable professional or that I am stealing his internet. And not, it is not a small business. It is a huge enterprise where such dinossaurs should not exist anymore.

答:
And no, it is not a small business.
  It is a huge enterprise where such
  dinossaurs should not exist anymore.

This statement baffles me. My experience with managers is the exact opposite. Only big enterprises can afford mismanagement.

My enterprise is really small and my boss is actually a programmer, even a decent one, but still a cowboy. Which is why I have to clean up a lot of mess, that in a lot of cases really wouldn't have needed to be there in the first place.

Title: Managers X Motivation


答:
In order:

Already exists?

Seems complex? Do I really know how it should work?

Lets try a prototype!

Title: What are your initial three steps when you are first presented with a software problem?

Body:
I am curious about the very early steps that a programmer's mind takes when it first encounters a problem that it is supposed to solve. How do you start reasoning about it ? What are the first questions you ask yourself ??.

Ok, let me make it more concrete for those of you who think the question is too vague or entirely situation dependent. Pick any of the following   requirements and think out loud about your very first hunches/impressions/tendencies about how to solve it.

1) build a simple word processor with about as much functionality as MS Word Pad

 2) design a single person card game (e.g. Solitaire)

 3) build a scientific calculator

 4) Any  problem of your choosing with similar scale/complexity as the above three


问:
What are the advantages and disadvantages of storing the number of comments in an integer column vs. calculating it on the fly?
Let's take CodeReview page as an example. If you go here, you will see the list of the questions with their vote numbers and comment numbers

Now, I am wondering if these numbers are calculated on the fly (e.g. count the total comments in db for this question), or is there an actual field in the questions table called voteCount and it's incremented by one whenever someone votes for this question?

Just another question. Both VoteCount and CommentCount are just integers, what about the user information that is displayed for each question?

Hope this is the correct place to ask this question.

答:
It really depends on the traffic of the site, and you should probably don't bother yourself with such decisions unless:

You've identified an actual bottleneck

You've identified an actual bottleneck on a very similar scenario in the past

Premature optimization is the buzzword, and Donald Knuth describes it1 better than I could possibly:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

The simplest approach is to have a vote table, where you log all votes. Typical fields would be voteID, voterID, questionID, voteTimestamp, and you could calculate the totals on each request. But, that will probably become a performance issue very soon, especially with a high traffic site as StackOverflow2.

In that case, my approach would be to run a scheduled background process3 that calculates totals and stores them in a different table (or the question table), and possibly even in a document storage database4. Or, even in a memory cache5, if it makes sense.

There are other ways to cache calculated totals, these are the simplest ones (I think).

As for the user information, they are expected to change less often, so you could probably get away with caching them, without any special database realm approach.

Generally speaking reads are quite faster than writes and in common low traffic scenarios you'd be just fine by just sensibly caching your views. There is no definitive approach, mix and match as you identify bottlenecks.

1 Warning! PDF link.

2 We can't really isolate CodeReview, it's based on the common platform, if something is a bottleneck on StackOverflow, by default it is (or will be) on CodeReview.

3 Cron is your best friend!

4 Assuming the core database is relational.

5 Memcached is your other best friend!


答:
You need to find a new job.

What do base such a harsh conclusion on?  I just think about some things you need from your work environment:

it lets you do your job.

it lets you grow professionally.

surround yourself with smart people - who may be leaving or have left already.

Title: Managers X Motivation

Body:
As a programmer what do you think that is the thing that your manager does that mostly decreases your motivation?

My manager insists in blocking web content (this week was msdn content and Microsoft domain sites) This is so stupid, make me think I am not a reliable professional or that I am stealing his internet. And not, it is not a small business. It is a huge enterprise where such dinossaurs should not exist anymore.


问:
Should consistency be favoured over programming convention?
When designing a class should consistency in behaviour be favoured over common programming practice? To give a specific example:

A common convention is this: If a class owns an object (e.g. it created it) it is responsible of cleaning it up once it's done. A specific example would be in .NET that if your class owns an IDisposable object it should dispose it at the end of its life. And if you don't own it then don't touch it.

Now if we look at the StreamWriter class in .NET then we can find in the documentation that it closes the underlying stream when it is being closed/disposed. This is necessary in cases where the StreamWriter is instantiated by passing in a file name as writer creates the underlying file stream and therefore needs to close it. However one can also pass in an external stream which the writer also closes.

This has annoyed me heaps of times (yes I know you can make a non-closing wrapper but that's not the point) but apparently Microsoft has made the decision that it's more consistent to always close the stream no matter where it came from.

When I come accross such a pattern in one of my classes I usually create a ownsFooBar flag which gets set to false in cases where FooBar is injected via the constructor and to true otherwise. This way the responsibility of cleaning it up is passed to the caller when he passes the instance explicitly.

Now I'm wondering if maybe consistency should be in favour over best practice (or maybe my best practice is not that good)? Any arguments for/against it?

Edit for clarification

With "consistency" I mean: The consistent behaviour of the class always taking ownership (and closing the stream) vs "best practice" to only take ownership of a object if you created it or explicitly transfered the ownership.

As for an example where it is enoying:

Assume you have two given classes (from some 3rd party library) which accept a stream to do something with it, like creating and processing some data:

```<code> public class DataProcessor
 {
     public Result ProcessData(Stream input)
     {
          using (var reader = new StreamReader(input))
          {
              ...
          }
     }
 }

 public class DataSource
 {
     public void GetData(Stream output)
     {
          using (var writer = new StreamWriter(output))
          {
               ....
          }
     }
 }
</code>```

Now I want to use it like this:

```<code> Result ProcessSomething(DataSource source)
 {
      var processor = new DataProcessor();
      ...
      var ms = new MemoryStream();
      source.GetData(ms);
      return processor.ProcessData(ms);
 }
</code>```

This will fail with an exception Cannot access a closed stream in the data processor. It's a bit constructed but should illustrate the point. There are various ways to fix it but nevertheless I feel that I work around something I should not have to.

答:
I think you're right, to be honest. I think that Microsoft messed up with the StreamWriter class, specifically, for the reasons you describe.

However, I've since seen a lot of code where people don't even try to dispose of their own Stream because the framework will do it for them, so fixing it now will do more harm than good.


问:
Precaching HTML image resources
I wrote a web cam viewer where the javascript source basically sources the image according to an "active" class in a list.

I was wondering what are good modern techniques to make images load faster in the background, so a user can get a better experience flicking through images.

Obviously it doesn't make sense to download all images, I imagine it needs to be like when one scrolls through a Google map in principle, images are loaded on demand.

答:
I haven't really looked into this specific technique before, but this is how I'd approach it:

```<code>$(function() {
    var src = [
        "https://developer.mozilla.org/skins/mdn/Transitional/img/mdn-logo-sm.png",
        "http://cdn.sstatic.net/programmers/img/logo.png?v=123",
        "http://livedocs.adobe.com/flex/3/html/images/adobe.png"
    ];
    var loaded = [];
    var idx = 0;

    var sz = src.length;
    for(var n = 0; n < sz; ++n) {
        var img = new Image();
        img.onload = function() {
            loaded.push(this);
            if(sz === loaded.length) onLoaded();
        };
        img.src = src[n];
    }

    function onLoaded() {
        $("#next").removeClass("disabled").addClass("enabled");
    }

    $("#next").click(function(e) {
        if(!$(this).hasClass("disabled")) {
            e.preventDefault();
            idx = (idx + 1) % sz;

            $($("img")[0]).remove();
            $("#container").append(loaded[idx]);
        }
    });
});
</code>```

http://jsfiddle.net/dbrecht/6MLHR/

In my fiddle sample, I only force the client to load the first image with the rest of the page. Then, on jQuery load ($(function() {})), I cache all other images I want to display with the script (3 images in this case).

Once each image has loaded, I push it into a cached array and check if the cached size equals the source size. If it does, then I call onLoaded.

One optimization to this might be to simply use the cache the image on the page rather than load another one (0th element in src).

Of course, this can easily be done with native Javascript as well, I chose to use jQuery for this example for no real good reason ;).

OwnerDisplayName: Kai Hendry

Title: Precaching HTML image resources

Body:
I haven't really looked into this specific technique before, but this is how I'd approach it:

$(function() {
    var src = [
        "https://developer.mozilla.org/skins/mdn/Transitional/img/mdn-logo-sm.png",
        "http://cdn.sstatic.net/programmers/img/logo.png?v=123",
        "http://livedocs.adobe.com/flex/3/html/images/adobe.png"
    ];
    var loaded = [];
    var idx = 0;

    var sz = src.length;
    for(var n = 0; n < sz; ++n) {
        var img = new Image();
        img.onload = function() {
            loaded.push(this);
            if(sz === loaded.length) onLoaded();
        };
        img.src = src[n];
    }

    function onLoaded() {
        $("#next").removeClass("disabled").addClass("enabled");
    }

    $("#next").click(function(e) {
        if(!$(this).hasClass("disabled")) {
            e.preventDefault();
            idx = (idx + 1) % sz;

            $($("img")[0]).remove();
            $("#container").append(loaded[idx]);
        }
    });
});

http://jsfiddle.net/dbrecht/6MLHR/

In my fiddle sample, I only force the client to load the first image with the rest of the page. Then, on jQuery load ($(function() {})), I cache all other images I want to display with the script (3 images in this case).

Once each image has loaded, I push it into a cached array and check if the cached size equals the source size. If it does, then I call onLoaded.

One optimization to this might be to simply use the cache the image on the page rather than load another one (0th element in src).

Of course, this can easily be done with native Javascript as well, I chose to use jQuery for this example for no real good reason ;).


答:
I use this technique too, I call it 'handoff', and I believe it deserves the status of a pattern. When an object A accepts a disposable object B as a construction time parameter, it also accepts a boolean called 'handoff', (which defaults to false,) and if it is true, then disposal of A cascades to disposal of B.

I am not in favor of proliferating other people's unfortunate choices, so I would never accept Microsoft's bad practice as an established convention, nor would I consider other people's blind following of Microsoft's unfortunate choices to be "consistent behaviour" in any way, shape or form.

Title: Should consistency be favoured over programming convention?

Body:
When designing a class should consistency in behaviour be favoured over common programming practice? To give a specific example:

A common convention is this: If a class owns an object (e.g. it created it) it is responsible of cleaning it up once it's done. A specific example would be in .NET that if your class owns an IDisposable object it should dispose it at the end of its life. And if you don't own it then don't touch it.

Now if we look at the StreamWriter class in .NET then we can find in the documentation that it closes the underlying stream when it is being closed/disposed. This is necessary in cases where the StreamWriter is instantiated by passing in a file name as writer creates the underlying file stream and therefore needs to close it. However one can also pass in an external stream which the writer also closes.

This has annoyed me heaps of times (yes I know you can make a non-closing wrapper but that's not the point) but apparently Microsoft has made the decision that it's more consistent to always close the stream no matter where it came from.

When I come accross such a pattern in one of my classes I usually create a ownsFooBar flag which gets set to false in cases where FooBar is injected via the constructor and to true otherwise. This way the responsibility of cleaning it up is passed to the caller when he passes the instance explicitly.

Now I'm wondering if maybe consistency should be in favour over best practice (or maybe my best practice is not that good)? Any arguments for/against it?

Edit for clarification

With "consistency" I mean: The consistent behaviour of the class always taking ownership (and closing the stream) vs "best practice" to only take ownership of a object if you created it or explicitly transfered the ownership.

As for an example where it is enoying:

Assume you have two given classes (from some 3rd party library) which accept a stream to do something with it, like creating and processing some data:

```<code> public class DataProcessor
 {
     public Result ProcessData(Stream input)
     {
          using (var reader = new StreamReader(input))
          {
              ...
          }
     }
 }

 public class DataSource
 {
     public void GetData(Stream output)
     {
          using (var writer = new StreamWriter(output))
          {
               ....
          }
     }
 }
</code>```

Now I want to use it like this:

```<code> Result ProcessSomething(DataSource source)
 {
      var processor = new DataProcessor();
      ...
      var ms = new MemoryStream();
      source.GetData(ms);
      return processor.ProcessData(ms);
 }
</code>```

This will fail with an exception Cannot access a closed stream in the data processor. It's a bit constructed but should illustrate the point. There are various ways to fix it but nevertheless I feel that I work around something I should not have to.


问:
Can manager classes be a sign of bad architecture?
Lately I've begun to think that having lots of manager classes in your design is a bad thing. The idea hasn't matured enough for me to make a compelling argument, but here's a few general points:

I found it's a lot harder for me to understand systems that rely heavily on "managers". This is because, in addition to the actual program components, you also have to understand how and why the manager is used.

Managers, a lot of the time, seem to be used to alleviate a problem with the design, like when the programmer couldn't find a way to make the program Just WorkTM and had to rely on manager classes to make everything operate correctly.

Of course, mangers can be good. An obvious example is an EventManager, one of my all time favorite constructs. :P My point is that managers seem to be overused a lot of the time, and for no good reason other than mask a problem with the program architecture.

Are manager classes really a sign of bad architecture?

答:
When the class has "Manager" in the name, beware of the god class problem (one with too many responsibilities).  If it is difficult to describe what a class is responsible for with its name, that is a design warning sign.

Bad manager classes aside, the worst name I've ever seen was "DataContainerAdapter"

"Data" should be another one of those banned substrings in names- it's all data, "data" doesn't tell you very much in most domains.


答:
I'd go with consistency. As you mentioned to most people, it makes sense that if your object creates a child object, it will own it and destroy it.  If it is given a reference from the outside, at some point in time "the outside" also is holding the same object and it shouldn't be owned.  If you want to transfer ownership from the outside into your object use Attach/Detach methods or a constructor which accepts a boolean that makes it clear that ownership is transferred.

Having typed all that for complete answer, I think most generic design patterns wouldn't necessarily fall into the same category as StreamWriter/StreamReader classes. I've always thought that the reason MS chose to have StreamWriter/Reader automatically take over the ownership is because in this specific instance, having shared ownership doesn't make a lot of sense.  You can't have two different objects concurrently read from/write to the same stream. I'm sure you could write some kind of deterministic time share, but that would be one hell of an anti-pattern.  So that's probably why they said, since it makes no sense to share a stream, let's just always take it over.  But I wouldn't consider this behavior to ever have become a generic convention across the board for all classes.

You could consider Streams to be a consistent pattern where the object that is being passed in is non-sharable from design point of view and therefore without any additional flags, the reader/writer just takes over its ownership.


问:
How are Programming Languages Designed?
After doing a bit of programming, I've become quite curious on language design itself. I'm still a novice (I've been doing it for about a year), so the majority of my code pertains to only two fields (GUI design in Python and basic algorithms in C/C++). I have become intrigued with how the actual languages themselves are written. I mean this in both senses. Such as how it was literally written (ie, what language the language was written in). As well as various features like white spacing (Python) or object orientation (C++ and Python).  </p>

<p>Where would one start learning how to write a language? What are some of the fundamentals of language design, things that would make it a "complete" language?    </p>

答:
Sounds snobby, but if you have to ask, you really should not.

Like in conceptual art,  you kind of need to learn everything that was done in the field since java inception (and I'd have said since C inception, a couple of years ago) to get a decent language out right.

And still you risk of emitting a useless behemoth that cannot be successfully applied to some interesting domain.

...or another lisp dialect, or another coffeescript.
(see, those have practical applications and usually are conceptually sound, but then again, put in perspective, usually happen to raise more problems then what they solve, and making problems worse is not a good reason to write a new language)

Title: How are Programming Languages Designed?


答:
Be careful.  What you think of as "consistency" might just be a random collection of habits.

"Coordinating user interfaces for consistency", SIGCHI Bulletin 20, (1989), 63-65. Sorry, no link, it's an old article. "... a two-day workshop of 15 experts was unable to produce a definition of consistency."  Yes, it's about "interface", but I believe that if you think about "consistency" for a while, you'll find you can't define it, either.


问:
How would Functional Programming proponents answer this statement in Code Complete?
On page 839 of the second edition, Steve McConnell is discussing all the ways that programmers can "conquer complexity" in big programs. His tips culminate with this statement:

"Object-oriented programming provides a level of abstraction that applies to algorithms and data at the same time, a kind of abstraction that functional decomposition alone didn't provide."

Coupled with his conclusion that "reducing complexity is arguably the most important key to being an effective programmer" (same page), this seems to pretty much a challenge to functional programming.

The debate between FP and OO is often framed by FP proponents around the issues of complexity that derives specifically from the challenges of concurrency or parallelization. But concurrency is certainly not the only kind of complexity software programmers need to conquer. Perhaps focusing on reducing one sort of complexity increases it greatly in other dimensions, such that for many cases, the gain is not worth the cost.

If we shifted the terms of the comparison between FP and OO from particular issues like concurrency or reusability to the management of global complexity, how would that debate look?

EDIT

The contrast I wanted to highlight is that OO seems to encapsulate and abstract away from the complexity of both data and algorithms, whereas functional programming seems encourage leaving the implementation details of data structures more "exposed" throughout the program.

See, e.g., Stuart Halloway (a Clojure FP proponent) here saying that "the over-specification of data types" is "negative consequence of idiomatic OO style" and favoring conceptualizing an AddressBook as a simple vector or map instead of a richer OO object with additional (non-vectorish & non-maplike) properties and methods. (Also, OO and Domain-Driven Design proponents may say that exposing an AddressBook as a vector or map overexposes the encapsulated data to methods that are irrelevant or even dangerous from the standpoint of the domain).

答:
I imagine functional programming proponents would argue that most FP languages provide more means of abstraction than "functional decomposition alone" and do in fact allow means of abstractions comparable in power to those of Object Oriented Languages. For example one could cite Haskell's type classes or ML's higher order modules as such means of abstractions. Thus the statement (which I'm pretty sure was about object orientation vs. procedural programming, not functional programming) doesn't apply to them.

It should also be pointed out that FP and OOP are orthogonal concepts and not mutually exclusive. So it does not make sense to compare them with each other. You could very well compare "imperative OOP" (e.g. Java) vs. "functional OOP" (e.g. Scala), but the statement you quoted would not apply to that comparison.


答: I think in most cases the classic OOP abstraction does not cover the concurrency complexity. Therefore OOP (by its original meaning) doesn't exclude FP, and that's why we see things like scala. </p>

Title: How would Functional Programming proponents answer this statement in Code Complete?

Body:
On page 839 of the second edition, Steve McConnell is discussing all the ways that programmers can "conquer complexity" in big programs. His tips culminate with this statement:

"Object-oriented programming provides a level of abstraction that applies to algorithms and data at the same time, a kind of abstraction that functional decomposition alone didn't provide."

Coupled with his conclusion that "reducing complexity is arguably the most important key to being an effective programmer" (same page), this seems to pretty much a challenge to functional programming.

The debate between FP and OO is often framed by FP proponents around the issues of complexity that derives specifically from the challenges of concurrency or parallelization. But concurrency is certainly not the only kind of complexity software programmers need to conquer. Perhaps focusing on reducing one sort of complexity increases it greatly in other dimensions, such that for many cases, the gain is not worth the cost.

If we shifted the terms of the comparison between FP and OO from particular issues like concurrency or reusability to the management of global complexity, how would that debate look?

EDIT

The contrast I wanted to highlight is that OO seems to encapsulate and abstract away from the complexity of both data and algorithms, whereas functional programming seems encourage leaving the implementation details of data structures more "exposed" throughout the program.

See, e.g., Stuart Halloway (a Clojure FP proponent) here saying that "the over-specification of data types" is "negative consequence of idiomatic OO style" and favoring conceptualizing an AddressBook as a simple vector or map instead of a richer OO object with additional (non-vectorish & non-maplike) properties and methods. (Also, OO and Domain-Driven Design proponents may say that exposing an AddressBook as a vector or map overexposes the encapsulated data to methods that are irrelevant or even dangerous from the standpoint of the domain).


问:
Where should I start on a large concurrent programming assignment?
My task is to implement a distributed semaphore system (links to description) and an application for it. I will be using Java sockets, and it will use watermark arrays and priority queues (not sure where), and so I am curious about how to tackle this project. Specifically, I'd like to know what is a good first-step goal, or a simple subsystem I can implement. At the moment, I just don't know where to focus my attention.

The application is a floating license system - like in a computer lab with only one copy of a software (maybe a CAD program), which allows only one PC at a time to use the software. When one machine is using the software, the access to the software is locked. When that machine is done using it, it gives it up and whomever was first in requesting should be next.

Here's  the pseudo-code algorithm referenced - http://i.imgur.com/q9kRm.png

答:
Generic Answer

Semaphore is a resource allocation technique to manage deadlocks and race conditions via priority queues. Putting it metaphorically, you have 3 bicycles for hire. Suppose, you hire it on a first come first serve basis. So if you have hired all your 3 bicycles and a fourth person requests it, he must wait until one of them has brought the bicycle back. There are chances that you may reserve the bike for someone, someone may cancel a already reserved bike and so on. Similar in case of processes that want to acquire some resources, semaphores are used.

In case of a distributed semaphore, there could be multiple resources that could be accessed by multiple processes. Assume a server hosts an application and can host multiple instances of it and the user can use the application if it is free. Let server be S1,S2,.. Sn while the application be A1,A2,...An and users be U1,U2,...Un. So if the first server could host three instances of the application then it would be denoted as S1A1,S1A2,S1A3. Also assume the application instances as slots or boxes for easy understanding. A slot is considered empty when it is free and full when it is busy. So, in this case, the following method is suggested

User requests the application

The request is passed to a priority queue.

The queue runs a continuous background process to search for free slots and once a free slot is found, passes the request to the application to start processing

Once a slot gets the request, they mark themselves busy and starts processing and marks themselves free when they finish processing

The slots periodically broadcasts their status to the queue so that the queue could forward the requests once a slot becomes free

Recommended resources

This model is based on centralized message brokering. The queue that processes the request should always be available. There can also be broker-less model that could be implemented in a different way

Semaphore Programming  on Wikipedia

The Little Book on Semaphores is a superb resources freely available

Semaphore is based on shared memory model. Actor Model would give a new insight to solve this problem in a different way

Specific answer to the question in context

Looking at the code, I prefer the classical version of a semaphore. Java has a built-in semaphore package to do this and you could just easily build on it.

Specifically, I'd like to know what is a good first-step goal, or a simple subsystem I can implement.

Assuming only one instance of the application should be run on the LAN

Use the package suggested above

Create the semaphore with a built-in queue mechanism (similar to a stack) and implement it as a server

When a user starts the application, it searches for the semaphore, decrements the count (in this case just 0 since only a single instance is to be allowed) and gives user the access to the application

When an other user starts the application, it searches for the semaphore, since it is 0, puts the user in the queue and gives a message to the user that the application is busy

When the first user exits the application, the semaphore is incremented, the resource becomes available, the user is intimated and he can now start the application.

The semaphore can be implemented as a stand-alone server (possibly with a simple web interface) that could be coupled with the application.

The following caveats are worth thinking

Queues may be flushed entirely or priority can be changed

Coupling it with the application as a server, requires there would be only one version of the server on the LAN

Prepare for crashes or unattended message queues (User request access but not available when the application is free)

I would probably suggest the following for better understanding

Follow this link for better understanding

Try SCALA. You can use all your existing JAVA libraries plus you get good concurrency

Have a look at ZMQ. This could be the option if you abstract out the entire process into a separate messaging application that interacts with the resources

Read about the AutoCAD licensing system (they implement a licensing model that matches few of your requirements)

EDIT
Answer completely edited since the original answer is based on a much broader perspective


答:
Functional Programming can have objects, but those objects tend to be immutable. Pure functions (functions without side effects) then operate on those data structures.
It's possible to make immutable objects in object oriented programming languages, but they weren't designed to do it and that's not how they tend to be used. This makes it hard to reason about object oriented programs.

Let's take a very simple example. Let's say that Oracle decided that Java Strings should have a reverse method and you wrote the following code.

```<code>String x = "abc";
StringBuffer y = new StringBuffer(x);
y.reverse();
x.reverse();
x.toString().equals(y.toString());
</code>```

what does the last line evaluate to? You need special knowledge of the String class to know that this would evaluate to false.

What if i made my own class WuHoString

```<code>String x = "abc";
WuHoString y = new WuHoString(x);
y.reverse();
x.reverse();
x.toString().equals(y.toString())
</code>```

It's impossible to know what the last line evaluates to.

In a Functional Programming style it would be written more as follows:

```<code>String x;
equals(toString(reverse(x)), toString(reverse(WuHoString(x))))
</code>```

and it should be true.

If 1 function in one of the most basic classes is so difficult to reason about then one wonders if introducing this idea of mutable objects has increased or decreased the complexity.

Obviously there are all sorts of definitions of what constitutes object oriented and what it means to be functional and what it means to have both. To me you can have a "functional programming  style" in languagess that don't have things like first class functions but other languages are made for it.

Body:
Functional Programming can have objects, but those objects tend to be immutable. Pure functions (functions without side effects) then operate on those data structures.
It's possible to make immutable objects in object oriented programming languages, but they weren't designed to do it and that's not how they tend to be used. This makes it hard to reason about object oriented programs.

Let's take a very simple example. Let's say that Oracle decided that Java Strings should have a reverse method and you wrote the following code.

String x = "abc";
StringBuffer y = new StringBuffer(x);
y.reverse();
x.reverse();
x.toString().equals(y.toString());

what does the last line evaluate to? You need special knowledge of the String class to know that this would evaluate to false.

What if i made my own class WuHoString

String x = "abc";
WuHoString y = new WuHoString(x);
y.reverse();
x.reverse();
x.toString().equals(y.toString())

It's impossible to know what the last line evaluates to.

In a Functional Programming style it would be written more as follows:

String x;
equals(toString(reverse(x)), toString(reverse(WuHoString(x))))

and it should be true.

If 1 function in one of the most basic classes is so difficult to reason about then one wonders if introducing this idea of mutable objects has increased or decreased the complexity.

Obviously there are all sorts of definitions of what constitutes object oriented and what it means to be functional and what it means to have both. To me you can have a "functional programming  style" in languagess that don't have things like first class functions but other languages are made for it.


答:
Ask yourself what value the interviewee is likely to add to your company.  Factor in the cost of having a mentor involved, especially if they can't solve problems at fizzbuzz level.  If the answer isn't commensurate to the intended salary, then you have a good economic case not to hire them.

Don't be afraid to go back to your manager and say "there were no candidates who would add sufficient value to our company to make hiring them worthwhile".  This has to be a better course of action than ending up with someone who is actually of negative value, because of the cost of having someone constantly helping them out.

Title: How to react to wrong/not answered questions during interview?

Body:
Today I have held my first interview with potential interns.
While this has been mostly open questions, I have had some trivial programming tasks for them:

Write a function that returns true if triangle sides (all integers) a, b and c can represent a right triangle.

FizzBuzz.

Calculate the Nth element of Fibonacci using recursion (if they didn't know what Fibonacci was, I would even write them the definition F(n) = F(n-1) + F(n-2); F(1) = 1; F(0) = 1).

Implement structure List for integer and write function to reverse it.

These are obviously very easy tasks and I was not prepared for someone not to solve them.

How should I act when they struggle with these questions? Should I give up the answer? Give tip by tip (I did that and ended up solving the problem myself)? Or just move on (or maybe just stop) with the interview?

ps. By having problems with questions, I don't mean like having a bug, I mean if they can't even get started. This was a case with Fibonacci and List questions.


答:
I find functional programming extremely helpful in managing complexity. You tend to think about complexity in a different way though, defining it as functions that act on immutable data at different levels rather than encapsulation in an OOP sense.

For example, I recently wrote a game in Clojure, and the entire state of the game was defined in a single immutable data structure:

```<code>(def starting-game-state {:map ....
                          :player ....
                          :weather ....
                          :other-stuff ....}
</code>```

And the main game loop could be defined as applying some pure functions to the game state in a loop:

```<code> (loop [initial-state starting-game-state]
   (let [user-input (get-user-input)
         game-state (update-game initial-state user-input)]
     (draw-screen game-state)
     (if-not (game-ended? game-state) (recur game-state))))
</code>```

The key function called is update-game, which runs a simulation step given a previous game state and some user input, and returns the new game state.

So where's the complexity? In my view it has been managed quite well:

Certainly the update-game function does a lot of work, but it is itself built up by composing other functions so it's actually a pretty simple itself. Once you go down a few levels, the functions are still pretty simple, doing something like "add an object to a map tile".

Certainly the game state is a big data structure. But again, it's just built up by composing lower level data structures. Also it's "pure data" rather than having any methods embedded or and class definition required (you can think of it as a very efficient immutable JSON object if you like) so there is very little boilerplate.

OOP can also manage complexity through encapsulation, but if you compare this to OOP, the functional has approach some very big advantages:

The game state data structure is immutable, so a lot of processing can easily be done in parallel. For example, it's perfectly safe to have a rendering calling draw-screen in a different thread from the game logic - they can't possibly affect each other or see an inconsistent state. This is surprisingly difficult with a big mutable object graph......

You can take a snapshot of the game state at any time. Replays are trivial (any thanks to Clojure's persistent data structures, the copies take up hardly any memory since most of the data is shared). You can also run update-game to "predict the future" to help the AI evaluate different moves for example.

Nowhere did I have to make any difficult trade-offs to fit into the OOP paradigm, such as defining a rigid class heirarchy. In this sense the functional data structure behaves more like a flexible prototype-based system.

Finally, for people who are interested in more insights on how to manage complexity in functional vs. OOP languages, I strongly reccoomend the video of Rich Hickey's keynote speech Simple Made Easy (filmed at the Strange Loop technology conference)

Body:
I find functional programming extremely helpful in managing complexity. You tend to think about complexity in a different way though, defining it as functions that act on immutable data at different levels rather than encapsulation in an OOP sense.

For example, I recently wrote a game in Clojure, and the entire state of the game was defined in a single immutable data structure:

(def starting-game-state {:map ....
                          :player ....
                          :weather ....
                          :other-stuff ....}

And the main game loop could be defined as applying some pure functions to the game state in a loop:

 (loop [initial-state starting-game-state]
   (let [user-input (get-user-input)
         game-state (update-game initial-state user-input)]
     (draw-screen game-state)
     (if-not (game-ended? game-state) (recur game-state))))

The key function called is update-game, which runs a simulation step given a previous game state and some user input, and returns the new game state.

So where's the complexity? In my view it has been managed quite well:

Certainly the update-game function does a lot of work, but it is itself built up by composing other functions so it's actually a pretty simple itself. Once you go down a few levels, the functions are still pretty simple, doing something like "add an object to a map tile".

Certainly the game state is a big data structure. But again, it's just built up by composing lower level data structures. Also it's "pure data" rather than having any methods embedded or and class definition required (you can think of it as a very efficient immutable JSON object if you like) so there is very little boilerplate.

OOP can also manage complexity through encapsulation, but if you compare this to OOP, the functional has approach some very big advantages:

The game state data structure is immutable, so a lot of processing can easily be done in parallel. For example, it's perfectly safe to have a rendering calling draw-screen in a different thread from the game logic - they can't possibly affect each other or see an inconsistent state. This is surprisingly difficult with a big mutable object graph......

You can take a snapshot of the game state at any time. Replays are trivial (any thanks to Clojure's persistent data structures, the copies take up hardly any memory since most of the data is shared). You can also run update-game to "predict the future" to help the AI evaluate different moves for example.

Nowhere did I have to make any difficult trade-offs to fit into the OOP paradigm, such as defining a rigid class heirarchy. In this sense the functional data structure behaves more like a flexible prototype-based system.

Finally, for people who are interested in more insights on how to manage complexity in functional vs. OOP languages, I strongly reccoomend the video of Rich Hickey's keynote speech Simple Made Easy (filmed at the Strange Loop technology conference)


问:
Is it better to return NULL or empty values from functions/methods where the return value is not present?
I am looking for a recommendation here.  I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

Take the following two methods as an examples:

string ReverseString(string stringToReverse) // takes a string and reverses it.
Person FindPerson(int personID)    // finds a Person with a matching personID.
```

In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that.  Also, this way, the caller would not have to check to see if a NULL was returned.

In FindPerson(), returning NULL seems like a better fit.  Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).  So why not just return NULL here and then the caller only has to check for NULL.

Does anyone else struggle with this?  Any help or insight is appreciated.

答:
null is the best thing to return if and only if the following following conditions apply:

the null result is expected in normal operation. It could be expected that you may not be able to find a person in some reasonable circumstances, so findPerson() returning null is fine. However if it is a genuinely unexpected failure (e.g. in a function called saveMyImportantData()) then you should be throwing an Exception. There's a hint in the name - Exceptions are for exceptional circumstances!

null is used to mean "not found / no value". If you mean something else, then return something else! Good examples would be floating point operations returning Infinity or NaN - these are values with specific meanings so it would get very confusing if you returned null here.

The function is meant to return a single value, such as findPerson(). If it was designed to return a collection e.g. findAllOldPeople() then an empty collection is best. A corollary of this is that a function which returns a collection should never return null.

In addition, make sure that you document the fact that the function can return null.

If you follow these rules, nulls are mostly harmless. Note that if you forget to check for null, you will normally get a NullPointerException immediately afterwards, which is usually a pretty easy bug to fix. This fail fast approach is much better than having a fake return value (e.g. an empty string) which gets quietly propagated around your system, possibly corrupting data, without throwing an exception.

Finally, if you apply these rules to the two functions listed in the question:

FindPerson - it would be appropriate for this function to return null if the person was not found

ReverseString - seems like it would never fail to find a result if passed a string (since all strings can be reversed, including the empty string). So it should never return null. If something goes wrong (out of memory?) then it should throw an exception.


问:
Is documentation a User Story?
We need to do some user documentation for a product we have been working on for the past few sprints. We are now starting a new project in the next sprint and the PO is making the documentation for the product produced previously a User story for this sprint.

I am just wondering your opinion on this approach. Personally, I don't agree that documentation is a User Story within Scrum because it doesn't produce any code.

EDIT: Thanks for your opinions guys. I had it in the back of my head that a sprint was to implement an increment of working software, but your views have changed my outlook. Thank you for all your answers.

答:
In our organization, the tooling team, in charge of our maintaining and enhancing our continuous integration system is using Scrum to help them manage their work. They are not writing code but they are practicing Scrum nonetheless.

To answer your question specifically, I would ask if the team considers that the documentation is part of the "Definition of Done" or not.

If the team considers that the documentation is part of the "definition of done" then, there is no need for an additional story and the story cannot be accepted unless the documentation is written and validated.

If the team considers that the documentation is not part of the "definition of done", I would create a separate story so that the Product Owner can manage their work.

Title: Is documentation a User Story?


问:
Write Unit test for heavily-database application?
I'm currently developing a Spring-based web-application, in which almost every operation create/update/delete something in the database. The logic mostly about checking condition so as to we should create/update records in the database or not.

The reason I want to try unit test is that we often meets regression errors when request changes or refactor. Most the bugs comes from Database changes, when I doesn't fully reflect those changes in the code. I have some experience in web-development now, but it seems that's not enough to stop them appear.

My controller/service is actually not too complex. I just take the binding object submited from the HttpRequest, check the condition & record in DB. Sometimes the system must read the Database, take out some records & manipulate them, then update some other records.Much of the coding effort lies on the interface(HTML/CSS/Javascript) too.

I'm investigating unit test, and I heard that when it comes to database operation, it's no longer unit test, since the test will be slow. Is that true? So that if my project is heavily database-operation, I shouldn't use unit test?

I also heard about DBUnit & some in-memory database which can quicken the test. Should I use them? And how I can write good unit test for database operation?

答:
You probably should have unit tests and integration tests. In the unit tests, you test for example your controllers/services in isolation. To achieve that, you may use for example a mocking framework such as Easymock or Mockito to cut the dependency to the database.

Your integration tests should go the whole way, from your controllers/services right to the database. You can write your integration tests with the same basic framework as your integration tests (JUnit or TestNG to name the most popular). I personally like DBUnit to prepopulate a database and verify the database state after the test. Whether you use an in-memory database IMO strongly depends on your persistence layer. If you use for example a JPA framework that generates its own queries, I like having an in-memory db. If you write your own SQL-Queries, it can be more difficult to use another DB than your production target as you cannot be sure that the syntax is gonna be equivalent, so an integration test against e.g. an in-memory H2 database not necessarily means that the Syntax works with DB2. This becomes even more problematic if you use stored procedures.

A good integration test itself runs in isolation, meaning that you should set up the database before each test to avoid dependency among tests. You don't want the success of your tests depend on the order they are executed in. After you perform your operations, you should use some kind of assertions to test if the database state is conforming to your expectations. DBUnit for example has its own asserts for comparing Datasets or Tables.


问:
How to keep a big and complex software product maintainable over the years?
I have been working as a software developer for many years now. It has been my experience that projects get more complex and unmaintainable as more developers get involved in the development of the product.

It seems that software at a certain stage of development has the tendency to get "hackier" and "hackier" especially when none of the team members that defined the architecture work at the company any more.

I find it frustrating that a developer who has to change something has a hard time getting the big picture of the architecture. Therefore, there is a tendency to fix problems or make changes in a way that works against the original architecture. The result is code that gets more and more complex and even harder to understand.

Is there any helpful advice on how to keep source code really maintainable over the years?

答:
Code refactoring and unit testing are perfectly fine. But since this long-running project is running in to hacks, this means that the management is not putting its foot down to clean the rot. The team is required to introduce hacks, because somebody is not allocating sufficient resources to train people and analyze the problem/request.

Maintaining a long running project is as much a responsibility of project manager as an individual developer.

People don't introduce hacks because they like it; they are forced by circumstances.


问:
Will Java still be relevant in 5 years?
Will Java have the same importance it had in the past, or it will be less relevant than nowadays?</p>

答:
Java is relevant and will continue to be relevant for many years in the Enterprise computing world.

Whether it continues to be relevant in other areas depends a lot on what Oracle does.  If they inject some life (and resources) into ME, desktop applications and other areas, and if they press on with the evolution of the Java language, then Java will do well.

But if Oracle cuts back on R&D and/or tries to stomp other players in the Java space, there's a good chance that someone / some company will develop a better (and more open) Java-like language.  If Oracle win their lawsuit against Google, I predict that the next generation of the Android platform will have a new language, just like happened with C#.  If Google get the openness right ... then, the game is on!

Title: Will Java still be relevant in 5 years?


问:
Intellectual Property cost
If a piece of bespoke software was developed by a company and the Intellectual Property was retained by the company that wrote it, but now the client of the software company wants to get that source code (and its IP) how much should it cost them? How would you calculate a fair cost for the purchase of that source and IP?

UPDATE: Just to add, the software in question is of no use to anyone else (for any legitimate purpose) as it ties in directly with the business processes of one company. It is not something that can be subsequently sub-licensed or installed outside the company in question. There are links of to third party services (but these were existing services that the bespoke software had to integrate with in the first place).

答:
You saw there was value in retaining ownership in the IP and the source. So does your client. Are there royalties that would be eliminated by their purchase? Do they hope to deny competitors access to the IP? Are there other related markets that are served by the IP?

The question is how do you value the market for the IP and source code? There are many sources on the web to help you determine their value for these properties.

A paper by accounting and management consulting firm PWC outlines several possible methods:

Excess operating profits or premium profits method.

Premium pricing method.

Cost savings method.

Royalty savings method.

Market approach.

Cost approach.

A guide by valuation specialists Valuation & Forensic Partners focuses on market, cost, and income valuation methods and warns,

Optimistic IP developers tend to
  overestimate asset potential. So,
  valuators generally view internal
  projections skeptically, especially
  when valuing unproven technology or
  when management lacks industry
  experience.

But another question to ask yourself is how well can you translate ownership of these properties into capital (in the form of money or some other asset) on your own (either marketing them yourself or licensing them) versus selling them outright?

Edit: In response to your update, two questions that have direct bearing on how valuable the properties are:

Can you mine the source for generalized components that are useful elsewhere?

Now that patents on business processes are deemed valid and have become a key factor in determining business valuation, is securing your IP crucial to patenting their business processes?

If none of these are valid, you might just have to settle for valuing your properties on a cost basis.

Title: Intellectual Property cost