问:
Is it reasonable to insist on reproducing every defect before diagnosing and fixing it?
I work for a software product company. We have large enterprise customers who implement our product and we provide support to them. For example, if there is a defect, we provide patches, etc. In other words, It is a fairly typical setup.

Recently, a ticket was issued and assigned to me regarding an exception found by a customer in a log file that has to do with concurrent database access in a clustered implementation of our product. So this customer's specific configuration may well be critical in the occurrence of this bug. All we got from the customer was their log file.

The approach I proposed to my team was to attempt to reproduce the bug in a configuration setup similar to that of the customer and get a comparable log. However, they disagree with my approach saying that I don't need to reproduce the bug as it's overly time-consuming and will require simulating a server cluster on VMs. My team suggests I simply "follow the code" to see where the thread- and/or transaction-unsafe code is and put in the change working off of a simple local development, which is not a cluster implementation like the environment from which the occurrence of the bug originates.

To me, working out of an abstract blueprint (program code) rather than a tangible, visible manifestation (runtime reproduction) seems difficult, so I wanted to ask a general question:

Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

Or:

If I am a senior developer, should I be able to read multithreaded code and create a mental picture of what it does in all use case scenarios rather than require to run the application, test different use case scenarios hands-on, and step through the code line by line? Or am I a poor developer for demanding that kind of work environment?

Is debugging for sissies?

In my opinion, any fix submitted in response to an incident ticket should be tested in an environment simulated to be as close to the original environment as possible. How else can you know that it will really remedy the issue? It is like releasing a new model of a vehicle without crash testing it with a dummy to demonstrate that the air bags indeed work.

Last but not least, if you agree with me:

How should I talk with my team to convince them that my approach is reasonable, conservative and more bulletproof?

答:
How do they intend to verify that the bug in question was fixed?  Do they want to ship untested code to the user and let them figure it out?  Any test setup that was never shown to reproduce the error can't be relied upon to show absence of the error.  You certainly don't need to reproduce the entire client environment, but you do need enough to reproduce the error.

I don't think it is unreasonable to attempt to reproduce every bug before fixing.  However if you attempt to reproduce it and you can't then it becomes more of a business decision on whether or not blind patches are a good idea.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
That assigning a priority other than "1" means the task will never be done.

I had a manager ask me to customize the bug-tracking tool with priorities 1a, 1b, 1c, 1d, and 1e so he could assign everything as some variation of priority 1, but we could still organize the work.

And yes, I did get through all the "priority 1" issues.  But before I could proceed to the issues that were still in priority 2-5, the manager made me re-assign the priorities of those issues into the five priority 1 levels.

(I realize this myth isn't specific to programming, but that's true of several other answers on this thread.)

ContentLicense: CC BY-SA 2.5


问:
How to read thousands lines of code without any documentation?
Previously I was searching for a good TimeLine control for a WPF project. I found an answer in Here which direct me to this CodePlex project.

Now I want to change code to feed my culture needs. But there are some mismatches!

My question is:

How you interact with such thousands lines of code?

EDIT:

Any shortcut will be great!

答: Step through it in the debugger as it runs, its nearly the only way to understand a new, large code base.</p>

ContentLicense: CC BY-SA 3.0


答:
I don't think you should make a reproducing the error a requirement to look at the bug. There are, as you've mentioned, several ways to debug the issue - and you should use all of them. You should count yourself lucky that they were able to give you a log file! If you or someone at your company is able to reproduce the bug, great! If not, you should still attempt to parse the logs and find the circumstances under which the error occurred. It may be possible, as your colleagues suggested, to read the code, figure out what conditions the bug could happen, then attempt to recreate the scenario yourself.

However, don't release the actual fix untested. Any change you make should go through the standard dev, QA testing, and integration testing routine. It may prove difficult to test - you mentioned multithreaded code, which is notoriously hard to debug. This is where I agree with your approach to create a test configuration or environment. If you have found a problem in the code, you should find it much simpler to create the environment, reproduce the issue, and test the fix.

To me, this is less a debugging issue and more of a customer service issue. You've received a bug report from a customer; you have a responsibility to do due diligence to find their issue and fix it.

Title: Is it reasonable to insist on reproducing every defect before diagnosing and fixing it?

Body:
I work for a software product company. We have large enterprise customers who implement our product and we provide support to them. For example, if there is a defect, we provide patches, etc. In other words, It is a fairly typical setup.

Recently, a ticket was issued and assigned to me regarding an exception found by a customer in a log file that has to do with concurrent database access in a clustered implementation of our product. So this customer's specific configuration may well be critical in the occurrence of this bug. All we got from the customer was their log file.

The approach I proposed to my team was to attempt to reproduce the bug in a configuration setup similar to that of the customer and get a comparable log. However, they disagree with my approach saying that I don't need to reproduce the bug as it's overly time-consuming and will require simulating a server cluster on VMs. My team suggests I simply "follow the code" to see where the thread- and/or transaction-unsafe code is and put in the change working off of a simple local development, which is not a cluster implementation like the environment from which the occurrence of the bug originates.

To me, working out of an abstract blueprint (program code) rather than a tangible, visible manifestation (runtime reproduction) seems difficult, so I wanted to ask a general question:

Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

Or:

If I am a senior developer, should I be able to read multithreaded code and create a mental picture of what it does in all use case scenarios rather than require to run the application, test different use case scenarios hands-on, and step through the code line by line? Or am I a poor developer for demanding that kind of work environment?

Is debugging for sissies?

In my opinion, any fix submitted in response to an incident ticket should be tested in an environment simulated to be as close to the original environment as possible. How else can you know that it will really remedy the issue? It is like releasing a new model of a vehicle without crash testing it with a dummy to demonstrate that the air bags indeed work.

Last but not least, if you agree with me:

How should I talk with my team to convince them that my approach is reasonable, conservative and more bulletproof?


答:
Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

You should give it your best effort. I know that sometimes there are conditions and environments that are so complex they can't be reproduced exactly, but you should certainly try if you can.

If you never reproduced the bug and saw it for yourself, how can you be 100% certain that you really fixed it? Maybe your proposed fix introduces some other subtle bug that won't manifest unless you actually try to reproduce the original defect.

If I am a senior developer, should I be able to read (multithreaded) code and create a mental picture of what it does in all use case scenarios rather than require to run the application, test different use case scenarios hands on, and step through the code line by line? Or am I a poor developer for demanding that kind of work environment? Is debugging for sissies?

I would not trust someone who runs the code "in their head", if that's their only approach. It's a good place to start. Reproducing the bug, and fixing it and then demonstrating that the solution prevents the bug from reoccurring - that is where it should end.

How should I talk with my team to convince them that my approach is reasonable, conservative and more bulletproof?

Because if they never reproduced the bug, they can't know for certain that it is fixed. And if the customer comes back and complains that the bug is still there, that is not a Good Thing. After all, they are paying you big $$$ (I assume) to deal with this problem.

If you fail to fix the problem properly, you've broken faith with the customer (to some degree) and if there are competitors in your market, they may not remain your customer.


答:
Unless the error is evident, obvious and trivial, with a very specific error message, etc., it's often very difficult to fix a bug if the user or the maintainer is not able to replicate it.

Also, how would you prove to them that the bug is fixed if you cannot replicate the steps?

The problem with your case is that the user doesn't know either how the error ocurred, that is, in what screen of doing what operation. They just simply have the log.

I think your point is reasonable. If you had psychic powers, you possibly wouldn't be working for a salary.

I think you should tell your bosses that without being able to replicate the error it would take an uknown amount of time to find it out, and there's no garantee at all that you will.

The problem will be when some co-worker of yours finds the bug out of pure luck and fixes it.


答:
In my opinion ... as the decision maker, you must be able to justify your position. If the goal of the 3rd line support department is to fix bugs in the shortest time frame with the acceptable effort from the client, then any approach must comply with that goal. Furthermore, if the approach can be proven to give the fastest expected results, then there should be no problem convincing the team.

Having worked in support, I have always reasonably expected the client to be able to give some "script" of actions they performed to consistently reproduce the bug and if not consistently then candidate examples which have produced the bug.

If I were new to the system and had no background with the code, my first steps would be to attempt to identify the possible sources of the error. It may be that the logging is insufficient to identify a candidate code. Depending on the client, I might be inclined to give them a debug version in order that they might be able to give you back log files which give further clues as to the position of the offending code.

If I am able to quickly identify the code block then visual mapping of the flow may be enough to spot the code. If not, then unit test based simulation may be enough. It may be that setting up a client replicating environment takes less time, especially if there is a great deal of replicability of the problem.

I think you may find that your approach should be a combination of the proposed solutions and that knowing when to quit one and move on to the next is key to getting the job done efficiently.

I am quite sure that the team will support the notion that if there is a chance their solution will find the bug quicker, then giving them a suitable time frame to prove that will not impact too much on the time it takes to fix the bug whichever route you take.


答:
Very good question!  My opinion is that if you can't reproduce the problem then you can't 100% for sure say that the fix you made will not:

a) actually fix the issue.
b) create another bug

There are times when a bug occurs and I fix it and I don't bother to test it.  I know 100% for sure that it works.  But until our QA department says that it's working then I consider it still a possibility that there is still a bug present... or a new bug created from the fix.

If you can't reproduce the bug and then install the new version and confirm that it is fixed then you can't, with 100% certainty, say that the bug is gone.

I tried for a few minutes to think of an analogy to help you explain to others but nothing really came to mind.  A vasectomy is a funny example but it's not the same situation :-)


答:
Ideally, you want to be able to reproduce each bug so that, at the very least, you can test that it's been fixed.

But... That may not always be feasible or even physically possible. Especially with 'enterprise' type software where each installation is unique. There's also the cost/benefit evaluation. A couple of hours of looking over code and making a few educated guesses about a non-critical problem may cost far less than having a technical support team spend weeks trying to set up and duplicate a customer's environment exactly in hopes of being able to duplicate the problem. Back when I worked in 'Enterprise' world, we would often just fly coders out and have them fix bugs on site, because there was no way to to duplicate the customer's setup.

So, duplicate when you can, but if you can't, then harness your knowledge of the system, and try to identify the culprit in code.


答: You add comments to the source code when you have understood it enough to be able to do so.  Refactor these comments vigorously as you understand more and more.</p>

Title: How to read thousands lines of code without any documentation?

Body:
Previously I was searching for a good TimeLine control for a WPF project. I found an answer in Here which direct me to this CodePlex project.

Now I want to change code to feed my culture needs. But there are some mismatches!

My question is:

How you interact with such thousands lines of code?

EDIT:

Any shortcut will be great!


问:
Maximum nesting for loops and conditionals?
I've written some code that has some fairly deep nests (one time, I wrote something that was a conditional check inside a forloop inside a conditional check inside a forloop inside a forloop).

Is there a general guideline on limits to the number of nested for loops/conditionals you have?

答: I personally try to avoid more than four or five levels deep in a single function. More than that would be a bad "code smell". I would suggest try to avoid that by adjusting the structure of the program or re-formulating your problem.</p>


答:
The C language allows for up to 127 levels of nested blocks; like 640KB of RAM, that's all anyone should ever need.

In practice, if you find yourself nesting more than 4 or 5 levels deep, think about factoring some of those inner levels out to their own functions (or re-think your algorithm).  If nothing else, the code will be easier to scan.

Title: Maximum nesting for loops and conditionals?

Body:
I've written some code that has some fairly deep nests (one time, I wrote something that was a conditional check inside a forloop inside a conditional check inside a forloop inside a forloop).

Is there a general guideline on limits to the number of nested for loops/conditionals you have?


答:
As with most questions about coding standards, the answer is: Whatever makes your code more readable.

I would argue that's usually fairly close to zero embedded layers of logic. But sometimes it isn't, and sticking vehemently to rules against common sense is more damaging than keeping to the simple policy of reading your own code, or getting someone else to.

Anything that makes it more readable, do it.


答:
You are touching upon one of the classic code metrics - cyclomatic complexity.  It doesn't measure nested levels, but rather loops and conditionals (which typically enclose nested levels).

PMD (a Java static analysis tool) has complexity as one of its measures and has this to say about it:

Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.

See also Experiments correlating code metrics to bug density from P.SE which goes deeper into the actual measures.


答:
Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

I say yes, with some caveats.

I think it's okay to read through the code and try to find places that look like they may be problematic. Create a patch and send that to the client to see if that resolves the problem. If this approach continues to fail, then you may need to investigate other options. Just remember that while you might be addressing a bug it might not be the bug that was reported.

If you can't reproduce it within reason, and you can't find any red flags in the code, then it may require some closer coordination with the customer. I've flown out to customer sites before to do on site debugging. It's not the best dev environment, but sometimes if the problem is environmental, then finding the exact cause is going to be easiest when you can reproduce it consistently.

I've been on the customer side of the table in this scenario. I was working at a US government office that used an incredibly large Oracle database cluster (several terabytes of data and processing millions of records a day).

We ran into a strange problem that was very easy for us to reproduce. We reported the bug to Oracle, and went back and forth with them for weeks, sending them logs. They said they weren't able to reproduce the problem, but sent us a few patches that the hoped might address the problem. None of them did.

They eventually flew out a couple of developers to our location to debug the issue on site. And that was when the root cause of the bug was found and a later patch correctly addressed the problem.


答:
If you're not positive about the problem, you can't be positive about the solution. Knowing how to reproduce the problem reliably in at least one test case situation allows you to prove that you know how to cause the error, and therefore also allows you to prove on the flip side that the problem has been solved, due to the subsequent lack of error in the same test case after applying the fix.

That said, race conditions, concurrency issues and other "non-deterministic" bugs are among the hardest for a developer to pin down in this manner, because they occur infrequently, on a system with higher load and more complexity than any one developer's copy of the program, and they disappear when the task is re-run on the same system at a later time.

More often than not, what originally looks like a random bug ends up having a deterministic cause that results in the bug being deterministically reproducible once you know how. The ones that defy this, the true Heisenbugs (seemingly random bugs that disappear when attempting to test for them in a sterile, monitored environment), are 99.9% timing-related, and once you understand that, your way forward becomes more clear; scan for things that could fail if something else were to get a word in edgewise during the code's execution, and when you find such a vulnerability, attempt to exploit it in a test to see if it exhibits the behavior you're trying to reproduce.

A significant amount of in-depth code inspection is typically called for in these situations; you have to look at the code, abandoning any preconceived notions of how the code is supposed to behave, and imagine scenarios in which it could fail in the way your client has observed. For each scenario, try to develop a test that could be run efficiently within your current automated testing environment (that is, without needing a new VM stack just for this one test), that would prove or disprove that the code behaves as you expected (which, depending on what you expected, would prove or disprove that this code is a possible cause of the clients' problems). This is the scientific method for software engineers; observe, hypothesize, test, reflect, repeat.


答: Take single action, debug (again and again) the code to find how that action is accomplished. Write down the same in simple language to get a better understanding!</p>


答:
[bug related to] concurrent database access, clustered implementation, multithreaded

Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

I'd not spend too much time trying to reproduce it.  That looks like a  synchronization problem and those are more often found by reasoning (starting from logs like the one you have to pinpoint the subsystem in which the issue occurs) than by being able to find a way to reproduce it and attacking it with a debugger.  In my experience, reducing the optimization level of the code or sometimes and even activating additional instrumentation can be enough to add enough delay or the lacking synchronization primitive to prevent the bug to manifest itself.

Yes, if you don't have a way to reproduce the bug, you won't be able to be sure that you fix it.  But if your customer doesn't give you the way to reproduce it, you may also be looking for something similar with the same consequence but a different root cause.


问:
Why use in-memory database for integration testing?
I'm really confused when I see a lot of in-memory database implementation used for testing, because I also heard a lot from integration testing best practices that the environment running the test should resemble as closely as possible the production environment, including operating system, library, database engine, etc.

What am I missing here?

答:
This depends much on the database system you are using. When your db system provides you with an in-memory alternative which is almost 100% API and behaviour compatible to a disk-based database configuration (except for speed and beeing failsafe, or course), then using the in-memory variant is obviously fine.

If, however, your DB system has significant differences between in-memory configuration  and non-in-memory usage, you are right: in this case integration tests have a higher risk of shadowing a bug. But even then, you may be able to "abstract that differences away" by yourself, given you know your DB system well and the differences.


问:
How to pass parameters to a function in C
Suppose I'm writing a program in C in which several parameters are asked at the beginning of the execution to the user and then remain costant until the end. Now, I need to pass these parameters to some function.

Since they are unchanged through the program, my temptation would be to declare them as global variables, to have them visible to all functions. However, I see that this is not a good practice if the dimension of the program gets big (this has been asked and answered here).

However, I neither see the point of creating functions with, say, 6 arguments, when the variable ones are only 2. Is there a more elegant way to do this without compromising too much the manipulability of the code?

答:
If you are asking for several parameters at the beginning, and these parameters never change, and need to be passed together, use a struct:

```<code>struct options {
    bool isDebug;
    int numberOfDigits;
    char userName[40];
};
</code>```

Then you don't have six arguments, where only two are variable, but rather just three:

```<code>doItNow(int speed, float precision, struct options* opts);
</code>```

(Even if you decided to use globals, it would still be better to bundle them together like that.)

One big advantage to passing these options into the function is that it makes it clear to the caller that they are required by the function.

Body:
If you are asking for several parameters at the beginning, and these parameters never change, and need to be passed together, use a struct:

struct options {
    bool isDebug;
    int numberOfDigits;
    char userName[40];
};

Then you don't have six arguments, where only two are variable, but rather just three:

doItNow(int speed, float precision, struct options* opts);

(Even if you decided to use globals, it would still be better to bundle them together like that.)

One big advantage to passing these options into the function is that it makes it clear to the caller that they are required by the function.


问:
Google App Engine -- should we use it?
I'm considering using Google App Engine for an online matchmaking (and possibly ranking, not sure) of users in a (currently hypothetical) RTS game. However, I just read this bad review, which has made me nervous. Which problems have they solved (or are planning to solve), which might be an issue for me, and are there any alternatives?</p>

答:
I love Google App Engine and its wonderful API *.

Before starting to develop a serious business on GAE, study its documentation and hidden limitations and then decide if your requirements would fit in a platform that, for scaling purpose, imposes several constraints.

My biggest concerns about Google App Engine are:

Lack of developer support

Downtimes and reliability issues

The *Premium service** seems to resolve both of them with:

Premium developer support available.

99.9% uptime service level agreement

*
I have developed StackPrinter on GAE

Title: Google App Engine -- should we use it?


答:
In a typical software development situation, tests are used at two points: during development, and before moving the product along the development chain.

The first situation, running tests during development, serves short-term goals: defining tasks (as in TDD: write a failing test, then make it pass), preventing regressions, making sure your changes don't break anything else, etc. Such tests need to be extremely fast: ideally, your whole test suite runs in less than 5 seconds, and you can just run it in a loop next to your IDE or text editor while you code. Any regression you introduce will pop up within seconds. Speedy test runs are more important in this phase than catching 100% of regressions and bugs, and since it is impractical (or outright impossible) to develop on exact copies of the production systems, the effort required to achieve perfect testing here isn't worth it. Using in-memory databases is a trade-off: they are not exact copies of the production system, but they do help keep test runs below the 5-second limit; if the choice is between a slightly different database setup for my database-related testing, and no testing at all, I know what I pick.

The second situation, moving the code along the development chain, however, does require extensive testing. Since we can (and should) automate this part of the development process, we can afford much slower tests - even if a full test run takes hours, scheduling a nightly build still means we always have an accurate picture of yesterday's codebase. Simulating the production environment as accurately as possible is important now, but we can afford it. So we don't make the in-memory-database tradeoff: we install the exact same version of the exact same DBMS as the production systems, and if possible, we fill it with actual production data before the testing begins.

Title: Why use in-memory database for integration testing?

Body:
I'm really confused when I see a lot of in-memory database implementation used for testing, because I also heard a lot from integration testing best practices that the environment running the test should resemble as closely as possible the production environment, including operating system, library, database engine, etc.

What am I missing here?


答:
I strongly recommend you to read "Clean Code" by Robert Martin, an extract of which says about nested structures:

Blocks and Indenting

...the blocks within if statements, else statements, while
  statements, and so on should be one line long. Probably that line
  should be a function call. Not only does this keep the enclosing
  function small, but it also adds documentary value because the
  function called within the block can have a nicely descriptive name.

This also implies that functions should not be large enough to hold
  nested structures. Therefore, the indent level of a function
  should not be greater than one or two. This, of course, makes the
  functions easier to read and understand.

So Bob Martin's recommendation is that the dept of nested structured should be two at most.

I agree with that and, although I don't always comply with it, at least I try.

Also, according with static analisys tool PDM's default configuration, the cyclomatic complexity of a function should not exceed 11, which is easily reached if you go beyond a dept of two.


问:
How much logic can be put into an object-pooling factory class before it does more harm than good?
The main language I'm interested in doing object pooling in is AS3, which is known to need it in many cases.  In the past I've always made a brand new factory class for every type I was going to try to pool, the parameters of its "object-producing" function being the same as those of that type's constructor.  Essentially:

```<code>static public function produce(<list of paramaters>):<type>
{
    if (m_arryPool.length)
    {
        var obj:<type> = m_arryPool.pop();
        // do something with the arguments passed to produce()
        return obj;
    }
    return new obj(<arguments passed to produce()>);
}
</code>```

But recently I've been trying to think of a way to avoid re-writing this sort of boiler-plate code for every single type I want to pool, but probably without forfeiting the idea of passing arguments around to the returned objects as in the above example, and definitely without putting so much dynamic functionality and stuff in there that it just winds up slowing stuff down too much.

I'm still a little green at object-pooling.  I know a one-size-fits-all pooling factory will probably not work out in all cases (AS3's Function.apply(), for instance, doesn't support constructors), but when does it get to the point that you're just passing in so many arguments to the produce() function, using so many untyped variables, going through so many dictionaries and lists, etc., that it just isn't hardly worth it anymore?

I know this question may be slightly subjective, but I do believe there are largely objective answers to it.  I'm mainly interested in how this would apply to AS3, but I'm also interested in (and asking for) a general answer.  Is the best way to handle it generally just to go ahead and write boilerplate code for every type you plan to pool or something like that?  Thanks!

答:
You will need some type of initialization method to get the arguments to the instance. It might be good to put that in a namespace.

Using some untyped voodoo is not good as untyped code is a lot slower - we're talking orders of magnitude in some cases (if you do that there's simply not point in having a pool in the first place). There's simply a lot of overhead involved in it. However a typed method invocation or field access can get performances near to C++ method calls (still factor 2-3 is to be expected).

So just have an initialization method and the you can have a plain constructor.

Reasons to leave the constructor blank:

Constructors are not JITed on the AVM2. Whatever you do in there is going to be slower.

If you have blank constructors, it is cheap to pre-allocate instances in batches. For one, it helps preventing memory fragmentation. But also this is something you can do while your app has low CPU load. Say at the beginning, say when you're loading assets, you can use the free time to preallocate some stuff. And when you need the instances, they are already there, which can result in a smoother experience overall.

And as a side note: Do not push and pop - for some reasons they are very slow, even on arrays.

The best is to maintain an index for an ample fixed size Vector. It takes 4 bytes per entry (due to FlashPlayer's 32 bit references). So 50000 slots will take up 200KB memory which is really not much compared to how much memory sounds or textures take when uncompressed to memory. Still, if you know less is fine, then go with less. That's something you will have to profile.

This is what it would look like:

```<code>var max:int = 50000;
var pool:Vector.<Type> = new Vector.<Type>(max, true);
var count:int = 0;
public function free(obj:Type):void {
    if (count < max - 1)
        pool[count++] = obj;
}
public function alloc():Type {
    return (count > 0) ? pool[--count] else new Type();
}
</code>```

Lastly, avoid static or global methods. They are also orders of magnitude slower.

The pool would be an instance (good use for a singleton) and whoever is responsible for getting objects from it or releasing them to it should be holding a reference to that object.

Body:
You will need some type of initialization method to get the arguments to the instance. It might be good to put that in a namespace.

Using some untyped voodoo is not good as untyped code is a lot slower - we're talking orders of magnitude in some cases (if you do that there's simply not point in having a pool in the first place). There's simply a lot of overhead involved in it. However a typed method invocation or field access can get performances near to C++ method calls (still factor 2-3 is to be expected).

So just have an initialization method and the you can have a plain constructor.

Reasons to leave the constructor blank:

Constructors are not JITed on the AVM2. Whatever you do in there is going to be slower.

If you have blank constructors, it is cheap to pre-allocate instances in batches. For one, it helps preventing memory fragmentation. But also this is something you can do while your app has low CPU load. Say at the beginning, say when you're loading assets, you can use the free time to preallocate some stuff. And when you need the instances, they are already there, which can result in a smoother experience overall.

And as a side note: Do not push and pop - for some reasons they are very slow, even on arrays.

The best is to maintain an index for an ample fixed size Vector. It takes 4 bytes per entry (due to FlashPlayer's 32 bit references). So 50000 slots will take up 200KB memory which is really not much compared to how much memory sounds or textures take when uncompressed to memory. Still, if you know less is fine, then go with less. That's something you will have to profile.

This is what it would look like:

var max:int = 50000;
var pool:Vector.<Type> = new Vector.<Type>(max, true);
var count:int = 0;
public function free(obj:Type):void {
    if (count < max - 1)
        pool[count++] = obj;
}
public function alloc():Type {
    return (count > 0) ? pool[--count] else new Type();
}

Lastly, avoid static or global methods. They are also orders of magnitude slower.

The pool would be an instance (good use for a singleton) and whoever is responsible for getting objects from it or releasing them to it should be holding a reference to that object.


问:
Hiring a Junior Developer, What should I ask?
We are currently hiring a junior developer to help me out, as I have more projects than I can currently manage. I have never hired anyone who wasn't a friend or at least an acquaintance. I have a phone interview with the only applicant that actually stood out to me (on paper), but I have never done this before.

Our projects are all high scalability, data intensive web applications that process millions of transactions an hour, across multiple servers and clients. To be language/stack specific, we use ASP.Net MVC2, WebForms and C# 4, MSSQL 2008 R2, all running atop Windows Server 2008 R2

What should I ask him? How should I structure the phone call?

答:
Sandglaz CEO Nada Aldahleh recently wrote a blog post about this, based on her own experience of hiring developers for her startup. Here are some of the things she looks for:

problem solving mind-set

strong communication skills

ask architecture and algorithm questions; a junior developer should be able to architect new small features and algorithm questions can be telling about problem-solving mindset and the kind of foundation they have

puzzles to isolate analytical skills

And, of course, the programming test, which should not consists though of the Fizz Buzz question. A real-life assignment that can be completed within a couple of hours at your office would be the best kind of test.

You can read more of her advice here:
http://blog.sandglaz.com/how-to-interview-and-hire-junior-developers/


答:
As with everything else in software development, the correct answer is a compromise.

In theory, you should never try to fix a bug if you cannot prove that it exists. Doing so may cause you to make unnecessary changes to your code that don't ultimately solve anything. And proving it means reproducing it first, then creating and applying a fix, then demonstrating that it no longer happens. Your gut here is steering you in the right direction -- if you want to be confident that you've resolved your customer's problem you need to know what caused it in the first place.

In practice, that is not always possible. Perhaps the bug only occurs on large clusters with dozens of users simultaneously accessing your code. Perhaps there is a specific combination of data operations on specific sets of data that triggers the bug and you have no idea what that is. Perhaps your customer ran the program interactively non-stop for 100's of hours before the bug manifested.

In any of those cases, there's a strong chance that your department is not going to have the time or money to reproduce the bug before you start work. In many cases, it's far more obvious to you, the developer, that there's a bug in the code that points you to the correct situation. Once you've diagnosed the problem, you may be able to go back and reproduce it. It's not ideal, but at the same time, part of your job as senior developer is to know how to read and interpret code, partly to locate these kind of buried bugs.

In my opinion, you are focusing on the wrong part of the question. What if you ultimately cannot reproduce the bug in question? Nothing is more frustrating to a customer than to hear "yeah, we know you crashed the program but we can't reproduce it, so it's not a bug." When your customer hears this, they interpret it as "we know our software is buggy but we can't bother to fix and fix the bugs so just cross your fingers." If it better to close a reported bug as "not reproducible", or to close it as "not reproducible, but we have made some reasonable changes to try to improve stability"?


问:
What are some arguments AGAINST using EntityFramework?
The application I am currently building has been using Stored procedures and hand-crafted class models to represent database objects. Some people have suggested using Entity Framework and I am considering switching to that since I am not that far into the project. My problem is, I feel the people arguing for EF are only telling me the good side of things, not the bad side :)

My main concerns are:

We want Client-Side validation using DataAnnotations, and it sounds like I have to create the client-side models anyways so I am not sure that EF would save that much coding time

We would like to keep the classes as small as possible when going over the network, and I have read that using EF often includes extra data that is not needed

We have a complex database layer which crosses multiple databases, and I am not sure EF can handle this. We have one Common database with things like Users, StatusCodes, Types, etc and multiple instances of our main databases for different instances of the application. SELECT queries can and will query across all instances of the databases, however users can only modify objects that are in the database they are currently working on. They can switch databases without reloading the application.

Object modes are very complex and there are often quite a few joins involved

Arguments for EF are:

Concurrency. I wouldn't have to code in checks to see if the record was updated before each save

Code Generation. EF can generate partial class models and POCOs for me, however I am not positive this would really save me that much time since I think we would still need to create the client-side models for validation and some custom parsing methods.

Speed of development since we wouldn't need to create the CRUD stored procedures for every database object

Our current architecture consists of a WPF Service which handles database calls via parameterized Stored Procedures, POCO objects that go to/from the WCF service and the WPF client, and the WPF desktop client itself which transforms POCOs into class Models for the purpose of Validation and DataBinding.

So my question is, is EF right for this? Are there any pitfalls about EF that I am unaware of?

答:
Simply ... the Domain Model is rarely a replica of the relational
model in your database. So mapping some tables to a class and
throwing it over the wire is just plain laziness. Tables might
locally map into 1 object even though the database is is 3 different
tables. Design the database intelligently.

2nd this EF stuff cannot    generate certain queries and you'll have
to write them anyway.

3rd    The Domain Model doesn't map directly    onto services .. One
will only    want to push the most minimal set    of data over the
wire as DTOs..    especially, if its going to be    communicating
with mobile apps.

5Th    test-ability ... Cannot create granular enough tests that will
provide enough regression against code changes ... all to easy to

break ...

I could write a 10 page diatribe. But, if you're just writing some throw away app for Company X .. who care then. But, if you're developing a software product ... you're going to have to be a lot more anal


答:
In layman's words:

The mocking of important parts of the architecture is OK (and a must) for unit testing.

But for integration testing, I strongly agree with you. Mocking shouldn't be done and an environment as similar as possible as the real one should be provided.

After all, integration tests are about testing how the different parts of the architecture behave together.


问:
Why use classes when programming a tkinter gui in python
I program primarily in python and have programmed a couple of GUI's with Tkinter, every tutorial I have ever seen has recommended defining and using a class for the GUI, but my GUI runs flawlessly using only procedures, without a class.

Why use a class? It seems from my perspective to simply be an extra layer of complexity and unnecessary code.

答:
Why use a class? Because it makes the job easier, assuming you know how to do object oriented programming, and assuming you're writing a non-trivial GUI. Using objects allows you to easily divide your code into modular units that are self contained, and modularizing your code is generally considered to be a best practice.

GUI programming readily lends itself to an object-oriented style, since a GUI is made up entirely of objects -- labels, buttons, scrollbars, text areas, etc. Since you're already using objects, organizing your code into larger objects makes sense. The toolbar is an object, the statusbar is an object, the navigation pane is an object, the main area is an object, each notebook tab is an object, and so on.

Even when your code isn't very complex, from a more practical standpoint it lets you define bindings and callbacks earlier in the file than the definition of the function you're calling, which I think makes a lot of sense.

For example, consider a simple example (assuming that tkinter has been imported like import tkinter as tk (python3) or import Tkinter as tk (python2):

```<code>def quit(event=None):
    sys.exit()
root = tk.Tk()
label = tk.Label(root, text="Hello, world")
label.pack()
label.bind("<1>", quit)
root.mainloop()
</code>```

To me, the flow of that code is all wrong. I have to define the quit method before I reference it, and the creation of the root window and the call to mainloop are separated by all of the other code.

By using classes, however, I can write the code in a more natural order:

```<code>class MyWindow(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Hello, world")
        label.pack()
        label.bind("<1>", self.quit)
    def quit(self, event=None):
        sys.exit()

root = tk.Tk()
MyWindow(root).pack()
root.mainloop()
</code>```

The main body of the GUI is right at the top of the file, and supporting code is below it. Now, of course, you can use functions to achieve much of the same thing. In my opinion, though, classes make it all just a little easier.

Another advantage is that I can now easily change the containing window without having to change anything about the "main" window (and visa versa). That is, I can add borders, or a complete new section to the main GUI, but I don't have to touch a single line of code inside of MyWindow. Contrast that with the procedural code where you might have to change the label.pack() statement, and the pack (or grid) statements of all of the other widgets in the UI.

All that being said, however, using an object oriented approach isn't necessary to write good, clean, maintainable code. It can be, but it can also lead to poor code. At the end of the day, an object-oriented approach is just a tool. Whether you use it or not, and whether you use it correctly or not depends on a lot of factors. So it may very well be that for you, and for the code you write, a functional style is perfectly acceptable. I do think you'll find that as your programs get more complex, an object-oriented approach will make it easier to organize and maintain your code.

Body:
Why use a class? Because it makes the job easier, assuming you know how to do object oriented programming, and assuming you're writing a non-trivial GUI. Using objects allows you to easily divide your code into modular units that are self contained, and modularizing your code is generally considered to be a best practice.

GUI programming readily lends itself to an object-oriented style, since a GUI is made up entirely of objects -- labels, buttons, scrollbars, text areas, etc. Since you're already using objects, organizing your code into larger objects makes sense. The toolbar is an object, the statusbar is an object, the navigation pane is an object, the main area is an object, each notebook tab is an object, and so on.

Even when your code isn't very complex, from a more practical standpoint it lets you define bindings and callbacks earlier in the file than the definition of the function you're calling, which I think makes a lot of sense.

For example, consider a simple example (assuming that tkinter has been imported like import tkinter as tk (python3) or import Tkinter as tk (python2):

def quit(event=None):
    sys.exit()
root = tk.Tk()
label = tk.Label(root, text="Hello, world")
label.pack()
label.bind("<1>", quit)
root.mainloop()

To me, the flow of that code is all wrong. I have to define the quit method before I reference it, and the creation of the root window and the call to mainloop are separated by all of the other code.

By using classes, however, I can write the code in a more natural order:

class MyWindow(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Hello, world")
        label.pack()
        label.bind("<1>", self.quit)
    def quit(self, event=None):
        sys.exit()

root = tk.Tk()
MyWindow(root).pack()
root.mainloop()

The main body of the GUI is right at the top of the file, and supporting code is below it. Now, of course, you can use functions to achieve much of the same thing. In my opinion, though, classes make it all just a little easier.

Another advantage is that I can now easily change the containing window without having to change anything about the "main" window (and visa versa). That is, I can add borders, or a complete new section to the main GUI, but I don't have to touch a single line of code inside of MyWindow. Contrast that with the procedural code where you might have to change the label.pack() statement, and the pack (or grid) statements of all of the other widgets in the UI.

All that being said, however, using an object oriented approach isn't necessary to write good, clean, maintainable code. It can be, but it can also lead to poor code. At the end of the day, an object-oriented approach is just a tool. Whether you use it or not, and whether you use it correctly or not depends on a lot of factors. So it may very well be that for you, and for the code you write, a functional style is perfectly acceptable. I do think you'll find that as your programs get more complex, an object-oriented approach will make it easier to organize and maintain your code.


问:
If I try to monetize free software, what could possibly prevent someone from forking that software and creating a proprietary version?
I've only recently begun to learn about the tensions between free and proprietary software, and I've been very confused by the way that free software can make money.

I understand that free software is "free as in speech, not as in beer," but if I release an open source program and then try to monetize it, what could possibly prevent someone from forking that software and creating a proprietary version?

Is the only thing that stops them the investment of other members of the open source community in improving the software?

It seems like every improvement free software makes is transparent so a proprietary copycat can make sure they are always up to date with the latest features in the free version, and then add their own features on top of that independently. I'm confused about how free software can survive in serious competition with proprietary software.

答:
There are two answers here, because there are two principal ways to look at this.

First, sometimes free software thrives in competition with proprietary software because it wasn't designed to make money in the first place.  That's not the only thing that motivates people, after all.

But if you're looking for a way to monetize free software, you're absolutely right in saying that anyone could fork it and use it to compete with you.  What you have to do, then, is what other successful services which run on open-sourced platforms have done: build value beyond the software itself.

Reddit is open source, for example.  If I wanted to, I could download it and host a Reddit instance of my own.  But you know as well as I do that that wouldn't do me much good, because I'd still be missing the thing that truly makes Reddit valuable: the large community of users.

The key to making money off of something with little to no inherent monetary value--such as software that anyone can obtain for free--is by providing a related service that does have a high value, such as connecting people together and making it easier for them to communicate with each other.


问:
Using BSD and GPL in one project
I am an author of project, that consists of two parts: daemon and library.
I want to license library under BSD License (or MIT, will decide later), and daemon under GPLv3.

I want to permit the library to be linked into closed-source products, but I want daemon to be GPL, as it uses GPL code heavily, and I do not want its commercial forks.

The thing is: This library just provides client interface for the daemon, where daemon acts just like sort of server.

Is it permitted to license my project using separate licenses for different parts of my project, linked with some sort of RPC protocol?

答:
AFAIK this sort of use case has never been checked in court but I think GNU would most certainly say that that you are indeed deriving your MIT/BSD library from a GPL product and applying common sense, it is what you are doing. In result, your MIT/BSD code gets "tainted" by GPL as well as any product utilizing your MIT/BSD code. Of course your library code can still be MIT/BSD code but anything using it will fall under derivative work.

Naturally as GPL has been written to be imprecise in the first place, no precise answer can be given.

What I say can be backed up by this article http://www.law.washington.edu/lta/swp/law/derivative.html

I would say that you are only safe if you are indeed not deriving anything from the GPL stuff - in the intuitive sense and any sort of technical circumvention is only fooling oneself. Court might not be fooled.

Title: Using BSD and GPL in one project


答:
The GNU General Public License was created explicitly to prevent proprietary forks - it allows you to distribute derived works (forks or add-ons) only if you agree to put them under the same license.

The GPL grants the recipients of a computer program the rights of the Free Software Definition and uses copyleft to ensure the freedoms are preserved whenever the work is distributed, even when the work is changed or added to. The GPL is a copyleft license, which means that derived works can only be distributed under the same license terms. This is in distinction to permissive free software licenses, of which the BSD licenses are the standard examples...

Title: If I try to monetize free software, what could possibly prevent someone from forking that software and creating a proprietary version?

Body:
I've only recently begun to learn about the tensions between free and proprietary software, and I've been very confused by the way that free software can make money.

I understand that free software is "free as in speech, not as in beer," but if I release an open source program and then try to monetize it, what could possibly prevent someone from forking that software and creating a proprietary version?

Is the only thing that stops them the investment of other members of the open source community in improving the software?

It seems like every improvement free software makes is transparent so a proprietary copycat can make sure they are always up to date with the latest features in the free version, and then add their own features on top of that independently. I'm confused about how free software can survive in serious competition with proprietary software.


答:
Nothing prevents anybody from forking your software and becoming a competitor.

If you use a copyleft-type license, their fork cannot ever become non-free software (if that's what you mean by proprietary). Things are different with permissive open source license, like BSD-style licenses.

If there are other Free alternatives, the only way to monetize on your software is to provide added value: service, community, reputation, etc.

It can be done, and successfully. But be prepared to invest more effort in service and communication than pure software development.


答:
One downside to nested loops not mentioned yet: If each loop iterates over a large dataset, your algorithm will have high complexity classes. For example,

```<code>foreach(foo in foos) {
  foreach(bar in bars) {
    foreach(baz in bazzes) {
      foreach(buzz in buzzes) {
        do_a_thing(foo, bar, baz, buzz);
      }
    }
  }
}
</code>```

Will run in roughly O(n^4) time if foos, bars, bazzes and buzzes are all about the same size.

This isn't an issue if the collections are always going to be small. Then, everyone else's advice applies. If your collections have a decent chance of being 1000's of items large or larger, though, it would be worth looking for a faster algorithm if possible.

Body:
One downside to nested loops not mentioned yet: If each loop iterates over a large dataset, your algorithm will have high complexity classes. For example,

foreach(foo in foos) {
  foreach(bar in bars) {
    foreach(baz in bazzes) {
      foreach(buzz in buzzes) {
        do_a_thing(foo, bar, baz, buzz);
      }
    }
  }
}

Will run in roughly O(n^4) time if foos, bars, bazzes and buzzes are all about the same size.

This isn't an issue if the collections are always going to be small. Then, everyone else's advice applies. If your collections have a decent chance of being 1000's of items large or larger, though, it would be worth looking for a faster algorithm if possible.


答:
Is it reasonable to insist on reproducing every defect and debug it before
  diagnosing and fixing it?

No, it very definitely isn't. That would be a stupid policy.

The problem I see with your question and your proposal is that they fail to make a distinction between

bug reports

failures (errors)

bugs (also sometimes called errors)

A bug report is communication about a bug. It tells you somebody thinks something is wrong. It may or may not be specific about what is supposed to be wrong.

A bug report is evidence of a failure.

A failure is an incident of something going wrong. A specific malfunction, but not necessarily with any clues as to what may have caused it.

A failure may be caused by a bug.

A bug is a cause of failures; something that can (in principle) be changed in order to prevent the failures it causes from occurring in the future.

Sometimes, when a bug is reported, the cause is immediately clear. In such a case, reproducing the bug would be nonsensical. At other times, the cause isn't clear at all: the bug report doesn't describe any particular failure, or it does but the failure is such that it doesn't provide a clue as to what might be the cause. In such cases, I feel your advice is justified - but not always: one doesn't insist on crashing a second $370 million space rocket before accepting to investigate what caused the first one to crash (a particular bug in the control software).

And there are also all sorts of cases in between; for instance, if a bug report does not prove, but only suggests, that a potential problem you were already aware of might play a role, this might be enough incentive for you to take a closer look at it.

So while insisting on reproducibility is wise for the tougher cases, it is unwise to enforce it as a strict policy.


答:
@Steven Burnap has outlined my preferred option. However, it often happens in large programs that one small function way down the call tree needs the information and it makes the code less readable and harder to maintain if you pass the data down the stack as parameters.

An alternate in C is make the data static within a module and provide one or more getter and setter function(s). The setter function should only be called at program initialization and this can easily be checked, and all references to the data can be quickly found by looking for calls to the getter. This is a common pattern for things like command line parameters and VSPs (Variable System Paramaters - data such as configuration items that does not change during program execution)

Debugging becomes easier as you can place trace outputs in the routines.

Title: How to pass parameters to a function in C

Body:
Suppose I'm writing a program in C in which several parameters are asked at the beginning of the execution to the user and then remain costant until the end. Now, I need to pass these parameters to some function.

Since they are unchanged through the program, my temptation would be to declare them as global variables, to have them visible to all functions. However, I see that this is not a good practice if the dimension of the program gets big (this has been asked and answered here).

However, I neither see the point of creating functions with, say, 6 arguments, when the variable ones are only 2. Is there a more elegant way to do this without compromising too much the manipulability of the code?


问:
Is it legal to distribute EXEs inside system32 folder with my product
I'm developing a product related to printing. To work it properly in all windows versions I need to include few exe (lpr.exe) files from system32 folder. So I need to know it is legal to distribute these exe file with my product. </p>

答:
The answer is pretty much no.

Those files are Microsoft's, and they have prohibited redistribution.


问:
Assigning Blame for Bugs versus Giving Rewards for Fixes
In a team that I used to work for, there was a policy that if you introduced a memory or other resource leak, you got a 'dummy of shame' hung on your door until you found the next resource leak.

While it was effective at finding resource leaks, I felt like it placed more emphasis on blaming others rather than working together to solve problems as a team.

Am I being unreasonable in thinking that this policy contributed to a lower sense of team cohesion?  Am I also being unreasonable in thinking that we should have rewarded those people who found and fixed the issue?

答:
I do not think you are being unreasonable in thinking that.

As the idiom goes You can catch more flies with honey than with vinegar

We are not perfect, people make mistakes from time to time and rather than focus on blaming someone then publicly shaming them, It would be in the team's best interest to have the bug fixed as fast as possible rather than ship failing code.

To mitigate the loss of sense of code ownership that might be brought by doing this pro-team move, you can place restrictions that the owner of the code where the bug originated from still has to fix it on his/her own UNLESS its a bug that is beyond the programmer's capability to fix.

As for reasons why bug bounties or incentives, check out MichaelIT's comment.


答: Ignoring the legality, its a profoundly bad idea to install a version of a Windows system exe on other installations running different versions of Windows (both major and minor).  You should look to see if MS has some sort of redistributable package for that program that you can include in your installer to enable the functionality you are looking for, or re-evaluate your current approach to whatever it is you are doing..

Title: Is it legal to distribute EXEs inside system32 folder with my product

Body: I'm developing a product related to printing. To work it properly in all windows versions I need to include few exe (lpr.exe) files from system32 folder. So I need to know it is legal to distribute these exe file with my product. </p>


答:
It is important to differentiate between 'bugs' and 'code quality'.

Bugs are unavoidable when developing software, so attaching a negative stigma to bugs is, in effect, attaching a negative stigma to creating any new code.  It is typically better to manage the overall code development process.  A more efficient process could cause those bugs to be caught at an earlier stage of development, and could enable a better response time to remaining bugs that are discovered later.

To start, examine the development process and identify areas of confusion, which could include:

Business requirements "X should be able to perform Y"

Technical breakdown of the business requirements (services affected, ui needed, acceptance tests)

Coding standards, tests, style (to some degree)

Frequency of code commits

Ability to fix bugs before writing new features.

If there is a culture of fixing bugs before developing new features, would there need to be a 'policy' surrounding bug fixes?  If developing quality code becomes a natural process, if fixing bugs becomes a natural process, then the need to make policies and reward systems will be lessened.

Title: Assigning Blame for Bugs versus Giving Rewards for Fixes

Body:
In a team that I used to work for, there was a policy that if you introduced a memory or other resource leak, you got a 'dummy of shame' hung on your door until you found the next resource leak.

While it was effective at finding resource leaks, I felt like it placed more emphasis on blaming others rather than working together to solve problems as a team.

Am I being unreasonable in thinking that this policy contributed to a lower sense of team cohesion?  Am I also being unreasonable in thinking that we should have rewarded those people who found and fixed the issue?


问:
Reconciling contradictory programming advice: get something working and iterate vs. really think it through before coding
I am an intermediate programmer with a few years of professional experience who is halfway through a masters degree. In learning to program I've often heard two pieces of seemingly contradictory advice.

The first piece of advice was get something working quickly, see how it works (either through prototyping or informal testing), improve the version , see how it works again, improve it again...and then repeat the cycle until you're done. This is sometimes called "spiral development" or phrased as "release early, release often."

The second piece of advice was: really think a project through before ever writing any code.

I've had success with both methods and I would say that I agree with each philosophy.

But now I'm starting to tackle much more complex projects that I have no idea how to complete (like distributed applications and performance-driven graphics programming).

How do I go about these projects?

Do I just start coding SOMETHING and learn (platforms/methods/languages/architectures) as I go -- or do I hold off from coding and do a ton of research/reading before I even open the IDE?

How do I reconcile these contradictory pieces of programming advice?

答:
There are certain decisions that need to be made ahead of time.

Are you making a web application?  Then you need to know what the overall architecture is going to look like.  Architectures like MVC already define what your large functional pieces are going to be (like routing, controllers, models, service layers, communication protocols and so forth); inventing all that from scratch is going to be a long haul, unnecessary, and probably inferior to that which is already invented.

Are you writing any kind of application that involves collections of objects or data?  Then you're going to need to know about which kinds of data structures are most appropriate for your particular scenario, and what their performance characteristics are.  Do you need fast lookup time?  How about ordered data sets?  Will an in-memory collection do, or do you need something more industrial-strength like a database?  You can't just begin coding without thinking these decisions through, because if you make the wrong choice, you'll have to start over.

That said, once the technological decisions are made, you have freedom within the framework you have established.  The goal then is to remain flexible, iterative and (dare I say) agile enough so that when the customer changes his mind about what they want, you can accommodate them with a minimum amount of fuss.

How do you do that?  Experience, mostly.  As someone once said, experience is what you get right after you need it.  But if you follow the successful design decisions of others (as embodied in the platforms, libraries and other tools of the trade), you can learn from them and reduce your risk.


答:
I don't view the two as mutually exclusive.

Like any sort of project management you need both a long term vision and short term goals.

Without the former you'll end up wasting time for example on features that may never even be used and without the latter you'll spend all day considering how to create the perfect application without finishing your project.

How often you release/etc. depends on the specific methodology you are using.

What you have to research depends on what you know versus what you are not comfortable with.

Title: Reconciling contradictory programming advice: get something working and iterate vs. really think it through before coding

Body:
I am an intermediate programmer with a few years of professional experience who is halfway through a masters degree. In learning to program I've often heard two pieces of seemingly contradictory advice.

The first piece of advice was get something working quickly, see how it works (either through prototyping or informal testing), improve the version , see how it works again, improve it again...and then repeat the cycle until you're done. This is sometimes called "spiral development" or phrased as "release early, release often."

The second piece of advice was: really think a project through before ever writing any code.

I've had success with both methods and I would say that I agree with each philosophy.

But now I'm starting to tackle much more complex projects that I have no idea how to complete (like distributed applications and performance-driven graphics programming).

How do I go about these projects?

Do I just start coding SOMETHING and learn (platforms/methods/languages/architectures) as I go -- or do I hold off from coding and do a ton of research/reading before I even open the IDE?

How do I reconcile these contradictory pieces of programming advice?


答:
I'm not sure that thinking about a problem ahead of time vs. iterative approach are contradictory to each other.  Just like many other things, I think you should strive to achieve the balance between the two.  How do you find the balance? That's something you learn with experience and often time best lessons (i.e. stuff that gives you experience) is when you don't get it quite right (or even better lesson: just flat out get it wrong).  As you already pointed out, there's a saying "release fast, release often".  There's another similar one, "fail early, fail fast, fail often"

Thinking ahead is great and you should absolutely do it. But with experience, learn when to stop thinking and to just build something even if you don't have all the data.  By building it, you'll be able to gain more insight into the problem domain and potentially come up with a much better solution.  So I'd recommend don't exclude one from the other but make "thinking head" part of your iterations and over time I think you'll find the right answer to this question yourself.

Just a little example.  The other day I was struggling with a software design decision.  In hindsight it was relatively trivial but I had two alternatives and it seemed like both of them would work.  I kept circling back to pros/cons of each one and then circling back and reconsidering my decisions.  Looking back, it's a bit embarrassing how much time I spent thinking.  Then I said to myself, f#@k it!  And instead of using either one of the designs, I just went ahead and hacked some code together, completely ignoring all good stuff you learn about good design.  I got the feature working in about 45 minutes.  Then I went back, looked at my code and refactored it into something solid and something I wouldn't feel ashamed about checking into source control.  The funny part is that after I got the hack working, to come up with "proper design" took about 15 minutes.

Another thing I'd recommend specifically for problems you are facing now (i.e. large, complex task looming ahead).  Instead of doing things in serial, do them in parallel.  Break up your day into chunks where you do research and then stop, switch gears and code for a while, at least on parts of the project which are not complete unknowns. This way staying close to the code will give you better perspective and you won't burn out by attempting to absorb too much information too fast.  For me at least, after few hours of research, it's good to let the brain digest stuff, switch tasks and do something else for a while. Then come back to more research.


问:
How to ask management to increase the number of programmers in the team without sounding incompetent
I am currently working for a small-medium sized company (~50 employees) as the sole IT staff.

Recently, we are on track to replace one expensive yet critical legacy system in favor of an application I am currently working on during my free time at work. However, its been very busy lately with issues spawning left and right so the development of the application has been lagging a lot.

How do I ask a very thrifty management to hire more programmers to help me build the new application without sounding incompetent.

FYI. I do support of all our applications, setup and administration of the network and servers and in-house application development.

EDIT 1: Nature of the Critical Legacy System for added information

The Legacy System is the center of our operations. Basically, all our reports, notifications and data are being handled or are passing through this system. We want to replace it for a few reasons:

We are bleeding money paying for support that is rarely helpful (really terrible support) plus licensing cost.

Ridiculous cost for adding new features (500$ to adjust the width of a column in a report)

System Design/Architecture problems that cause the system to be slow and unscalable (Other branches find the system unusable because of how slow it is when used outside of the Office LAN)

Its a program made with access '97. Need I say more? It still works but its like trying to cut something with a dull blade in terms of performance

答:
You have to make a value proposition.  Explain in terms that management will understand how much money it's going to cost them by not adding additional software developer(s), and how that cost is going to exceed the cost of the new developers.

Of course, it might actually be less expensive for them to just let you do it in your free time.  You haven't told us much about the nature of the legacy system, why it is critical, or why your company wants to replace it.

If they really can't afford to hire more staff and are willing to wait it out, ask them to carve out a specific amount of time each week (say, 8 hours) that is sacred time for you to work on the system, where nobody interrupts you while you are working on it.


问:
What process do typical (the majority) of high level language compilers use when changing a source-code's variable name to a machine code name?
Do long (very long) variable names slow down the compilation of source code?

I'm aware that the length of variables has 0% impact on interpretation as the compiler changes them to machine code which is always the same length. But my question is, does the speed at which the compiler vary depending on the length of variables?

For example, if I have a variable name which is a million characters long, surely the compiler would struggle as for it to recognise the variable is a variable, it would need to read the entire thing first which would surely take longer depending on its size?

To clarify, what process do typical (the majority) of high level language compilers use when changing a source-code's variable name to a machine code name?

Do they find the start of the variable working from the left and then find the end working from the right, do they read through the entire variable name (one character at a time) until the end is found or do they not even look at the variable name at all and just know that the code requires a variable of type int (for example) and assign it a machine-level name instantly and then completely ignore any user-defined variable names?

Note that I am a complete novice (still a student) so excuse my ignorance if I get my terms mixed up.

答:
The compiler have to build a symbol table to identify variables in your code. Here both foos refer to the same abstract concept:

```<code>foo = 1
bar = foo + 5
</code>```

So to identify both foo as a single identity, you have to process the full word. So a long variable will take longer to process. But it should not be a concern. Readability should be your main concern when naming a variable.

Body:
The compiler have to build a symbol table to identify variables in your code. Here both foos refer to the same abstract concept:

foo = 1
bar = foo + 5

So to identify both foo as a single identity, you have to process the full word. So a long variable will take longer to process. But it should not be a concern. Readability should be your main concern when naming a variable.


答:
Your dummy of shame will actually result in your bugs getting fixed slower. People just being people, they will have a secret backlog of bugs so when they get passed the dummy, they will "miraculously" find another developers resource leak before the day is over.

It's all about incentive, your policy does not promote finding leaks, it promotes finding 1 leak, and that's the leak you find right after you got passed the dummy.

Also the fact that it stays with you till the next leak is found means that the "punishment" has nothing to do with the severity of the bug. Someone can make a big resource leak, have the dummy for a day, find a tiny issue the next day, pass on the dummy and it may stay with the one who made the tiny issue for longer then the guy who made the big oops.


问:
Is it reasonable to insist on reproducing every defect before diagnosing and fixing it?
I work for a software product company. We have large enterprise customers who implement our product and we provide support to them. For example, if there is a defect, we provide patches, etc. In other words, It is a fairly typical setup.

Recently, a ticket was issued and assigned to me regarding an exception found by a customer in a log file that has to do with concurrent database access in a clustered implementation of our product. So this customer's specific configuration may well be critical in the occurrence of this bug. All we got from the customer was their log file.

The approach I proposed to my team was to attempt to reproduce the bug in a configuration setup similar to that of the customer and get a comparable log. However, they disagree with my approach saying that I don't need to reproduce the bug as it's overly time-consuming and will require simulating a server cluster on VMs. My team suggests I simply "follow the code" to see where the thread- and/or transaction-unsafe code is and put in the change working off of a simple local development, which is not a cluster implementation like the environment from which the occurrence of the bug originates.

To me, working out of an abstract blueprint (program code) rather than a tangible, visible manifestation (runtime reproduction) seems difficult, so I wanted to ask a general question:

Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

Or:

If I am a senior developer, should I be able to read multithreaded code and create a mental picture of what it does in all use case scenarios rather than require to run the application, test different use case scenarios hands-on, and step through the code line by line? Or am I a poor developer for demanding that kind of work environment?

Is debugging for sissies?

In my opinion, any fix submitted in response to an incident ticket should be tested in an environment simulated to be as close to the original environment as possible. How else can you know that it will really remedy the issue? It is like releasing a new model of a vehicle without crash testing it with a dummy to demonstrate that the air bags indeed work.

Last but not least, if you agree with me:

How should I talk with my team to convince them that my approach is reasonable, conservative and more bulletproof?

答:
Reading the question, I don't see any fundamental opposition between your position and your team's.

Yes, you should give your best effort to reproduce the problem occurring in the client setting. But best effort mean that you should define some time box for that, and there may not be enough data in the log to actually reproduce the problem.

If so, all depends on the relationship with this customer. It can go from you won't have anything else from him, to your may send a developper on site with diagnosis tools and ability to run them on the failing system. Usually, we are somewhere in between and if initial data is not enough there are ways to get some more.

Yes, a senior developper should be able to read the code and is likely to find the reason of the problem following the log content. Really, it is often possible to write some unit test that exhibit the problem after carefully reading the code.

Suceeding writing such unit tests is nearly as good as reproducing the breaking functional environment. Of course, this method is not a guarantee either that you will find anything. Understanding the exact sequence of events leading to failure in some multi-threaded software can be really hard to find by just reading the code, and ability to debug live is likely to become critical.

Summarily, I would try for both approaches simultaneously and ask for either a live system exhibiting the problem (and showing that it is fixed afterward) or for some breaking unit test breaking on the problem (and also showing it is fixed after the fix).

Trying to just fix the code and send it in the wild, does indeed look very risky. In some similar cases that occured to me (where we failed to reproduce the defect internally), I made clear that if a fix went in the wild and failed to resolve the customer problem, or had any other unexpected negative consequences, the guy that proposed it would have to help the support team to find the actual problem. Including dealing with the customer if necessary.


问:
Should a developer close a ticket in bug tracking tool?
Should a developer close a ticket in a bug tracking tool? Or should only the scrum master or testers should do it?

What are the best practices?

答:
It fully depends on the policy applied in your team.

And this policy may evolve with the progress of the project.

In an agile team, this can be discussed at the start of each sprint.


答:
At the company I work at only a pm can close a ticket.
The developer can set it to resolved though.

They to this so that every fix gets a check from the pm.

But it depends on the company.

Title: Should a developer close a ticket in bug tracking tool?

Body:
Should a developer close a ticket in a bug tracking tool? Or should only the scrum master or testers should do it?

What are the best practices?


答:
Like everyone else has mentioned, it depends on the company or house rules of the team

but according Joel's post: Painless Bug Tracking

Bugs should be closed by the issuer of the bug to make sure that the bug is indeed fixed.
So in your case, should a developer close the ticket? Yes, if the developer is the one who raised the bug ticket.


问:
MVC Architecture -- How many Controllers do I need?
I have been coding for a while, but mostly scripts and simple applications. I've moved into a new role where it is all about developing Web Apps and using a proper MVC architecture, so I am desperately trying to learn about all that very quickly.

I hope this question is not too similar to "Best Practices for MVC Architecture" but as I am going through a few different tutorials, I noticed that some have multiple controllers for different things.

How many controllers does a single web app need?

I realize this would be difficult to answer without an example so I'll provide one:

Application:

User logs in.

User can do one of three things:

a)  Upload a file (stored in a mongodb database with meta data).

b)  Search for a file.

c)  Log out.

My question is a general one, but I gave the example to help out anyone trying to answer.

答:
One example that I like is thinking of a thermostat. A thermostat is a great visual for viewing the MVC pattern.

On an older, analogue thermostat you can picture things like this:

View - The temperature reader, which displays the current temperature.

Controller - The dial, where you change the temperature

Model - The parts inside that are invoked by the controller that cause the temperature to change.

You should always abide by designs that allow loose coupling and limit models and their associated controllers to a single task, and you should use as many modules/controllers as you need. Depending on the size of your application, you may have far less views than you do models and controllers. This is to be expected with any large size application. Good Object-Oriented Programming is characterized by loose coupling, encapsulation, inheritance, and polymorphism. Not all languages support polymorphism to the same degree (function, method, operator overloading / overriding).

If you want to have a better understanding of employing the MVC architecture properly, consult the GoF "Design Patterns: Elements of Reusable ... Software" which uses C++ and SmallTalk for example code. This book is not the alpha and omega, but it's certainly a start!

Good luck!


答:
The open source business model is not  much about selling lots of copies to many individual customers. This model would not be sustainable, because each of your customers could compete with you and underbid you. But there are other business models which allow you to make money from open source software:

Support and consulting fees: Your software may be free, but who is the best person in the world to help people use it? The people who made it, of course. Being one or the main developer of an open source software makes you most qualified for this job, and allows you to charge a lot for an hour of your time.

Collaboration for strategic reasons: Some companies support the development of open source software because they are using it themself and want the best software possible. Or they are creating other products which benefit indirectly from a certain open source project. Take a look at the top twenty contributors of the Linux kernel, for example. You see some Linux distributors in there, but also companies like IBM or Intel who sell hardware running Linux or companies like Oracle who sell software running on Linux.

Customized software: While the one-size-fits-all model works well in consumer-software, many companies have very specific requirements for the software they are using. Taking an open source software and modifying it to fulfill these exotic requirements is a viable business. The company could resell the modified software, but there wouldn't be anyone to sell it to, because their requirements are too unique. You need a web shop which can interface with your industrial welding robots? I don't know one which can, but I could hack Magento to do it.

Multilicensing: Many corporations (like Oracle, for example) offer the same software under both an open-source share-alike license and a proprietary license. In some cases the proprietary version has additional features the free version lacks (this might look like a glorified demo version, but there can be good reasons to do so, for example when the proprietary version uses 3rd party technology which is not open source). In other cases, both versions are functionally identical, but the proprietary license comes with an agreement to create derivate versions which are also proprietary allowing the buyer to sell his derivate to multiple customers.


问:
Overcoming slow problem solving due to increased knowledge of what might go wrong
This has been troubling me for some time, and I'd really appreciate the input of other professionals.

Short background: I started programming when my parents bought me my first computer in 1988 (at age 14, I'm 39 now). I followed a couple of other career paths before finally becoming a professional programmer in 1997. Late bloomer, perhaps, but that's how it was. I'm still happy with my choice, I love programming, and I consider myself good at what I do.

Lately, I've been noticing that the more experience I gain, the longer it takes me to complete projects, or certain tasks in a project. I'm not going senile yet. It's just that I've seen so many different ways in which things can go wrong. And the potential pitfalls and gotchas that I know about and remember are just getting more and more.

Trivial example: it used to be just "okay, write a file here". Now I'm worrying about permissions, locking, concurrency, atomic operations, indirection/frameworks, different file systems, number of files in a directory, predictable temp file names, the quality of randomness in my PRNG, power shortages in the middle of any operation, an understandable API for what I'm doing, proper documentation, etc etc etc.

In short, the problems have long since moved from "how do I do this" to "what's the best/safest way of doing it".

The upshot is that it takes me longer to finish a project than a novice. My version may be rock solid, and as impenetrable as I know how to make it, but it takes longer.

The "create file" example above was just that, an example. Real tasks are obviously more complex, but less suited for a generic question like this one. I hope you understand where I'm going with this. I have no problem coming up with efficient algorithms, I love math, I enjoy complex subjects, I have no difficulties with concentration. I think I do have a problem with experience, and consequently with a fear of errors (intrinsic or extrinsic).

I spend almost two hours a day reading up on new developments, new techniques, languages, platforms, security vulnerabilities, and so on. The conundrum is that the more knowledge I gain, the slower I am in completing projects.

How do you deal with this?

答:
Don't be too hard on yourself.  You are working in a profession of increasing complexity, that requires more human intelligence, knowledge and experience than ever before.

Computer processing power is slowing - perhaps soon stalling - leading to the need to introduce multi-core chips, gpu powered numerics, parallelism, etc.  There are only so many transistors that can be placed on a chip.

Therefore the big advances presently and in the future are going to come from programmers - advanced algorithms and more efficient code.

If you look at GTA 4 and GTA 5 the differences are astounding.  But they both run on the same hardware.  This is the result of some very intelligent and advanced programming practice that simply was not required, or available, 10 years ago.

It could also mean that experienced programmers may become more valuable in the future - much like other professions such as engineering where peak earnings typically occur late in the career.


答:
Apart from the premises of the question, how same question (about the unreasonable thinking) applies to a classroom teaching:

Imagine two teachers who both frequently makes class participate by asking questions like "Does anyone know the answer?"

When students in classroom raise hands they might know or not know the answer, or hit the point anywhere between. Lets focus on the "not so right answers" that are picked.

Teacher One would approach it with the "dummy of shame" approach. If the answer is not correct, or very close to correct... The student is ridiculed with "How poor answer, shame on you."

Teacher Two would approach it with encouragement. When the answer is not correct, everyone are encouraged with "Good answer, it explains X and Y about the question but there is more." (then continuing to explain it, not asking anyone to "correct" the first answer because it would create competitive environment.)

Now think which one of these teachers have more hands raised when asking question like this. Teacher Two creates an environment where everyone can participate without fear of not fully understanding it.

This can be applied to original question. In team programming everyone are participating, which should be encouraged. When memory leak bug is found, like another reply stated, making bug creator fix it by offering support creates learning experience and lead to less such mistakes made in the future by this programmer.
It is also more likely that everyone are more willing to participate and work as a team, not working as "pack of competing predators".


答:
Depends on the processes within your team.

I would close a bug off only if I executed acceptance test and verified that the bug has indeed been fixed. Even then, depending on the severity of the bug I would probably run it past the quality assurance lead.

I normally don't get SCRUM masters involved with bug fixing/testing as it's not their job.


问:
How do the blogging sites or sites that host prose like contents store the data?
How do the blogging sites, Q&A sites (or any other sites host prose like content) store their data? That is, how do you store blogs and Q&A content in the database? </p>

<p>I hope it is not good to store this huge text data inside RDBMS table columns.   </p>

答:
Depends on the size and functionality of the web site. As a first step they will in fact store this information in a relational database in many cases. Though you won't use a normal index on large text fields. But it is still a very good model to keep all the relations (which answer goes to which question, which question or answer was posted by which user).

For the large text parts you will need full text search. Here you have two options. Some RDBMS have the ability to create such a type of index. Otherwise (or if you want very specific full text search abilities that your DB doesn't offer) you will copy this part of your data into some full text search engine like Solr, ElasticSearch, Sphinx (or any other, there are lots of them).

There are alternative options with NoSQL databases too of course and some may decide to use those for some advantages those may offer for their project.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Software is like sex: it's better when it's free.

— Linus Torvalds

LastEditorDisplayName: Roger Pate


答:
It's perfectly good to store huge text data inside RDBMS table columns. Provided appropriate type (CLOB, TEXT or BLOB, depending on specific database) is used. Many RDBMS even have an extension for creating full text index.

In contrast images are usually stored in filesystem, because then they can be served statically by the web server which can than often use the sendfile(2) optimization. Since the text has to be embedded into the HTML output, no similar optimization is possible for it. The text is also not really huge.

Title: How do the blogging sites or sites that host prose like contents store the data?

Body:
How do the blogging sites, Q&A sites (or any other sites host prose like content) store their data? That is, how do you store blogs and Q&A content in the database? </p>

<p>I hope it is not good to store this huge text data inside RDBMS table columns.   </p>


答:
Developing your library and daemon as one project, but releasing them under different licenses is probably fine, but I would advise against it. Unless you have a very clear project structure that separates the sources of both parts, you are likely to run into a situation where it becomes unclear which part a particular source file belongs to.
And even if you do have a clear separation, the situation is less clear for common files. It is possible that it can be argued that those files are dual-licensed, which might make the GPL apply effectively also to your library. You should consult a lawyer to get that cleared up.

A better alternative is to split the library and daemon into two separate projects (both maintained by you), where the daemon project depends on the library.

It is certainly possible to use BSD-licensed libraries in a GPL-licensed product. Most BSD-style licenses are compatible with the GPL license, which means that you can legally distribute a product that uses both GPL and BSD-licensed parts. If parts are GPL, the entire product must comply with the restrictions set out in the GPL, but that does not affect (separately obtained) copies of the (BSD) library.

Title: Using BSD and GPL in one project

Body:
I am an author of project, that consists of two parts: daemon and library.
I want to license library under BSD License (or MIT, will decide later), and daemon under GPLv3.

I want to permit the library to be linked into closed-source products, but I want daemon to be GPL, as it uses GPL code heavily, and I do not want its commercial forks.

The thing is: This library just provides client interface for the daemon, where daemon acts just like sort of server.

Is it permitted to license my project using separate licenses for different parts of my project, linked with some sort of RPC protocol?


答:
Large texts stored in RDBMS aren't unusual, in fact, most Q&A and blogging sites make use of RDBMS for storing their content, normally as TEXT or CBLOBs or BLOBs

i.e.

StackOverflow uses SQL Server 2008, which an RDBMS (info may be out of date since article dates back to 2008)

Wordpress requires MySQL to work

Given that these examples use RDMBS, and still manage to work well, should be a testament that RDBMS are more than capable of storing large walls of text for blogs and Q&A sites. Though depending on your use case, you may refer Thorsten's answer for unstructured databases like NoSQL