问:
Finding developers for collaboration in enterprise open-source project
I am a founder and only developer of an open-source software designed for a small subset of enterprises. It was originally developed for and now runs at one of businesses of the type it was designed for.

It's my biggest project and I wanted to make something even bigger of it. Creating a software developing company and selling the product is not an option to me, so I decided to make the project open-source and sell the deployment and support services to enterprises in my area.

The problem I faced is that I can't find developers to contribute to the project. Most articles and books on growing open-source community state that developer arrive from the users base, however my project's users base is small and is not related to IT. So it's really unlikely that one of my customers will happen to be an opensource enthusiast who happen to know the stack of technologies I use.

I have been thinking about it for a long time, and seems like the only way to attract someone to collaboration is to look for programmers in my area and offer them to cooperate in both development and commercialization of the project. No one else would be interested in contributing to my project.

Is that correct and no other option exists?

The generalized question is: How do opensource projects with small, non-IT users base (like enterprise software projects) find developers to collaborate?

答:
Milk the user-base for all it's worth. If they request features, ask them to participate in it's development. Some of them might learn the tools they need to help themselves. I'm not just making this up, I've seen it happen in the Maptool community. Encourage them to submit bug reports or feature requests if nothing else.

For enterprise software, you're going to find that you have to market the project, and ask for participation, not from the users, but from their bosses. Most office drones punch out at the end of the day and don't look back. But if the company has a need, they could ask one of their more technically inclined employees to put on a new hat. They probably won't be top notch software developers right off the bat, but they can help. Or the bosses could do something crazy and hire a programmer to work on software they need.

Alternatively, ask your friends to help. They may not bring domain knowledge, and it may not scratch their own itch, but there are altruistic coders out there and people looking for experience. And they're your friends, they should help you out as much as you help them out.


问:
Loop invariant vs Assertions
I have an exam on Programming Concepts this Saturday and I am struggling to find some information to understand some concepts better.

What is the difference between loop invariant and assertion? To me they look the same.

Also, what exactly is while loop invariance theorem?

Not sure whether it is me or it is ridiculously hard to find any specific information about algorithms and pseudocode online.

答:
An invariant is a condition that can be relied upon to be true during execution of a program. For example, a loop invariant is a condition that is true at the beginning and end of every execution of a loop.

An assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place.  Programmers often use assertions in their code to make invariants explicit.

While Loop Invariance Theorem

Assume that S is an invariant of the loop

```<code>While C do
 E
</code>```

Assume also that S is true on the first entry to the loop. Then S stays true after every iteration
of the loop. In particular,

If the loop terminates then S is true after the last iteration.

If the loop does not terminate then S always stays true.

OwnerDisplayName: Vetaxili

ContentLicense: CC BY-SA 3.0

Title: Loop invariant vs Assertions

Body:
An invariant is a condition that can be relied upon to be true during execution of a program. For example, a loop invariant is a condition that is true at the beginning and end of every execution of a loop.

An assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place.  Programmers often use assertions in their code to make invariants explicit.

While Loop Invariance Theorem

Assume that S is an invariant of the loop

While C do
 E

Assume also that S is true on the first entry to the loop. Then S stays true after every iteration
of the loop. In particular,

If the loop terminates then S is true after the last iteration.

If the loop does not terminate then S always stays true.

OwnerDisplayName: Robert Harvey


问:
What's a schrödinbug?
This wiki page tells :

A schrödinbug is a bug that manifests only after someone reading
  source code or using the program in an unusual way notices that it
  never should have worked in the first place, at which point the
  program promptly stops working for everybody until fixed. The Jargon
  File adds: "Though... this sounds impossible, it happens; some
  programs have harbored latent schrödinbugs for years."

What is being talked about is very vague..

Can someone provide an example of how a schrödinbug is like (like with a fictional / real-life situation)?

答:
I have never seen a true schrodinbug and I don't think they can exist--finding it won't break things.

Rather, something changed that exposed a bug that's been lurking for ages.  Whatever changed is still changed and thus the bug keeps showing up while at the same time someone finds the bug.

Title: What's a schrödinbug?


问:
Is use of finally clause for doing work after return bad style/dangerous?
As part of writing an Iterator, I found myself writing the following piece of code (stripping error handling)

```<code>public T next() {
  try {
    return next;
  } finally {
    next = fetcher.fetchNext(next);
  }
}
</code>```

finding it slightly easier to read than

```<code>public T next() {
  T tmp = next;
  next = fetcher.fetchNext(next);
  return tmp;
}
</code>```

I know it's a simple example, where the difference in readability may not be that overwhelming, but I'm interested in the general opinion as to whether it is bad to use try-finally in cases like this where there are no exceptions involved, or if it is actually preferred when it simplifies the code.

If it's bad: why? Style, performance, pitfalls, ...?

Conclusion
Thanks you all your answers! I guess the conclusion (at least for me) is that the first example might have been more readable if it was a common pattern, but that it isn't. Therefore the confusion introduced by using a construct outside of it's purpose, along with possibly obfuscated exception flow, will outweigh any simplifications.

答:
The title statement: "...finally clause for doing work after return..." is false. The finally block happens before the function returns. That is the whole point of finally in fact.

What you are abusing here is the order of evaluation, where the value of next is stored for returning before you mutate it. It is not common practice and in my opinion wrong as it makes you code non-sequential and therefore much harder to follow.

The intended use of finally blocks is for exception handling where some consequence must happen regardless of exceptions being thrown e.g. cleaning up some resource, closing DB connection, closing a file/socket etc.


问:
C++ exceptions vs. preliminary error condition checks

Preamble

One of the concepts used in writing Python code is "Easier to ask for forgiveness than permission", aka EAFP. Literally, this means that instead of doing checks, whether an operation is possible, you do the operation and "ask forgiveness" if what you do fails. Technically this means (just an example with no particular meaning):

```<code>try:
    obj.x = 10
    obj.y = 20
except AttributeError:
    pass
</code>```

This technique is often used when the code in try ... except block is known to run without any errors in most cases, or if the code is rarely executed. The same code with preliminary checks would look as follows:

```<code>if hasattr(obj, 'x'):
    obj.x = 10

if hasattr(obj, 'y'):
    obj.y = 20
</code>```

C++ practices

While generally not an issue in Python, C++ has a "heritage" flame war of "function returning error status" vs. "throwing exceptions". This has been discussed a lot, but I can't find any good source of information which describes whether the Python-like EAFP is applicable in Python.

E.g. consider the following:

```<code>if (node.has_element('x')) {
    node['x'] = 10;
}
</code>```

versus

```<code>try {
    node['x'] = 10;
}
catch(ElementNotFoundException e) {
    // pass
}
</code>```

Which approach is generally used in C++ code? If performance is not the issue, would you write EAFP-fashioned code? Thank you.

答:
In my experience, purposely allowing an exception to be thrown for something predictable is very rare in C++ code.  It's perceived as non-performant, and despite the continually repeated mantra of no premature optimization, C++ programmers have a long culture of premature optimization.

I realize it's just an example for illustration, but in your particular example I might actually go for a third option, which is to design the container so node['x'] = 10 would just be a no-op if the element didn't exist, depending on how frequently this logic was needed compared to an insert.  I hate repeating boilerplate code all over that can be consolidated into one place.

ContentLicense: CC BY-SA 4.0


答:
It's hard to classify something as being generally used in C++. Not only do many companies have their own conventions, but C++ by design lets you compile without exception support at all (no support for stack unwinding, function prologue/epilogue).

That said; ignored exceptions are considered an anti-pattern in most C++ applications, and should usually be complemented by a good, documented reason. The reason not only being performance, but because it's considered an abuse of the try/catch mechanism. The idiom is that it should only be used for exceptional cases, not the normal flow of a program (unlike in Python, in which it is even used for iteration).

Title: C++ exceptions vs. preliminary error condition checks

Body:
Preamble

One of the concepts used in writing Python code is "Easier to ask for forgiveness than permission", aka EAFP. Literally, this means that instead of doing checks, whether an operation is possible, you do the operation and "ask forgiveness" if what you do fails. Technically this means (just an example with no particular meaning):

```<code>try:
    obj.x = 10
    obj.y = 20
except AttributeError:
    pass
</code>```

This technique is often used when the code in try ... except block is known to run without any errors in most cases, or if the code is rarely executed. The same code with preliminary checks would look as follows:

```<code>if hasattr(obj, 'x'):
    obj.x = 10

if hasattr(obj, 'y'):
    obj.y = 20
</code>```

C++ practices

While generally not an issue in Python, C++ has a "heritage" flame war of "function returning error status" vs. "throwing exceptions". This has been discussed a lot, but I can't find any good source of information which describes whether the Python-like EAFP is applicable in Python.

E.g. consider the following:

```<code>if (node.has_element('x')) {
    node['x'] = 10;
}
</code>```

versus

```<code>try {
    node['x'] = 10;
}
catch(ElementNotFoundException e) {
    // pass
}
</code>```

Which approach is generally used in C++ code? If performance is not the issue, would you write EAFP-fashioned code? Thank you.


问:
Why does DirectX use a left-handed coordinate system?
I considered posting on Stack Overflow, but the question strikes me as being far too subjective since I can't think of a reasonable technical explanation for Microsoft's choice in this matter. But this question has bugged me for so long and the issue keeps coming up in one of my projects, and I have never actually seen an attempt at explaining this:

OpenGL uses a right-handed coordinate system, where the +Z part of the world coordinate system extends toward the viewer.

DirectX uses a left-handed system where the +Z part of the world coordinate extends into the screen, away from the viewer.

I never used the Glide API, so I don't know how it worked, but from what I can gather, it uses a left-handed system as well.

Is there a technical reason for this? And if not, is there some conceptual advantage to a particular handedness of a coordinate system? Why would one choose one over the other?

答:
I hate to tell ya, but the 'hand' of a set of coordinates is actually subjective -- it depends on which way you imagine you are looking at things. An example, from the OpenGL cube map spec: if you imagine being inside the cube looking out, the coordinate system is left-handed, if you think of looking in from the outside it is right handed.  This simple fact causes endless grief, because to get a numerically correct answer all of your assumptions have to be consistent, even though locally it doesn't actually matter which assumption you make.

The OpenGL spec is officially "handedness neutral" and goes to great lengths to avoid this issue -- that is, to put it off onto the programmer.  However there is a "hand change" between  eye coordinates and clip coordinates: in model and eye space we are looking in, in clip and device space we are looking out.  I'm always struggling with the consequences of this no doubt accidental complication.

The cross-product is our friend, because it lets you generate a definitely right handed or left handed 3D coordinate system from a pair of vectors.  But which hand it is depends on which of those vectors you call "X".


问:
For small-ish programs, should a single method handle most method calls to centralize program flow?
I'm fairly new to OOP (and programming in general), but what I find myself doing is that in the event that I don't need to pass a value from one method to another, I'll have my method calls centralized in some class within a Form.cs file.

For example:

```<code>public void CentralMethod()
{
    MethodA();
    MethodC();
    MethodD();
}
</code>```

MethodA() will then do some stuff and call MethodB() directly, to which it passes a value.  However after MethodB() is done, control reverts back to CentralMethod() and then MethodC() is called, etc.

I can see how this is a nightmare on a large project, but is this at all a habit that one should get into on a relatively small project?  I didn't necessarily do this by design, but I found myself doing it when it didn't make logical sense to include some method calls within other methods.

答:
You mentioned that your rationale for calling methods this way is when the methods don't pass parameters from one to another. What exactly do you mean by that?

If you mean that the methods are not directly related to a single process (for instance, a PerformMaintenance() method that calls CleanCache() and then CheckForDeadOrders()), then this makes sense. This is a single main method that has several sections, performed independently, but that are a part of the same logical unit of work.

However, if by "don't pass parameters" you mean "use shared member variables", it might be a problem. If you have something like this:

```<code>private List<Order> _orders;
public Order FindMatchingOrder()
{
    LoadOrders();
    SortOrders();
    return _orders.First();
}
</code>```

where the methods share data, but each simply modifies the _orders variable, then yes, I'd say this is bad practice. It's bad practice because it saves persistent state for no reason, which makes your code less thread-safe and possibly prone to other bugs. It's bad practice because the flow of data between the methods isn't clear, since it's not implicit in their contract - a LoadOrders() that returned a list of orders that is then passed to SortOrders would be more explicit.

Body:
You mentioned that your rationale for calling methods this way is when the methods don't pass parameters from one to another. What exactly do you mean by that?

If you mean that the methods are not directly related to a single process (for instance, a PerformMaintenance() method that calls CleanCache() and then CheckForDeadOrders()), then this makes sense. This is a single main method that has several sections, performed independently, but that are a part of the same logical unit of work.

However, if by "don't pass parameters" you mean "use shared member variables", it might be a problem. If you have something like this:

private List<Order> _orders;
public Order FindMatchingOrder()
{
    LoadOrders();
    SortOrders();
    return _orders.First();
}

where the methods share data, but each simply modifies the _orders variable, then yes, I'd say this is bad practice. It's bad practice because it saves persistent state for no reason, which makes your code less thread-safe and possibly prone to other bugs. It's bad practice because the flow of data between the methods isn't clear, since it's not implicit in their contract - a LoadOrders() that returned a list of orders that is then passed to SortOrders would be more explicit.


问:
Is this "anti-pattern" and should I stop using it or is this clever design?
I've basically stared to do the following when creating a REST service:

HTML is requested

service returns the desired web page but without the requested "resource", eg. data

web page contains JavaScript that issues AJAX request to the same service (different content-type)

service then returns the actual data (JSON) and the page displays it

On one side it seems inefficient (2 requests) but then were I used this, "performance is of no concern", meaning low traffic internal app and the web sites are simple and load fast.

The reason I ended up with this is that the web page can then be almost pure Html + JavaScript and almost no server-side stuff is required, especially no loops, to create tables and stuff like that (which I think is very ugly compared to things like slickgrid), e.g. separation of data and view.

Now before I get to using this, is this a good idea or should I just stop doing it?

答:
I wouldn't call it an anti-pattern, what you're describing is more or less a fat client,  not totally unlike services such as Trello. The server's initial responsibility is to send the DOM and whatever resources are needed to make the client work. I've worked on similar projects in data center automation and network monitoring.

The client starts off as a sparse DOM, pulls in some data via XHR (sometimes via JSONP) and finally attaches itself to a socket server. An even more basic example would be a chat application.

The only reason not to do it is that it can be extremely hard to get right. If you're comfortable with asynchronous functional programming and all of the races and other challenges it can present, then you'll have no problem maintaining it. More importantly, you'll have no problem writing it so that other people can eventually maintain it.

If the thought of adding more features begins to frighten you, or you begin to find that debugging is a nightmare, then you might want to consider other methods in production while you continue to experiment and learn.

It is a valid design as long as you're not digging a hole for yourself. If you have gobs and gobs of random JS everywhere instead of a clean interface then you probably want to re-factor or go about the project differently. Most of your functions that are defined to execute once all resources load should be anonymous and entered from a clean interface. If they aren't, you might be headed for trouble.


问:
should you always enter a bug in a bug tracking system

Possible Duplicate:

  Should developers enter bugs into the bug tracking system?

  Should I log trivial fixes?

For a project I'll be doing in school soon I will be working with 6 other people. We will probably be using YouTrack to track our bugs and we can obviously see the value in this system.

My question, however, is whether a bug should always be entered in the bug tracking system. In our case, some people will be front-end developers, others will be back-end developers but the complexity of the project will not be of such a high level that back-end developers wouldn't know how to solve a front end bug. By this I don't mean that they will actually solve it but because they (think) they know it's an easy fix, what's stopping them from just letting one of the front-end developers know about the bug by telling him across the table.

The main reasons I can come up with are these:

The bug might at first seem very easy to fix but actually uncover a far larger problem (at this point in time presumably it would be entered, but by the frond-end developer.

You might take someone of out of the "zone" by just casually mentioning they have a bug somewhere, which might be solved in 10 seconds but then requires them 15 minutes to get back in the zone.

On the other hand it does seem silly that you'd have to enter a bug which could be fixed in 2 minutes, especially if the part you're working on at the time needs that bug to be fixed.

I understand this is probably a bit subjective, but I also feel that other people could give very good reasons for doing it one way or the other which is what I would like to hear.

答:
A paper trail can be useful to cover your ass if things go tits-up and management start asking questions. An official bug will have the details of the bug, the name of the person who fixes it, the names of the people who reviewed it and a way of identifying the actual source code changes.

Managers love processes, it's a good idea to follow them.


问:
Can an entire software infrastructure stack be built entirely from source in-house? Is it practical and sustainable?
I'm a big fan of using open source software but I mostly use community binary releases for the job.

I'm wondering about companies that go the extra degree and build everything they use in their production server application infrastructure entirely from source, in-house, in an effort to promote transparency and supportability (instead of relying on binaries). Is it practical and sustainable to do this?

It seems that the sheer number of dependencies to maintain and build from source for some of the major open source projects would quickly complicate things.

答:
Among the hats I wear is overseeing packaging and installation of the software and the development tool set for one of my company's business units.  We  build everything (almost; see below) from source from scratch nightly using a custom-built, fully-automated process.  Anything not burped out by the build process doesn't ship, no exceptions.

We do this for a lot of reasons:

Safety.  Building from source mitigates the risk that a provided binary has had something malicious added.  If we suspect software-induced foul play, we can go back and audit the sources.

Accountability.  If we change versions of a package, we'll know about it because we put the distributions (usually as the blob, not broken out into individual files) into our VCS.

Maintainability.  As we correct bugs or make enhancements, we write patches that go into our VCS with the distributions and get applied as part of the build process.  As we upgrade to later versions, we remove patches if what they do has been incorporated into the source and review the remainder for relevance.  Patching also adds accountability we wouldn't have otherwise ("that broke after we applied the autodefrobulator patch").

Insight.  Because we go through the process of building sources into packages, we get a good understanding of the dependencies and what quirks there are in the build process.  Because builds are automated, the known-correct process for building the package is scripted and can be read and understood.  In at least one case, we've ditched something because the process of figuring out how to make it build caused us to look closely at the source, when we discovered that the entire thing was poorly written.

There are two things we don't build:

Operating Systems.  The benefit we would get from building the entire thing from source isn't worth the administrative effort.  We get our OS media from sources we trust, usually directly from the vendor, and treat that as a unit.  Most of our OS installations are done from a central server, so we keep that up to date with the latest patches.

Commercial Products.  There are a handful of things we use that are either unavailable or prohibitively expensive in source form.  In those cases, we keep the binary distributions, one for each architecture, in our VCS with everything else.  In some cases, when the vendor provides it in something other than our preferred installation format, we'll actually have a build process that repackages it as we want it.  In all cases, even if the build process is "do nothing, here's your finished package," these go through our automated build process.

Is it practical and sustainable?

Absolutely.  There is a certain level of labor and equipment required to get it started and the kinks worked out, but our process has been set-and-forget.  I haven't done a detailed accounting of it, but I'm pretty sure we spend a lot less time downloading and compiling software because the engineering staff can go look in a well-known place for what they need.  Those of us that do the actual packaging have become are good enough at it that most new additions are available after the next nightly build.

We're not doing anything on the scale of spinning a Red Hat distribution, which involves 3,000+ packages.  We're an order of magnitude smaller than that, but my experience has been that once the figure gets beyond a certain point, consolidating everything into a central system is worthwhile.

It seems that the sheer number of dependencies to maintain and
build from source for some of the major open source projects would
quickly complicate things.

If your builds are done using a packaging system that can handle dependencies and conflicts (e.g., RPM), it's not as difficult as you might think.  We do go through "dependency hell" when we build something that has a lot of prerequisites that are new to us, but once it's done, it's done.  After that, the nightly build takes care of making sure everything is in the right order.  Understanding the dependencies forces us to think about the overall architecture and how new additions fit in.  We'll reconsider something if it's going to turn into a rat's nest.

Addendum based on comments:

Multiple Versions:  I go to great lengths to avoid situations where we need multiple versions of the same thing installed, but sometimes the ugly train stops at your station and you have to board it if you want to get anywhere.  Python has been a bit of a thorn in my side in that respect, because we get a few things from other parts of the company where they've used features from later versions than the one we like to use.  Fortunately, Python is built so multiple versions can be installed in parallel, so we do that and write patches for the "outside" software to force it to use the right one.  On other occasions, I've had to do full repackagings so software requiring a special version of other software has the what it needs bundled in and isolated from the rest of the system.

Upgrades:  I don't do them unless they need to happen.  Once nice thing about building from sources is that you can pick and choose things from later versions if you need them and turn them into patches to your existing version.  I do this with bug fixes.


问:
Use Windows Store controls in a Windows 8 desktop app?
Is it possible to use the Windows 8 Store controls in a Windows 8 desktop app? Controls like the FlipView and SemanticZoom would be useful. </p>

<p>I haven't found any information about this and would presume the answer is no, but thought someone would have a more definitive answer. </p>

答:
Well if my reading comprehension was better, I'd have seen the answer was right on the MSDN page. It's no. :)

http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx


问:
Effectiveness of FizzBuzz and Beyond
As part of the interview process we initially ask the candidates to do 'FizzBuzz' nowadays the percentage of candidates that can correctly answer FizzBuzz has increased dramatically - this may be due to it's popularity on the web.

About a year ago, as a second question we began asking a question very similar to the original FizzBuzz. The question was designed to be as simple as the original FizzBuzz, and to also assess a particular ability of the candidate, specifically the ability to order and prioritize in a meaningful and logical manner a set of "business rules" that have been provided in some arbitrary order. The wording of the question initially seems slightly ambiguous, which may make it difficult for non-native English speakers, but if thought through can be correctly resolved - Also it gives the candidate the opportunity to ask questions for clarification, which is always a good thing.

We find this a very important skill to have as a developer, as software development is typically based on functional requirements that are derived in no particular order over time, that may place constraints and conditions upon other areas of the software without explicitly indicating and it is the job of the astute developer to at the very least investigate potential issues and conflicts with regards to the implementation.

What we found was that a little over 65% of the candidates (sample size of 38) that passed FizzBuzz completely failed FizzBuzz v2.0 Normally these candidates would be detected later on in the process, but it seems to be a nice way to detect them early on.

My question is not about whether or not FizzBuzz is outdated, but rather what factors could be contributing to such a high number of candidates failing the FizzBuzz v2 question.

Is the question too ambiguous?

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

Question:

Write a routine in your favourite programming language that will take a list of strings as input, and for each string in the list will do one of the following:

Print only Fizz if the string contains the letter A

Print only Buzz if the string contains the letter B

Print only BuzzBuzz if the string contains both A and B

Print only FizzFizz if the string does not contain both A and B

Print only FizzBuzz if the string contains only one A and only one B

Some typical questions asked by candidates are:

Should it be case sensitive?

Does "contains A and B" mean A should come before B

What should be printed if none of the points are met?

What should happen if more than one condition can be met?

We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.

答:
If you want to remove any ambiguity, you can change the requirements to:

Write a routine in your favourite programming language that will take a list of strings as input, and for each string in the list do the following:

Print "Fizz" if the string contains the character '$' and does not contain '?'.

Print "Buzz" if the string contains the character '?' and does not contain '$'.

Print "FizzBuzz" if the string contains exactly one '$' and exactly one '?'.

Print "BuzzBuzz" if the string contains exactly one '$' and more than one '?'.

Print "BuzzBuzz" if the string contains exactly one '?' and more than one '$'.

Print "FizzFizz" if the string does not contain '$' and does not contain '?'.

Title: Effectiveness of FizzBuzz and Beyond


问:
How can I understand aggregation and containment?
I'm confused between aggregation and containment. I'm wondering if the following represent an aggregation or containment?</p>

```<code>class Auto
{

   private string model;
   private int speed;

     class AutoCustomer
     {
        public string LastName;
        public string Address;
        public DateTime DateOfPurchase;
     }
}
</code>```

答:
If your class Auto is going to have a reference to the class AutoCustomer, then this represents an example of Aggregation, since the Auto class doesnt OWN the AutoCustomer instance.

But it is sketchy.. since the data members of AutoCustomer are so specific that it might imply ownership after all, which means its just vanilla composition.


答:
It's has the potential to be a much better test than FIZZBUZZ, but if you have any concept of a correct answer, its the worst test in world. These tests have very little value in interviews to start with.

If a candidate answers it "Correctly" without asking a question, then you have a problem that the candidate selection will select the wrong kind of programmer- He is unable to identify ambiguous requirements, or is unable to comprehend that most people cannot write unambiguous requirements. It does not matter if the program is technically perfect in every aspect, it's likely he's the kind of guy that will deliver software with a "I don't care its not what you wanted,  that is what you asked for".

The part of the test here is the priority order of the rules. You do not specify it. Input "ABC" can print Fizz, Buzz, BuzzBuzz or FizzBuzz - any one of these is correct

The candidate I would take is the one who got it (mostly) right, but asked lots of questions and, ideally, did lots of "doddling" on the white board.

For instance, i would explore my understanding of those requirements by giving you a series of samples texts, and asking you what you expected to be printed, and why. - Discussion on my "ABC" example input should lead to some useful insites for you.

Just like FIZZBUZZ, the result of this test is only as good as your observations made on how the result was obtained - the result is irrelevant.

I would tweak it a little - just to make it more interesting - take the 'only' out. It's covered in the line above ("print one of the following"), and see how many people ask about it. If the candidate misses the "only" and you have time, point it out and see what happens. If he deals with the "only", remove it from the requirement and get them to change the code.

Title: Effectiveness of FizzBuzz and Beyond

Body:
As part of the interview process we initially ask the candidates to do 'FizzBuzz' nowadays the percentage of candidates that can correctly answer FizzBuzz has increased dramatically - this may be due to it's popularity on the web.

About a year ago, as a second question we began asking a question very similar to the original FizzBuzz. The question was designed to be as simple as the original FizzBuzz, and to also assess a particular ability of the candidate, specifically the ability to order and prioritize in a meaningful and logical manner a set of "business rules" that have been provided in some arbitrary order. The wording of the question initially seems slightly ambiguous, which may make it difficult for non-native English speakers, but if thought through can be correctly resolved - Also it gives the candidate the opportunity to ask questions for clarification, which is always a good thing.

We find this a very important skill to have as a developer, as software development is typically based on functional requirements that are derived in no particular order over time, that may place constraints and conditions upon other areas of the software without explicitly indicating and it is the job of the astute developer to at the very least investigate potential issues and conflicts with regards to the implementation.

What we found was that a little over 65% of the candidates (sample size of 38) that passed FizzBuzz completely failed FizzBuzz v2.0 Normally these candidates would be detected later on in the process, but it seems to be a nice way to detect them early on.

My question is not about whether or not FizzBuzz is outdated, but rather what factors could be contributing to such a high number of candidates failing the FizzBuzz v2 question.

Is the question too ambiguous?

Does the stress of an interview environment decrease ones ability to think critically to the point of not being able to complete such a trivial task?

Question:

Write a routine in your favourite programming language that will take a list of strings as input, and for each string in the list will do one of the following:

Print only Fizz if the string contains the letter A

Print only Buzz if the string contains the letter B

Print only BuzzBuzz if the string contains both A and B

Print only FizzFizz if the string does not contain both A and B

Print only FizzBuzz if the string contains only one A and only one B

Some typical questions asked by candidates are:

Should it be case sensitive?

Does "contains A and B" mean A should come before B

What should be printed if none of the points are met?

What should happen if more than one condition can be met?

We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.


答: You generally don't need a bug report unless a version of software with the bug exists outside of your development team.  If you don't need one, you might still want one if there's a chance you might forget about it before getting around to fixing it.  For me that means if I haven't fixed it by the end of the day, and it's not in a file I currently have checked out for other reasons.

Title: should you always enter a bug in a bug tracking system

Body:
Possible Duplicate:

  Should developers enter bugs into the bug tracking system?

  Should I log trivial fixes?

For a project I'll be doing in school soon I will be working with 6 other people. We will probably be using YouTrack to track our bugs and we can obviously see the value in this system.

My question, however, is whether a bug should always be entered in the bug tracking system. In our case, some people will be front-end developers, others will be back-end developers but the complexity of the project will not be of such a high level that back-end developers wouldn't know how to solve a front end bug. By this I don't mean that they will actually solve it but because they (think) they know it's an easy fix, what's stopping them from just letting one of the front-end developers know about the bug by telling him across the table.

The main reasons I can come up with are these:

The bug might at first seem very easy to fix but actually uncover a far larger problem (at this point in time presumably it would be entered, but by the frond-end developer.

You might take someone of out of the "zone" by just casually mentioning they have a bug somewhere, which might be solved in 10 seconds but then requires them 15 minutes to get back in the zone.

On the other hand it does seem silly that you'd have to enter a bug which could be fixed in 2 minutes, especially if the part you're working on at the time needs that bug to be fixed.

I understand this is probably a bit subjective, but I also feel that other people could give very good reasons for doing it one way or the other which is what I would like to hear.


答:
More important than filing a bug report is to create a test case that will trigger it.

If it takes only two minutes to fix a bug, how quickly would you forget about it?

Create that test, fix the bug, and it won't raise its ugly head again.

The test case is a living bug report, in the sense that no-one has to browse through a bugs database to evaluate what might need attention.

See also this inspiring lightning talk by Jon Arild Torresdal: Why you shouldn't track bugs

Both @Karl and @Andrew mention an important caveat: After code is released, any bugs that are not (easily) fixed are now part of the product, and should be documented.


问:
Developing on a production server
Today I got yelled at for developing an application on a production server. Quote, "developing on a production server is not acceptable - ever!"

Here is the situation.

I set up a development instance: http://example.com:3000

The production instance is: http://example.com

I complete all my development work on http://example.com:3000 and when the client is pleased with the changes, I move them over to http://example.com.

The application I am working with is an old Ruby on Rails application, and I have to say that initially, I did try to set up an development environment locally, but I could never get it running. After trying for a while, I gave up and decided to develop on the production server.

Again, am I an idiot? Probably so, but I've been doing web development for a couple of years now, and I have never encountered a situation like this. Who is right and why?

答:
This is really a protocol issue.  Generally, this is not something that you would want to be doing.  You want to leave production machines alone.  They may contain sensitive data, and you don't want to compromise the performance or stability of production sites with non-production ready code.

That said, there are times where this is commonly done.  If you are in a position where you are pumping out low traffic brouchureware or simple CMS sites, this will likely be less of an issue.  But if you are working on anything with sensitive data or "business critical" processes, you really shouldn't be risking having development code on the same machine.

Title: Developing on a production server


答:
I used to develop on the production server. It can work fine, but it is inadvisable for at least two reasons:

Development code can cause infinite loops, memory leaks, or other problems that lock up the CPU, eat up all the memory, or otherwise affect the server in a way that will impact your production code.

If you need to make changes to components of the server environment as part of your development work, like the version of Ruby or MySQL or whatever, you'll be in a bind.

Title: Developing on a production server

Body:
Today I got yelled at for developing an application on a production server. Quote, "developing on a production server is not acceptable - ever!"

Here is the situation.

I set up a development instance: http://example.com:3000

The production instance is: http://example.com

I complete all my development work on http://example.com:3000 and when the client is pleased with the changes, I move them over to http://example.com.

The application I am working with is an old Ruby on Rails application, and I have to say that initially, I did try to set up an development environment locally, but I could never get it running. After trying for a while, I gave up and decided to develop on the production server.

Again, am I an idiot? Probably so, but I've been doing web development for a couple of years now, and I have never encountered a situation like this. Who is right and why?


答:
I did try to set up an development environment locally, but I could never get it running. After trying for a while, I gave up and decided to develop on the production server.

I DO support the statements to AVOID development on a production server. You may only be justified to do under the GUN, if it is a typo correction in config file and  insisted by your manager.

WHY NOT? - Because, it is very risky and pron to become a habit later on that would catch you up badly. Because, fatal production errors/failures may cost you to be fired from your work.

Let me re-iterate it again, even-though if you requested to do typo correction on production server, first do it on Staging. or in another words test your changes, test it, and again test it before placing in production.

This is something that happens often in places where culture of  "do it quick and dirty" seems to be a norm.

Edit: Developing on production server, as a separate environment is also NOT acceptable. Any issues caused in your work may simply bring down the production server, and affect the production application performance. As example, i do remember a case when there was a security hole, when my previous co-worker tried to use production server WinServer 2003 for development purposes.

Title: Developing on a production server


答:
Another important reason not to develop directly in production is that a development instance will usually produce and show verbose errors and stack traces. You never want to expose that to the user.

Yes, you can log them instead of showing them to the client, but that makes debugging that much less amusing than it already is.

Added Addressing your side-problem of having trouble with your development instance: I've had great success deploying a VirtualBox-based VM which duplicates our production environment (exclusive of hardware, of course) with an Ubuntu Server.

Title: Developing on a production server


问:
Relationship between user story, feature, and epic?
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?

答:
It's just problem decomposition. They are just stories, except with different sizes.

I personally prefer not to label their sizes, but if you do that is fine as well. Ask you PM what the definition is in your workspace.


答:
I always try and ask other developers what the procedures are for the particular company. In general yes, you should always:

Build locally.

Push it to some type of box that mimics production as much as possible to see if it plays nice there.

Possibly push it to a QA or certification instance to pass to the client/QA team to review the changes.

Push to production.

You can use Capistrano recipes paired with GitHub to handle all of this stuff for you. If you have to do this by hand every time, it can get old fast.

Title: Developing on a production server


答:
At school, I guess it doesn't matter so much...

But out in the big-wide world then without a doubt you should record the bug. There are a number of reasons for this.

Once code has been released, changes should only be made for traceable reasons. This is especially appropriate in regulated industries (aerospace, medical etc) where type approval includes software audits.

It means that the code-change is traceable through the whole lifecycle - particularly testing and release documentation. eg in a tdd project you'll also want to extend the test spec

It may not actually be a bug - you may have misunderstood, or maybe it'swhat the customer wants

It ensures that only one person is trying to fix the bug

It ensures management visibility - when asked why you haven't finished what you SHOULD have been doing, you can show what you HAVE been doing

Doing it properly reduces the risk of accidentally adding in a different (bigger?) bug

There is the chance that the cause of the original bug leads developers to learn lessons

etc


问:
Should one declare alternative response types (e.g. JSON) in Rails controller actions even if not utilising them?
Just wondering what the accepted convention is for Rails controller design. Currently, every controller in my app that I've written it set up to send a JSON response when necessary. Thing is, I only ever utilse HTML responses in my app. So is it a good idea to have them defined?

For example:

```<code>def show
  @dog = Dog.find(params[:id])

  respond_to do |format|
    format.html
    format.json { render json: @dog } # needed?
  end
end
</code>```

It makes the controller code less readable (because more LOC) and it also means I have to think deeply about what a good JSON response should be when HTML is not being is used, so it decreases the speed of my controller development. This is especially true when you have conditional responses.

For example:

```<code>def create
  @dog = Dog.new(params[:dog])

  respond_to do |format|
    if @dog.save
      format.html { redirect_to @dog }
      format.json { render json: @dog, status: :created, location: @dog }
    else
      format.html { render action: "new" }
      format.json { render json: @dog.errors, status: :unprocessable_entity }
    end
  end
end
</code>```

The only positive I can see is that it "future-proofs" the controllers (i.e. if I need JSON responses later on then they are already written).

But if I'm writing JSON responses just because then by that same logic I might as well write XML responses (i.e. format.xml) too...

答:
as it is trivial to add json (or xml, etc) responses later on, I would recommend against implementing them before.

your reasons you give are valid:

it is less readable

you more LOC and thus more code to maintain, more potential bugs

you spend time writing code that you don't need

plus:

you risk exposing attributes that are not meant to be openly accessible

there is no RoR convention to have all actions respond to json.


答:
For last 10+ years I always use bug reports in cases like you describe.

Thing worth keeping in mind is that with sufficient practice, this will take you very little time and effort (that's a matter of fluency).

Another important thing to consider is that using bug tracking should be convenient. Purpose of bug tracking system is to make developer more productive, not less. If it's easier to achieve the same goal without bug tracking tool than with it, this kind of trashes purpose of the tool.

To be precise, it can be somewhat cumbersome at first, when you are getting used to the tool, but if after substantial practice it still doesn't feel easy, this indicates there's something wrong - either with the tool, or with the way you use it, or with the way how bug tracking process is set up in your team.

Taking into account how important is the convenience, have to note that one thing in the title of your question feels really slippery: "always enter a bug".

This appears to assume a new bug report has to be always created - a typical newbie mistake; I made this mistake myself, it gave me quite some pain and it took a while to figure this ain't necessarily so.

It could be sometimes more convenient to just add the bug you discovered to some existing report, or, if you found several bugs, list them in a single report.

In one of the past projects I was assigned to fix issues discovered in code review performed against particular component. Review document listed about 180 (one hundred eighty) items; I sure as hell was going to use bug tracker because I knew it'll be a nightmare to track work progress otherwise.

But I was not going to create 180 separate bug reports either (why would I?) - I just created one for the whole list bug report #123 address code review comments submitted 20.10.2010 against component XYZ.

In the course of my work, some of the items turned out to be worthy dedicated bug reports; no problem I created these when needed. "Progress table" in bug #123 looked about as follows

```<code>review item  status
-------------------
item 1       fixed
...
item 11      not started
...
item 21      in progress
...
item 31      extracted to bug report id #234
...
</code>```

it does seem silly that you'd have to enter a bug which could be fixed in 2 minutes

Silliness here depends on how much time does it take you to register the bug you discovered.

If it takes say, half an hour, it's definitely silly. If it takes 5-10 minutes, it's not too smart but may be OK if happens infrequently. Finally, if it takes less than a minute, why not - I see nothing silly here.

Actually, in cases like that it just takes me less than a minute, and here's why. Look, here's what you have

the part you're working on at the time needs that bug to be fixed

As for me, the part I am working on is always registered in the issue tracker. When I find a 2-minute-bug needed to be fixed for that part, I just add a comment in the bug report I am working on, like

```<code>discovered and fixed <this bug>
</code>```

Heck I do this even if the fix isn't needed right now. Why wouldn't I?

Body:
For last 10+ years I always use bug reports in cases like you describe.

Thing worth keeping in mind is that with sufficient practice, this will take you very little time and effort (that's a matter of fluency).

Another important thing to consider is that using bug tracking should be convenient. Purpose of bug tracking system is to make developer more productive, not less. If it's easier to achieve the same goal without bug tracking tool than with it, this kind of trashes purpose of the tool.

To be precise, it can be somewhat cumbersome at first, when you are getting used to the tool, but if after substantial practice it still doesn't feel easy, this indicates there's something wrong - either with the tool, or with the way you use it, or with the way how bug tracking process is set up in your team.

Taking into account how important is the convenience, have to note that one thing in the title of your question feels really slippery: "always enter a bug".

This appears to assume a new bug report has to be always created - a typical newbie mistake; I made this mistake myself, it gave me quite some pain and it took a while to figure this ain't necessarily so.

It could be sometimes more convenient to just add the bug you discovered to some existing report, or, if you found several bugs, list them in a single report.

In one of the past projects I was assigned to fix issues discovered in code review performed against particular component. Review document listed about 180 (one hundred eighty) items; I sure as hell was going to use bug tracker because I knew it'll be a nightmare to track work progress otherwise.

But I was not going to create 180 separate bug reports either (why would I?) - I just created one for the whole list bug report #123 address code review comments submitted 20.10.2010 against component XYZ.

In the course of my work, some of the items turned out to be worthy dedicated bug reports; no problem I created these when needed. "Progress table" in bug #123 looked about as follows

review item  status
-------------------
item 1       fixed
...
item 11      not started
...
item 21      in progress
...
item 31      extracted to bug report id #234
...

it does seem silly that you'd have to enter a bug which could be fixed in 2 minutes

Silliness here depends on how much time does it take you to register the bug you discovered.

If it takes say, half an hour, it's definitely silly. If it takes 5-10 minutes, it's not too smart but may be OK if happens infrequently. Finally, if it takes less than a minute, why not - I see nothing silly here.

Actually, in cases like that it just takes me less than a minute, and here's why. Look, here's what you have

the part you're working on at the time needs that bug to be fixed

As for me, the part I am working on is always registered in the issue tracker. When I find a 2-minute-bug needed to be fixed for that part, I just add a comment in the bug report I am working on, like

discovered and fixed <this bug>

Heck I do this even if the fix isn't needed right now. Why wouldn't I?


问:
serving static or dynamic web-content based on user group
I need help understanding a problem I have, and that others surely have had as well.

I'm working on a web-application that allows users to interface with a database. The application in general has multiple pages with tabbed navigation, that displays and allows most content to be editable. So far, it works well.

I need to restrict access to certain pages and disable dynamic (editable) content of the application based on the group (in the database) that the User belongs to, sounds simple, maybe it is. The issue is though, the editable pages have input of type buttons and text which should disappear for a user in a restricted group. Also, certain tabbed-navigation selections should not be displayed for Users of a restricted group. At what point in my application should this logic be handled?

Using javascript for this logic seems like the wrong approach (using a library like underscore.js with templates), but I do need to hide or disable multiple options. My other thought was having dynamic and static web-pages and serve those based on User group.

It's clear that I'm lost on this subject, and could use some insight as how this problem should be approached in a way that is sane so the next guy behind me won't say...wtf.

I'm not sure if this question is better suited for stackoverflow or here. So hopefully this is the right place!

答:
This type of thing is usually handled by a server-side script: if a user is logged in, and has permission to edit the page, the script inserts suitable controls into the HTML output. Also, whenever any request is received that is related to page editing, the check needs to be repeated; if it's not, it is very easy for malicious users to circumvent the protection (guessing the correct URL is all it takes).

Doing this on the client side is not really an option; client-side script can be modified by the user, and there is absolutely nothing you can do about that. You can insert the editing controls client-side, but the permission check absolutely has to happen on the server, otherwise bypassing it is as simple as changing a variable value in the javascript console (or by typing a javascript: URL into the address bar if you're really old-school).


答:
The word "only" in your requirements creates a contradiction in all questions.

Thus your question tests requirements gathering while under pressure, are you sure you want to test for that combination of skills?

If you want to test requirement gathering, I would suggest making ONE of the questions ambiguous.  If you want a replacement for FizzBuzz, remove the ambiguity.

Prioritizing business rules can only be done with domain specific knowledge -- unless you include some simple context for what you are doing (perhaps they are coupons to be redeemed for various values), there's no basis for the developer to make his own decision.

But requiring someone to ask for clarifcation where doing so has a significant risk of undesirable outcome, is perhaps not the best way of gauging their skill in recognizing the limits of their knowledge.  They may figure that it is safer to guess and get it wrong, than to point out that you are incompetent at writing requirements, or if none of the interviewers are developers, being labeled as having a bad attitude.

Title: Effectiveness of FizzBuzz and Beyond


问:
Why is it often said that the test cases need to be made before we start coding?
Why is it often said that the test cases need to be made before we start coding?

What are its pros and what the cons if we don't listen to this advice?

Moreover, does that advice refer to black box testing or White Box testing or both?

答:
It is said in the context of practising TDD/BDD, which are design methodologies, not test methodologies.

With TDD/BDD, the idea is to drive out the API usage before writing the API, evolving it with tests.

Seen in this light, the point is to write a test for a non-existing API call or a test for a non-existing API behaviour and then implementing it.

As for blackbox/whitebox testing - again, this isn't about testing - it is about design.


答:
What your doing sounds good! However if your json responses contain any HTML then your wasting your time. </p>

<p>Another point though is your dumb client should probably getting its json data from a different project. You should aim for proper separation between client and service then you will have a proper RESTful service </p>

Title: Is this "anti-pattern" and should I stop using it or is this clever design?

Body:
I've basically stared to do the following when creating a REST service:

HTML is requested

service returns the desired web page but without the requested "resource", eg. data

web page contains JavaScript that issues AJAX request to the same service (different content-type)

service then returns the actual data (JSON) and the page displays it

On one side it seems inefficient (2 requests) but then were I used this, "performance is of no concern", meaning low traffic internal app and the web sites are simple and load fast.

The reason I ended up with this is that the web page can then be almost pure Html + JavaScript and almost no server-side stuff is required, especially no loops, to create tables and stuff like that (which I think is very ugly compared to things like slickgrid), e.g. separation of data and view.

Now before I get to using this, is this a good idea or should I just stop doing it?

Body:
What your doing sounds good! However if your json responses contain any HTML then your wasting your time.

Another point though is your dumb client should probably getting its json data from a different project. You should aim for proper separation between client and service then you will have a proper RESTful service


答:
Why is it often said that the test cases need to be made before we start coding?

It's a basic principle of test-driven development, but not a general "best practice". Not everyone wants or needs to do TDD, even though its proponents often claim that everyone would benefit from it.

What are its pros and what the cons if we don't listen to this advice?

The advantage is that it forces you to think about your code from a perspective of testing before you write it, which has two main advantages: you're less likely to forget about special cases and boundary conditions, and your code has to be testable and thus modular. Another important benefit: at any time you know that your code is working as you thought it should.

The disadvantage is that it may encourage thinking about low-level details and overlook important design issues (but the same can happen if you just start coding). Also, the most easily testable design is not necessarily the best (but probably much better than one grown out of ad hoc coding).

Of course there's the question whether TDD saves more time than writing all those unit tests costs. Its proponents certainly claim so.

Moreover, does that advice refer to black box testing or White Box testing or both?

Usually, TDD deals exclusively with unit tests, which are white box tests. Integration tests have to be done additionally.

Body:
Why is it often said that the test cases need to be made before we start coding?

What are its pros and what the cons if we don't listen to this advice?

Moreover, does that advice refer to black box testing or White Box testing or both?


答:
As others have stated, coding on the PROD environment exposes your users to your bugs. Even if you've started a different instance, you've still got shared hardware resources and can still access production files and databases. And as some of the comments point out, if your Dev instance gets hacked (for example, because you forget to wipe it and someone then discovers a massive security exploit in Rails), you've now got a publicly accessible machine with your app acting as a gateway in. Which would be... unfortunate.

Different businesses have different responses to this, but it can be generally broken down like this:

Did a screw-up occur?

How long would it take to revert a change (I primarily work in C++, so rolling back a binary can take significantly longer than in Ruby, especially when you've "lost" the old binary and have to recompile)

What the effect of the change (rough guide: screwing up stored data is so much worse than not storing or displaying data, which in turn is worse than not showing the page at all)

If you screwed up then walked out the door, would anyone know what you'd done?

Was there another deployment option that would have prevented/minimized/detected the screw-up before impact?

This gives you the final calculation:

How much would this completely preventable screw-up have cost the business?

This is now how much less your entire management structure is worth to the guy making budget decisions. Hence shouty.

If you're working on the company's internal "About Us" page and typo your own name to be L. "God-like" Thomas, embarrassing nickname problem; if you're working on the business-critical purchasing app, and it ends up accidentally plain-text debugging out credit card details to the homepage... lawsuit problem. Between those extremes lie everything from mischarging, crippling productivity, and all the other things that can drive away customers.

The reason not to allow it even for the "About Us" page is because coding directly in production is addictive. You start by only doing it for the minors, but over time, it's so much quicker not to have to get the DEV env up to scratch.

Beyond that, the size of the business can have a big effect. In a two-man team, when something goes phut, you lean over your shoulder and go "Oi, jackass, put it back". In a 300-person company, you have to start worrying about whether it was incompetence or malice, managers can be held responsible for stuff they had no control over, etc.

At the end of the day, if you follow procedure and screw up, they check what's wrong with the procedure. If you skirt procedure and screw-up, it's now your responsibility alone, even if the blame gets spread out a bit. Whether you want to roll the dice on that is up to you.

Title: Developing on a production server


答:
Writing tests before implementations is one of the core ideas behind Test Driven Development (TDD). The procedure is:

write a failing test

change the code to make it pass, without breaking any other test

refactor the code, verify that all tests still pass

This procedure is the same whether you implement a feature or fix a bug; it is often referred to as "Red-Green-Refactor" (red = test fails, green = test passes). The advantages of this method are numerous:

the test clearly defines what constitutes "done"

the test documents how you intend the code to be used

if you do it right, you build a complete test suite with 100% coverage as a by-product of your development process, which means you always have reliable regression tests at hand no matter what you do

coding to meet a test case (and nothing else) helps keep you focused on one task and prevents feature creep

the red-green-refactor cycle makes for a nice, clean and tracable commit history and fits a feature branch repository approach well (each feature branch starts with a commit that adds a failing test, then one or more commits until "green" is reached, and then one or more refactoring commits).

you produce working versions at regular intervals - ideally, each red-green-refactor cycle ends with a potentially shippable product, but at the very least, it should build without failures and pass all the tests.

Now for the downsides:

Not all code lends itself to automated testing. This can be because it's a legacy codebase written without automated tests in mind; it can be because the problem domain is such that certain things cannot be mocked; or maybe you rely on external data sources that are not under your control and would be too complicated to mock; etc.

Sometimes, correctness, maintainability and stability are not high enough on the priority list. This sounds bad, but it doesn't have to be: if you're writing a one-use script to batch convert a bunch of documents, writing tests at all is silly - you just run it on a few test documents, eyeball the result, and that's that. Automated testing wouldn't add any value here.

Writing the test before writing the code implies that you already know exactly what you want done. Quite often, though, you don't, and a significant amount of explorative programming is required to get a feeling for the particular problem domain; and more often than not, the results of such explorative coding are then bashed into shape to become the real product. Automated tests are just as valuable for such products, but it doesn't make much sense adding them before you know what you're going to make. In this case, it's better to take the prototype at the end of the explorative phase, add tests to cover everything you have so far, and switch to red-green-refactor from there.

Test-before-implementation isn't everyone's cup of tea; writing the implementation first feels more natural, and some people have an easier time getting into a flow that way

Title: Why is it often said that the test cases need to be made before we start coding?


问:
Recursion or while loops
I was reading about some development interview practices, specifically about the technical questions and tests asked at interviews and I've stumbled quite a few times over sayings of the genre "Ok you solved the problem with a while loop, now can you do it with recursion", or "everyone can solve this with a 100 lines while loop, but can they do it in a 5 lines recursive function?" etc.

My question is, is recursion generally better than if/while/for constructs?

I've honestly always thought that recursion is not to be preferred, because it's limited to the stack memory which is a lot smaller than the heap, also doing a great number of function/method calls is suboptimal from a performance standpoint, but I may be wrong...

答:
It depends.

Some problems are very amenable to recursive solutions e.g. quicksort

Some languages don't really support recursion e.g. early FORTRANs

Some languages assume recursion as a primary means for looping e.g. Haskell

It's also worth noting that support for tail recursion makes tail recursive and iterative loops equivalent, that is, recursion doesn't always have to waste the stack.

Also, a recursive algorithm can always be implemented iteratively by using an explicit stack.

Finally, I'd note that a five-line solution is probably always better than a 100 line one (assuming they are actually equivalent).

Title: Recursion or while loops


问:
Are there any OO-principles that are practically applicable for Javascript?
Javascript is a prototype-based object oriented language but can become class-based in a variety of ways, either by:

Writing the functions to be used as classes by yourself

Use a nifty class system in a framework (such as mootools Class.Class)

Generate it from Coffeescript

In the beginning I tended do write class based code in Javascript and heavily relied on it. Recently however I've been using Javascript frameworks, and NodeJS, that go away from this notion of classes and rely more on the dynamic nature of the code such as:

Async programming, using and writing writing code that uses callbacks/events

Loading modules with RequireJS (so that they don't leak to the global namespace)

Functional programming concepts such as list comprehensions (map, filter, etc.)

Among other things

What I gathered so far is that most OO principles and patterns I've read (such as SOLID and GoF patterns) were written for class-based OO languages in mind like Smalltalk and C++. But are there any of them applicable for a prototype-based language such as Javascript?

Are there any principles or patterns that are just specific to Javascript? Principles to avoid callback hell, evil eval, or any other anti-patterns etc.

答:
Adding to Daniels answer:

Observable values/components

This idea is borrowed from the MVVM framework Knockout.JS (ko.observable), with the idea that values and objects can be observable subjects, and once change happens in one value or object it will automatically update all the observers. It is basically the observer pattern implemented in Javascript, and instead how most pub/sub frameworks are implemented, the "key" is the subject itself instead of an arbitrary object.

The usage is as follows:

```<code>// the subjects
// plain old javascript object with observable values
var shipComponent = {
    velocity : observable(0)
};

// the observer, a player user interface
// implemented with revealing module pattern
var playerUi = (function(ship) {

  var module = {
    setVelocity: function (x) {
      // ... sets the velocity on the player user interface
    },

    // only called once
    init: function() {

      // subscribe to changes on the velocity value
      // using the module's function as callback
      module.velocity.onChange(playerUi.setVelocity);
    }
  };

  return module;
})(shipComponent).init();

// the player ui will change when the velocity value is changed
shipComponent.velocity.set(10);
</code>```

The idea is that observers usually know where the subject is and how subscribe to it. The advantage of this instead of the pub/sub is noticeable if you have to change the code a lot as it is easier to remove subjects from as a refactoring step. I mean this because once you remove a subject everyone who was dependent on it will fail. If code fails fast then you know where to remove the remaining references. This is in contrast with the completely decoupled subject (such as with a string key in pub/sub pattern) and has a higher chance to stay in the code especially if dynamic keys were used and the maintenance programmer was not made aware of it (dead code in maintenance programming is an annoying problem).

In game programming, this reduces the need of ye olde update loop pattern and more into an evented/reactive programming idiom, because as soon as something is changed the subject will automatically update all observers on the change, without having to wait for the update loop to execute. There are uses for the update loop (for things that needs to be synchronized with elapsed game time), but sometimes you just don't want to clutter it down when the components themselves can auto-update themselves with this pattern.

The actual implementation of the observable function is actually surprisingly easy to write and understand (especially if you know how to handle arrays in javascript and the observer pattern):

```<code>var observable = function(v) {
    var val = v, subscribers = [];

    // the observable object,
    // as revealing module
    var output = {

        // subscribes to event
        onChange : function(func) {
            // idiomatic JS to add object to the
            // subscribers array
            subscribers.push(func);

            return output: // enables chaining
        },

        // the method that changes the observable object
        // and emits the event
        set : function(v) {
            var i;
            val = v;
            for (i = 0, i < subscribers.length; i++) {
                // this is hardly fault tolerant but as long
                // as subscribers are functions it'll work
                subscribers[i](v);
            }

            return output;
        }

    };

    return output;
};
</code>```

I've made an implementation of the observable object in JsFiddle that continues on this with observing components and being able to remove subscribers. Feel free to experiment the JsFiddle.

Body:
Adding to Daniels answer:

Observable values/components

This idea is borrowed from the MVVM framework Knockout.JS (ko.observable), with the idea that values and objects can be observable subjects, and once change happens in one value or object it will automatically update all the observers. It is basically the observer pattern implemented in Javascript, and instead how most pub/sub frameworks are implemented, the "key" is the subject itself instead of an arbitrary object.

The usage is as follows:

// the subjects
// plain old javascript object with observable values
var shipComponent = {
    velocity : observable(0)
};

// the observer, a player user interface
// implemented with revealing module pattern
var playerUi = (function(ship) {

  var module = {
    setVelocity: function (x) {
      // ... sets the velocity on the player user interface
    },

    // only called once
    init: function() {

      // subscribe to changes on the velocity value
      // using the module's function as callback
      module.velocity.onChange(playerUi.setVelocity);
    }
  };

  return module;
})(shipComponent).init();

// the player ui will change when the velocity value is changed
shipComponent.velocity.set(10);

The idea is that observers usually know where the subject is and how subscribe to it. The advantage of this instead of the pub/sub is noticeable if you have to change the code a lot as it is easier to remove subjects from as a refactoring step. I mean this because once you remove a subject everyone who was dependent on it will fail. If code fails fast then you know where to remove the remaining references. This is in contrast with the completely decoupled subject (such as with a string key in pub/sub pattern) and has a higher chance to stay in the code especially if dynamic keys were used and the maintenance programmer was not made aware of it (dead code in maintenance programming is an annoying problem).

In game programming, this reduces the need of ye olde update loop pattern and more into an evented/reactive programming idiom, because as soon as something is changed the subject will automatically update all observers on the change, without having to wait for the update loop to execute. There are uses for the update loop (for things that needs to be synchronized with elapsed game time), but sometimes you just don't want to clutter it down when the components themselves can auto-update themselves with this pattern.

The actual implementation of the observable function is actually surprisingly easy to write and understand (especially if you know how to handle arrays in javascript and the observer pattern):

var observable = function(v) {
    var val = v, subscribers = [];

    // the observable object,
    // as revealing module
    var output = {

        // subscribes to event
        onChange : function(func) {
            // idiomatic JS to add object to the
            // subscribers array
            subscribers.push(func);

            return output: // enables chaining
        },

        // the method that changes the observable object
        // and emits the event
        set : function(v) {
            var i;
            val = v;
            for (i = 0, i < subscribers.length; i++) {
                // this is hardly fault tolerant but as long
                // as subscribers are functions it'll work
                subscribers[i](v);
            }

            return output;
        }

    };

    return output;
};

I've made an implementation of the observable object in JsFiddle that continues on this with observing components and being able to remove subscribers. Feel free to experiment the JsFiddle.


答:
As usual, this is unanswerable in general because there are additional factors, which in practice are widely unequal between cases and unequal to each other within a use case. Here are some of the pressures.

Short, elegant code is in general superior to long, intricate code.

However, the last point is somewhat invalidated if your developer base is not familiar with recursion and unwilling/unable to learn. It may even become a slight negative rather than a positive.

Recursion can be bad for efficiency if you will need deeply-nested calls in practice and you can't use tail recursion (or your environment can't optimize tail recursion).

Recursion is also bad in many cases if you can't properly cache intermediate results. For instance, the common example of using tree recursion to compute Fibonacci numbers performs horribly bad if you don't cache. If you do cache, it's simple, fast, elegant and altogether wonderful.

Recursion is not applicable to some cases, just as good as iteration in others, and absolutely necessary in yet others. Plodding through long chains of business rules is usually not helped by recursion at all. Iterating through data streams can be usefully done with recursion. Iterating over multidimensional dynamic data structures (e.g. mazes, object trees...) is pretty much impossible without recursion, explicit or implicit. Note that in these cases, explicit recursion is much better than implicit - nothing is more painful than reading code where somebody implemented their own ad-hoc, incomplete, buggy stack within the language just to avoid the scary R-word.

Title: Recursion or while loops

Body:
I was reading about some development interview practices, specifically about the technical questions and tests asked at interviews and I've stumbled quite a few times over sayings of the genre "Ok you solved the problem with a while loop, now can you do it with recursion", or "everyone can solve this with a 100 lines while loop, but can they do it in a 5 lines recursive function?" etc.

My question is, is recursion generally better than if/while/for constructs?

I've honestly always thought that recursion is not to be preferred, because it's limited to the stack memory which is a lot smaller than the heap, also doing a great number of function/method calls is suboptimal from a performance standpoint, but I may be wrong...


答:
We found that the overwhelming majority of candidates that successfully completed the question, didn't ask anything at all they just did it like they did FizzBuzz.

With the ambiguity of the requirements one can not finish v2.0 correctly without asking questions.

Title: Effectiveness of FizzBuzz and Beyond


答:
There's no universally agreed on definition of "better" when it comes to programming, but I'll take it to mean "easier to maintain/read".

Recursion has more expressive power than iterative looping constructs: I say this because a while loop is equivalent to a tail recursive function and recursive functions need not be tail recursive. Powerful constructs are usually a bad thing because they allow you to do things that are difficult to read. However, recursion gives you the ability to write loops without using mutability and to my mind mutability is much more powerful than recursion.

So, from low expressive power to high expressive power, looping constructs stack up like this:

Tail recursive functions that use immutable data,

Recursive functions that use immutable data,

While loops that use mutable data,

Tail recursive functions that use mutable data,

Recursive functions that use mutable data,

Ideally, you'd use the least expressive constructs that you can. Of course, if your language doesn't support tail call optimization, then that may also influence your choice of looping construct.

Title: Recursion or while loops


答:
Use the strategy design pattern.

Recursion is clean

Loops are (arguably) efficient

Depending on your load (and/or other conditions), choose one.

Title: Recursion or while loops


问:
Effective implementation of "array" of type Int X String -> String in .NET or in general
The question in general is: is there a more effective way of implementation of table with structure like Dictionary<int, Dictionary<string, string>>?

The reason I am asking this is because I have made few performance tests and it does not perform well for data with > 5M rows. Now, I dont really need this amount of data but I was wandering if there is a more effective way. It could also help performance for smaller tables with thousands of rows. Last but not least I am interested in what COULD be done to improve it.

What I have thought of is to use string[][] and have some method transform string rows/column to numbers. That would however require a quite significant rewrite of my work so far. Is there something simpler? I need rows to be able to handle gaps.

Background on my project:

I have a home brewed structure of objects that represent a table along with some additional functionality that I need. I have table called T, and it stores data (rows) in Dictionary<int, TRow>. Each TRow has another dictionary<string, TCell> that represents the row data, in which TCells are indexed by column names. TCells is basically a wrapper around simple string. Table and each row has a Schema definition (column -> {INT, DOUBLE, STRING, BOOL, ...} that is parsed when getting data from the table by methods like .getBool( int row, string column ) etc. Each object (T,TRow,TCell) has quite a lot of helper methods that I use, so they are not a simple wrapper with get methods.

EDIT TO ANSWER FOLLOW-UP QUESTIONS:
The table is meant for general purpose. No special focus on reading/writing only. The table is often initially loaded from result-set produced by stored procedure in database and then only read from - but not exclusively. The composite key is an interesting idea, but that would break my T, TRow, TCell structure I am afraid. The Dictionary INT X STRING -> STRING is only a simplification, as written in my last paragraph the table T has Dictionary< int, TRow> and TRow has Dictionary< string, string >. The reason I need to keep Table, Row and Cell broken up is that sometimes I work directly with rows, e.g. some method can return a single row etc. Any ideas please? Or there is nothing better :/.

答:
It all depends on what operations are you doing often. Writing? Reading? Do you work separately with Dictionary<string, string> or do you always work with Dictionary<int, Dictionary<string, string>> as a whole? Also, you are saying you have rows and columns. Do you add/remove them, or are they constant for each instance of this dictionary?

First thing that comes to mind is to create a composite key from int and string, and use that as a key for dictionary.

```<code>public struct IntStringKey
{
    public int A {get; private set;}
    public string B {get; private set;}

    public IntStringKey(int a, string b)
    {
        A = a;
        B = b;
    }

    // override GetHash and Equals here
}
</code>```

And then use it :

```<code>Dictionary<IntStringKey, string> data;
</code>```

This will make it easier on GC, because you are not creating so many internal dictionaries and also you call the get/set only once.

Body:
It all depends on what operations are you doing often. Writing? Reading? Do you work separately with Dictionary<string, string> or do you always work with Dictionary<int, Dictionary<string, string>> as a whole? Also, you are saying you have rows and columns. Do you add/remove them, or are they constant for each instance of this dictionary?

First thing that comes to mind is to create a composite key from int and string, and use that as a key for dictionary.

public struct IntStringKey
{
    public int A {get; private set;}
    public string B {get; private set;}

    public IntStringKey(int a, string b)
    {
        A = a;
        B = b;
    }

    // override GetHash and Equals here
}

And then use it :

Dictionary<IntStringKey, string> data;

This will make it easier on GC, because you are not creating so many internal dictionaries and also you call the get/set only once.


答:
Recursion is often less obvious. Less obvious is harder to maintain.

If you write for(i=0;i<ITER_LIMIT;i++){somefunction(i);} in the main flow, you make it perfectly clear you are writing a loop. If you write somefunction(ITER_LIMIT); you don't really make it clear what will happen. Only seeing content: that somefunction(int x) calls somefunction(x-1) tells you it is in fact a loop using iterations. Also, you can't easily put an escape condition with break; somewhere halfway the iterations, you must either add a conditional that will be passed all the way back, or throw an exception. (and exceptions again add complexity...)

In essence, if it's an obvious choice between iteration and recursion, do the intuitive thing. If iteration does the job easily, saving 2 lines is rarely worth the headaches it may create in the long run.

Of course if it's saving you 98 lines, that's an entirely different matter.

There are situations for which recursion simply fits perfectly, and they aren't really uncommon. Traversal of tree structures, multiply-linked networks, structures that can contain its own type, multi-dimensional jagged arrays, essentially anything that isn't either a straightforward vector or an array of fixed dimensions. If you traverse a known, straight path, iterate. If you dive into unknown, recurse.

Essentially, if somefunction(x-1) is to be called from within itself more than once per level, forget iterations.

...Writing iteratively functions for tasks that are best done by recursion is possible but not pleasant. Wherever you'd use int, you need something like stack<int>. I did it once, more as an exercise than for practical purposes. I can assure you once you face such a task you won't have doubts like the ones you expressed.

Title: Recursion or while loops


答:
When I am writing test first, it isn't much a matter of verifying correct functioning of my code, not really a matter of black box or white box or whatever related to quality assurance, and here is why...

Over the years I practiced and polished a skill to convince management that I need good testers 1, 2, 3 and this suffices to ensure that my code will work as intended without me having to think much about it.

Main reason why I prefer test first is it helps me understand how to design my code so that it's convenient to use. I am not good at imagining in my head how my module will be used by other modules so I can do it overly complicated and that will bite me later and possibly even require redesign.

This is a problem no matter whether I am coding a module for myself or for someone else, it is equally painful using inconvenient interface myself as well as having to explain its usage to other programmers.

"Test-first" approach saves me from that pain; it doesn't require imagination to immediately see how my module will be used if designed this or that way and makes it easy to choose the more convenient one.

When coding module for someone else, it also saves me from the need to painfully explain how to use it.

Look, code in this test shows how you should use that module and if you run it, you'll also see what results you should expect. Using any other way than shown in this test would be a mistake. Now go away and let me do something interesting.


问:
How do you approach database design?
I am primarily a web developer and I have a couple of personal projects which I want to kick off.

One thing that is bugging me is database design. I have gone through in school db normalization and stuff like that but it has been a couple of years ago and I have never had experience with relational database design except for school.

So how you do you approach database from a web app perspective? How do you begin and what do you look out for? What are flags for caution?

答:
In general terms, good database design is good database design - the bigger question for web use will be how you access the data and manage things that one might consider require state which basically the web doesn't have.

Thinking about it, my approach is based on really rather a lot of experience... but whether you start with schema or objects you're actually trying to do the same thing i.e. build a useable model of your data - for a substantial number of projects there is liable to be a fairly direct relationship between model and schema (not in all cases, and probably not for all tables/objects) so really its a matter of building a decent model starting wherever you're comfortable and working from there.

In terms of building a decent model - @Tim has it for down for databases and fundamentally building your object model is going to be broadly similar - what's unique, what's a hierarchy, where are there many to many relationships, etc. then, however you get to a database, make sure that you do all the good stuff.

Also make sure that you have scripts or ddl in code to allow you to create the schema from scratch and to update as you make changes (ddl in code is my preferred method - I have a system and it works).

ContentLicense: CC BY-SA 2.5

Title: How do you approach database design?


答:
Recursion is not intrinsically better or worse than loops - each has advantages and disadvantages, and those even depend on the programming language (and implementation).

Technically, iterative loops fit typical computer systems better at the hardware level: at the machine code level, a loop is just a test and a conditional jump, whereas recursion (implemented naively) involves pushing a stack frame, jumping, returning, and popping back from the stack. OTOH, many cases of recursion (especially those that are trivially equivalent to iterative loops) can be written so that the stack push / pop can be avoided; this is possible when the recursive function call is the last thing that happens in the function body before returning, and it's commonly known as a tail call optimization (or tail recursion optimization). A properly tail-call-optimized recursive function is mostly equivalent to an iterative loop at the machine code level.

Another consideration is that iterative loops require destructive state updates, which makes them incompatible with pure (side-effect free) language semantics. This is the reason why pure languages like Haskell do not have loop constructs at all, and many other functional-programming languages either lack them completely or avoid them as much as possible.

The reason why these questions appear so much in interviews, though, is because in order to answer them, you need a thorough understanding of many vital programming concepts - variables, function calls, scope, and of course loops and recursion -, and you have to bring the mental flexibility to the table that allows you to approach a problem from two radically different angles, and move between different manifestations of the same concept.

Experience and research suggest that there is a line between people who have the ability to understand variables, pointers, and recursion, and those who don't. Almost everything else in programming, including frameworks, APIs, programming languages and their edge cases, can be acquired through studying and experience, but if you are unable to develop an intuition for these three core concepts, you are unfit to be a programmer. Translating a simple iterative loop into a recursive version is about the quickest possible way of filtering out the non-programmers - even a rather inexperienced programmer can usually do it in 15 minutes, and it's a very language-agnostic problem, so the candidate can pick a language of their choice instead of stumbling over idiosyncracies.

If you get a question like this in an interview, that's a good sign: it means the prospective employer is looking for people who can program, not people who have memorized a programming tool's manual.

Title: Recursion or while loops


答:
It really depends on convenience or the requirement:

If you take the programming language Python, it supports recursion, but by default there is a limit for the recursion depth (1000). If it exceeds the limit, we will get an error or exception. That limit can be changed, but if we do that we may experience abnormal situations in the language.

At this time (number of calls more than recursion depth), we need to prefer loop constructs. I mean, if the stack size is not enough, we have to prefer the loop constructs.

Title: Recursion or while loops


问:
What will be the better way to access information from another object
I have a page Object,
which has Paragraph and Image object Collections

And each paragraph has only image_id(s) that are assigned to a paragraph. All other information about image is stored in Page->Image

Now from the paragraph object I want to access the image information where paragraph has only image_id and all other information about the image is in Page->Image object.

What will be the better way to access this info?

Should I pass the page object in every paragraph constructor or something else?

I also can't change the class structure, as it is written by someone else.

答:
The paragraph object need to have some mechanism to know where it's image data comes from.

Assuming that a paragraph can't exist in isolation but only as part of a page, there's no harm in adding the owning page as a constructor parameter for each paragraph in order to supply this.


问:
Is use of finally clause for doing work after return bad style/dangerous?
As part of writing an Iterator, I found myself writing the following piece of code (stripping error handling)

```<code>public T next() {
  try {
    return next;
  } finally {
    next = fetcher.fetchNext(next);
  }
}
</code>```

finding it slightly easier to read than

```<code>public T next() {
  T tmp = next;
  next = fetcher.fetchNext(next);
  return tmp;
}
</code>```

I know it's a simple example, where the difference in readability may not be that overwhelming, but I'm interested in the general opinion as to whether it is bad to use try-finally in cases like this where there are no exceptions involved, or if it is actually preferred when it simplifies the code.

If it's bad: why? Style, performance, pitfalls, ...?

Conclusion
Thanks you all your answers! I guess the conclusion (at least for me) is that the first example might have been more readable if it was a common pattern, but that it isn't. Therefore the confusion introduced by using a construct outside of it's purpose, along with possibly obfuscated exception flow, will outweigh any simplifications.

答:
I would be really carefull, because (in general, not in your example) part in try can throw exception, and if it is thrown out, nothing will be returned and if you actualy inteded to execute what is in finally after return, it will execute when you did not want it to.

And other can of worm is, that in general, some usefull action in finally can throw exceptions, so you can end with really messy method.

Because of these, someone reading it must think about these problems, so it is harder to understand.


答:
Two things here:

yes I think most people just googled fizz buzz and then stumble when they try to expand it

Check out : http://dave.fayr.am/posts/2012-10-4-finding-fizzbuzz.html
It explains nice how you can solve fizz buzz using appropriate abstractions.

Title: Effectiveness of FizzBuzz and Beyond