答:
Development on virtual machines can work quite nicely, but only if done right:

Just because using VMs allows you to have a single computer for your entire team rather than one per developer doesn't mean that it is a good idea

Rebooting should not require opening a support ticket with a 24 hour response time

Development VMs should not be in a datacenter 5000 miles away from the developers.

While VMs may be managed by developers and therefore unsupported, that does not mean that they should be unable to access network services such as source control.

The remote desktop connection should be standard, not some custom "high security" applet that converts any quotes typed into umlauts.

Getting a new VM or rebuilding an existing one should take minutes, not weeks

I have seen all of these issues, and don't particularly enjoy working with them. However I also have a VM setup at home which I use by choice. That runs faster than a local install would and allows things like separate environments for different projects and fast rebuilds when an environment becomes unstable.

Title: Thoughts on Development using Virtual Machines

Body:
I'll be working as a development lead for a startup and I've suggested that we use VMs for development.  I'm not talking about each developer having a desktop with VMs for testing/development, I mean having a server rack where all VMs are managed and have the developers work from a microPC (ChromeOS anyone?) locally, or even remotely from their home computer.

To me, the benefits are the fact that it's extremely scalable, cheaper in the long run, easier to manage and that we utilize the hardware its maximum potential.  As for cons, I can't think of any particular showstoppers other than we'll need someone to setup/maintain said setup.

I was hoping that some of you might of had a similar setup at your place of employment and be able to weight in with your opinions.  Thanks.


问:
Thoughts on Development using Virtual Machines
I'll be working as a development lead for a startup and I've suggested that we use VMs for development.  I'm not talking about each developer having a desktop with VMs for testing/development, I mean having a server rack where all VMs are managed and have the developers work from a microPC (ChromeOS anyone?) locally, or even remotely from their home computer.

To me, the benefits are the fact that it's extremely scalable, cheaper in the long run, easier to manage and that we utilize the hardware its maximum potential.  As for cons, I can't think of any particular showstoppers other than we'll need someone to setup/maintain said setup.

I was hoping that some of you might of had a similar setup at your place of employment and be able to weight in with your opinions.  Thanks.

答:
That was one of my ideas in the past: having a high performance server which has all the required software, and a bunch of low performance desktop PCs which would be used only to connect to the server through Remote Desktop.

The benefits would be:

The solid backup. Some developers may not want to backup their desktop computers regularly, so a central solution would be more reliable,

The possibility, for every developer, to work from anywhere. By this I also mean working from any PC in the company. Let's say in the morning, the developer wants silent work conditions. He goes to his own room and works there. Then he wants to do some pair programming or to work in a more social environment. He just shuts down his desktop PC, goes to another room where there are ten computers, and connects from there. No "I must reload all my apps again".

Well, there are several serious problems with that, making me think that I will never use the thing like this the next years.

Specificity of remote solutions. What about working distantly using several computer screens at once? I mean, is it easy? Is it obvious? Are shortcuts I use daily enabled when working distantly? I'm not so sure. What if I press Ctrl+Shift+Esc to see the list of programs currently running? Oh yes, it doesn't work, so now I must remember doing it in a different way.

Performance hit. I'm not sure there will be no performance decrease at all. And remember, a programmer who uses a slow computer is an unhappy programmer. And the company who makes their programmers unhappy with crappy conditions will never produce high quality software.

Higher impact of a disaster. Will you host the solution on a redundant server? Do you have redundant network in your company? Let's say the router goes down, and is not redundant. It means that all the developers are now unable to work. At all. Because they don't have software installed locally. Because they don't even have source code: it's on the server. So everyone stops, and you're paying all those people per hour just to wait the router to be replaced.

Hardware costs. If it's one and one only server, how much will it cost? If you have, let's say, twenty developers, would 64 GB of RAM on the server be enough? Not so sure. Would quad-core solution with two CPU be enough? Again, I have some doubts. Otherwise, what do you think about? Some sort of cloud? Or do you have a scalable solution which works on several servers? Are you ready to pay the cost of Windows Server (if you use Windows) per machine?

Electricity cost. If you work completely remotely, it means that you spend nearly the same amount of power server-side as if you were working locally, plus the amount of power wasted by the local machine and the network.

Licenses. I'm not sure if I must put it as a benefit or a problem, but I feel like the cost of software licensing in this case will be much higher.

And again, think about all the costs of management, support, deployment, maintenance. With a custom solution like this, it may easily become huge, not counting that every time something will fail, you'll see every developer NOPing around, waiting to be able to continue his work.

ContentLicense: CC BY-SA 3.0


答:
I think you're being penny-wise and pound-foolish.

First of all, machine costs are trivial compared to the cost of a developer.  You should work at maximizing productivity, not minimizing machine cost.

Second, latency (not bandwidth) is the key to many programming tasks -- especially text editing. For every dollar/pound/euro you save on machines for your developers, you'll spend at least ten on network upgrades to maintain even a semblance of productivity -- and even then, they'd probably be more productive if you economized by supplying them with Pentium III's you found in a dumpster somewhere.

I also think there's a substantial benefit in having your developers use an environment at least reasonably close to that expected of the target end user. Regardless of official performance targets in a spec and such, most programmers base quite a bit on how the code "feels" when they test it. When they're using a completely different environment from the end user's, they're likely to waste time on trivialities while completely overlooking major problems.

As attractive as a homogeneous environment sounds from a viewpoint of support and such, you should generally encourage as much variety in the developers' machines as possible. Developers rarely need much support anyway, and knowing immediately when you have code that's going to fail with a different graphics chip, CPU, network adapter, etc., more than repays the minimal investment.

Bottom line: if you're writing code that's intended (at least primarily) to be used in a virtualized server environment, you just about need to provide that for your developers. If you're doing it anyway for testing, it can (but doesn't necessarily) make sense for development as well. Likewise, if you need (or at least have) a severely over-speced server and network anyway, it might make sense to take advantage of that by using what you already have available.

Under most typical circumstances, however, it seems to me that this is likely to introduce more problems than it solves.


问:
How do I avoid "Developer's Bad Optimization Intuition"?
I saw on a article that put forth this statement:

Developers love to optimize code and with good reason. It is so
  satisfying and fun. But knowing when to optimize is far more
  important. Unfortunately, developers generally have horrible intuition
  about where the performance problems in an application will actually
  be.

How can a developer avoid this bad intuition? Are there good tools to find which parts of your code really need optimization (for Java)? Do you know of some articles, tips, or good reads on this subject?

答:
As anyone here is talking about profilers I will focus on this part of the question.

How can a developer avoid this bad intuition?

You. do. not. Instead you never optimize early on.

Repeat it again and again and again, as it's a religious mantra.

You will find yourself doing that and will discover you should have not.

And then again.

And again.

Early Optimization is one of programmers' capital sins.

Tools and stuff are part of the later optimization which is an established craft.

ContentLicense: CC BY-SA 4.0


问:
How do I handle refactoring that takes longer than one sprint?
I work with a code base that is over 500K lines of code. It is in serious need of refactoring. There have been refactoring efforts identified that will take longer than the normal two week sprint. These can't be broken up into smaller tasks as I have seen suggested in other answers on this site. The product needs to work at the end of the iteration, and partial refactoring will leave the system in an unusable state as the dependency between items is horrible. So what would be the best way to approach this hurdle? Again I mention, breaking it down into smaller pieces is is not an option, that has already been done.

Update:
People seem to need an explanation of why this can't be fit into a 2 week sprint. There is more involved in a sprint than just writing code. We have a policy of no code without tests. That policy did not always exist and a large portion of the codebase does not have them. Also some of our integration tests are still manual tests. The issue is not that the refactoring itself is so large. It is with the fact that small changes have an effect on many parts of the system, and we need to ensure that those parts still operate correctly.

We can't put off or extend a sprint because we have monthly hotfixes. So this change extending past a sprint cannot stop the other work being added to the hotfix.

Refactoring vs Redesign:
Just because our development process is not efficent enough to handle this refactoring in a two week cycle does not warrant renaming it to a redesign. I would like to believe that in the future we could accomplish the exact same task within a two week cycle as our process improves. The code in question here has not had to change in a very long time, and is quite stable. Now, as the direction of the company is becoming more adaptable to change, we want this portion of the code base to be as adaptable as the rest. Which requires refactoring it. Based on the answers here, it is becoming apparent that there is missing scaffolding necessary to make this refactoring work in the time frame of normal sprints.

Answer:

I am going to do the branch and merge approach that Corbin March suggested the first time so we can learn more about these problem areas and how to identify the missing tests. I think moving forward, we should take the approach that Buhb suggested of identifying the areas that are missing tests and implement those first, then do the refactoring. It will allow us to keep to our normal two week sprint cycle, just like many here have been saying should always be the case for refactoring.

答:
Although the redesign you really want to do is a large task, would it be possible to refactor smaller pieces to break/decouple individual dependencies?  You know--when in doubt, add indirection.  Each of these decouplings should be a smaller task than the mammoth one you cannot complete.  </p>

<p>Once the dependencies are removed, you should be able to break up the remaining refactoring tasks to be obtainable within sprints.  </p>

Body:
Although the redesign you really want to do is a large task, would it be possible to refactor smaller pieces to break/decouple individual dependencies?  You know--when in doubt, add indirection.  Each of these decouplings should be a smaller task than the mammoth one you cannot complete.

Once the dependencies are removed, you should be able to break up the remaining refactoring tasks to be obtainable within sprints.


答:
We use on-demand amazon ec2 instances as developer machines. This has nothing to do with cost. We have a "pool of developers" working on several projects, and we need the ability to move across projects quickly.

In general, the VM saves initial setup time. But longer term, it wastes time due to loss of productivity. Cost is a non-axis, because developer cost is much more than machine cost.

Productivity costs include - time taken to start a VM image (several minutes), poor responsiveness, and resource/memory constraints. These are not much initially, but over time they get annoying.

On one of our projects we refactored the code to simplify initial setup to "download code and run maven". With this change, it was simple for a new developer to start working on the project -- and now nobody uses the amazon VM image. We are looking to emulate this on other projects as well, but its going to take time. Till then, we have our ec2 images.


问:
How should I handle invalid user input?
I have been thinking about this issue for a while and I would be curious to have opinions from other developers.

I tend to have a very defensive style of programming. My typical block or method looks like this:

```<code>T foo(par1, par2, par3, ...)
{
    // Check that all parameters are correct, return undefined (null)
    // or throw exception if this is not the case.

    // Compute and (possibly) return result.
}
</code>```

Also, during the computation, I check all pointers before dereferencing them. My idea is that, if there is some bug and some NULL pointer should appear somewhere, my program should handle this nicely and simply refuse to continue the computation. Of course it can notify of the problem with an error message in the log or some other mechanism.

To put it in a more abstract way, my approach is

```<code>if all input is OK --> compute result
else               --> do not compute result, notify problem
</code>```

Other developers, among them some colleagues of mine, use another strategy. E.g., they do not check pointers. They assume that a piece of code should be given correct input and it should not be responsible for what happens if the input is wrong. Also, if a NULL pointer exception crashes the program, a bug will be found more easily during testing and have more chances of being fixed.

My answer to this is normally: but what if the bug is not found during testing and appears when the product is already being used by the customer? What is a preferred way for the bug to manifest itself? Should it be a program that does not perform a certain action, but can still continue to work, or a program that crashes and needs to be restarted?

Summarizing

Which of the two approaches to handling wrong input would you advise?

```<code>Inconsistent input --> no action + notification
</code>```

or

```<code>Inconsistent input --> undefined behaviour or crash
</code>```

Edit

Thanks for the answers and suggestions.
I am a fan of design by contract too. But even if I trust the person who has written the code calling my methods (maybe it is myself), there can still be bugs, leading to wrong input. So my approach is to never assume a method is passed correct input.

Also, I would use a mechanism to catch the problem and notify about it. On a development system, it would e.g. open a dialog to notify the user. In a production system it would just write some information to the log. I do not think that extra checks can lead to performance problems. I am not sure if assertions are enough, if they are switched off in a production system: maybe some situation will occur in production that had not occured during testing.

Anyway, I was really surprised that many people follow the opposite approach: they let the application crash "on-purpose" because they maintain that this will make it easier to find bugs during testing.

答:
Using "assertions" is the way to go to notify fellow developers that they are doing it wrong, in "private" methods only of course. Enabling/disabling them is just one flag to add/remove at compile time and as such it is easy to remove assertions from the production code. There are also a great tool to know if you are somehow doing it wrong in your own methods.

As for verifying input parameters within public/protected methods, I prefer to work defensively and check parameters and throw InvalidArgumentException or the like. That is why there are here for. It also depends on whether you are writing an API or not. If it's an API, and even more if it is closed source, better validate everything so that the developers know precisely what went wrong. Otherwise, if the source is available to other developers, it is not black/white. Just be consistent with your choices.

Edit: just to add that if you look for example at the Oracle JDK, you will see that they never check for "null" and let the code crash. Since it is going to throw a NullPointerException anyway, why bother checking for null and throwing an explicit exception. I guess it makes some sense.

Title: How should I handle invalid user input?


问:
How do you prevent the piracy of your software?
Is it still worth it to protect our software against piracy? Are there reasonably effective ways to prevent or at least make piracy difficult?</p>

答:
Give the software away for free as a 'lite' version. People who are serious about it can pay for the 'full' version and have their version somehow stamped to identify it. Don't stick their name in it - that's too easy to remove.

A better model is to manage payment from the server side. See my answer on pricing for more details.

ContentLicense: CC BY-SA 2.5


答:
I struggled with this same issue while going through a university class in programming.  I leaned towards the paranoid side and tend to check everything  but was told that this was misguided behavior.

We were being taught "Design by contract".  Emphasis is that the preconditions, invariants and post-conditions be specified in the comments and design documents.  As the person implementing my part of the code, I should have trust in the software architect and empower them by following the specifications which would include the preconditions (what inputs my methods have to be able to handle and what inputs I will not be sent).    Excessive checking in every method call results in bloat.

Assertions should be used during build iterations to verify program correctness (validation of preconditions, invariants, post conditions).  Assertions would then be turned of in the production compile.

Title: How should I handle invalid user input?

Body:
I have been thinking about this issue for a while and I would be curious to have opinions from other developers.

I tend to have a very defensive style of programming. My typical block or method looks like this:

```<code>T foo(par1, par2, par3, ...)
{
    // Check that all parameters are correct, return undefined (null)
    // or throw exception if this is not the case.

    // Compute and (possibly) return result.
}
</code>```

Also, during the computation, I check all pointers before dereferencing them. My idea is that, if there is some bug and some NULL pointer should appear somewhere, my program should handle this nicely and simply refuse to continue the computation. Of course it can notify of the problem with an error message in the log or some other mechanism.

To put it in a more abstract way, my approach is

```<code>if all input is OK --> compute result
else               --> do not compute result, notify problem
</code>```

Other developers, among them some colleagues of mine, use another strategy. E.g., they do not check pointers. They assume that a piece of code should be given correct input and it should not be responsible for what happens if the input is wrong. Also, if a NULL pointer exception crashes the program, a bug will be found more easily during testing and have more chances of being fixed.

My answer to this is normally: but what if the bug is not found during testing and appears when the product is already being used by the customer? What is a preferred way for the bug to manifest itself? Should it be a program that does not perform a certain action, but can still continue to work, or a program that crashes and needs to be restarted?

Summarizing

Which of the two approaches to handling wrong input would you advise?

```<code>Inconsistent input --> no action + notification
</code>```

or

```<code>Inconsistent input --> undefined behaviour or crash
</code>```

Edit

Thanks for the answers and suggestions.
I am a fan of design by contract too. But even if I trust the person who has written the code calling my methods (maybe it is myself), there can still be bugs, leading to wrong input. So my approach is to never assume a method is passed correct input.

Also, I would use a mechanism to catch the problem and notify about it. On a development system, it would e.g. open a dialog to notify the user. In a production system it would just write some information to the log. I do not think that extra checks can lead to performance problems. I am not sure if assertions are enough, if they are switched off in a production system: maybe some situation will occur in production that had not occured during testing.

Anyway, I was really surprised that many people follow the opposite approach: they let the application crash "on-purpose" because they maintain that this will make it easier to find bugs during testing.


问:
Do you sign each of your source files with your name?

Possible Duplicate:

  How do you keep track of the authors of code?

One of my colleagues is in the habit of putting his name and email address in the head of each source file he works on, as author metadata.  I am not; I prefer to rely on source control to tell me who I should be speaking to about a given set of functionality.

Should I also be signing files I work on for any other reasons?  Do you?  If so, why?

To be clear, this is in addition to whatever metadata for copyright and licensing information is included, and applies to both open sourced and proprietary code.

答:
Why would you want a comment with someone's name in it in your source code?

If offers no insight in to the intent of the code and unless you struggle to remember your own name has no value at all that I can see.

It would be removed at the next commit if I came across it.

Of course, comments are generally a smell in themselves but that's another topic:)


问:
What is an efficient way to retrieve product counts at multiple levels of a hierarchy?
I'm working on an e-business website to sell books and also want to display the number of available books in the category list.

The category list contains the genre and the format (pocket, ebook, audiobook etc). In each element in genre and format I would like to display the number of available products from the stock list. Of course, when you go deeper into the hierarchy, you retrieve more specific information of available books at that level.

For instance there are 2000 available books in the "medicine" genre and if I select the "pocket" format then there are 200 available books left. In other words, you have combined "pocket" and "medicine" and you know now that there are 200 available pocket books in total in the "medicine" genre.

My question is:

How do you create that functionality without making lots of effort to ask the database about the amount of available products in each element? Do you need to buy a special application or plugin? Please remember that there are millions of books in the database.

答:
You pre-calculate the data once in a while (24 hours f.e.) - and cache the result (this can range from a special optimized table to a file cache).

No-one will count the amount of books and notice there are only 1800 instead of 2200, it is for indication only and it doesn't have to accurate all the time.


答:
I work with VMs, but I do not recommend it for your main project.

The reason I use VMs for development is because I have to support legacy projects (e.g. VB6, .NET 1.1, etc...) and I don't want to dirty my main machine by having to install VS2003/2005/vb6/etc...  It works out OK, but there are intermittent issues here and there.

In addition, the interaction is slower, VMs take a while to start/shutdown, do not have native UI effects (like Aero in Win7), etc...

Whatever you are going to save in terms of money you'll waste and more by the hassle you are about to impose on your team.  Plus, as someone here mentioned, no multi-screen support.  I need at least 3 screens to be as productive as possible.


答:
There's no "correct" answer here, particularly without specifying the language, the type of code, and the type of product that the code might go into. Consider:

Language matters. In Objective-C, it's often okay to send messages to nil; nothing happens, but the program doesn't crash, either. Java doesn't have explicit pointers, so nil pointers aren't a big concern there. In C, you need to be a little more careful.

To be paranoid is to unreasonable, unwarranted suspicion or mistrust. That's probably not any better for software than it is for people.

Your level of concern should be commensurate with the level of risk in the code and the probable difficulty of identifying any problems that do show up. What happens in the worst case? The user restarts the program and continues where they left off? The company loses millions of dollars?

You can't always identify bad input. You can religiously compare your pointers to nil, but that only catches one out of 2^32 possible values, nearly all of which are bad.

There are a lot of different mechanisms for dealing with errors. Again, it depends to some degree on the language. You can use assert macros, conditional statements, unit tests, exception handling, careful design, and other techniques. None of them is foolproof, and none is appropriate for every situation.

So, it mostly boils down to where you want to put responsibility. If you're writing a library for use by others, you probably want to be as careful as you reasonably can about the inputs you get, and do your best to emit helpful errors when possible. In your own private functions and methods, you might use asserts to catch silly mistakes but otherwise put responsibility on the caller (that's you) to not pass garbage in.

Title: How should I handle invalid user input?


问:
How is dependency inversion related to higher-order functions?
Today I've just seen this article which described the relevance of SOLID principle in F# development-

F# and Design principles – SOLID

And while addressing the last one - "Dependency inversion principle", the author said:

From a functional point of view, these containers and injection concepts can be solved with a simple higher order function, or hole-in-the-middle type pattern which are built right into the language.

But he didn't explain it further. So, my question is, how is the dependency inversion related to higher order functions?

答:
Dependency Inversion in OOP means that you code against an interface which is then provided by an implementation in an object.

Languages that support higher language functions can often solve simple dependency inversion problems by passing behaviour as a function instead of an object which implements an interface in the OO-sense.

In such languages, the function's signature can become the interface and a function is passed in instead of a traditional object to provide the desired behaviour. The hole in the middle pattern is a good example for this.

It let's you achieve the same result with less code and more expressiveness, as you don't need to implement a whole class that conforms to an (OOP) interface to provide the desired behaviour for the caller. Instead, you can just pass a simple function definition. In short: Code is often easier to maintain, more expressive and more flexible when one uses higher order functions.

An example in C#

Traditional approach:

```<code>public IEnumerable<Customer> FilterCustomers(IFilter<Customer> filter, IEnumerable<Customers> customers)
{
    foreach(var customer in customers)
    {
        if(filter.Matches(customer))
        {
            yield return customer;
        }
    }
}

//now you've got to implement all these filters
class CustomerNameFilter : IFilter<Customer> /*...*/
class CustomerBirthdayFilter : IFilter<Customer> /*...*/

//the invocation looks like this
var filteredDataByName = FilterCustomers(new CustomerNameFilter("SomeName"), customers);
var filteredDataBybirthDay = FilterCustomers(new CustomerBirthdayFilter(SomeDate), customers);
</code>```

With higher order functions:

```<code>public IEnumerable<Customer> FilterCustomers(Func<Customer, bool> filter, IEnumerable<Customers> customers)
{
    foreach(var customer in customers)
    {
        if(filter(customer))
        {
            yield return customer;
        }
    }
}
</code>```

Now the implementation and invocation become less cumbersome. We don't need to supply an IFilter implementation anymore. We don't need to implement classes for the filters anymore.

```<code>var filteredDataByName = FilterCustomers(x => x.Name.Equals("CustomerName"), customers);
var filteredDataByBirthday = FilterCustomers(x => x.Birthday == SomeDateTime, customers);
</code>```

Of course, this can already be done by LinQ in C#. I just used this example to illustrate that it's easier and more flexible to use higher order functions instead of objects which implement an interface.

Body:
Dependency Inversion in OOP means that you code against an interface which is then provided by an implementation in an object.

Languages that support higher language functions can often solve simple dependency inversion problems by passing behaviour as a function instead of an object which implements an interface in the OO-sense.

In such languages, the function's signature can become the interface and a function is passed in instead of a traditional object to provide the desired behaviour. The hole in the middle pattern is a good example for this.

It let's you achieve the same result with less code and more expressiveness, as you don't need to implement a whole class that conforms to an (OOP) interface to provide the desired behaviour for the caller. Instead, you can just pass a simple function definition. In short: Code is often easier to maintain, more expressive and more flexible when one uses higher order functions.

An example in C#

Traditional approach:

public IEnumerable<Customer> FilterCustomers(IFilter<Customer> filter, IEnumerable<Customers> customers)
{
    foreach(var customer in customers)
    {
        if(filter.Matches(customer))
        {
            yield return customer;
        }
    }
}

//now you've got to implement all these filters
class CustomerNameFilter : IFilter<Customer> /*...*/
class CustomerBirthdayFilter : IFilter<Customer> /*...*/

//the invocation looks like this
var filteredDataByName = FilterCustomers(new CustomerNameFilter("SomeName"), customers);
var filteredDataBybirthDay = FilterCustomers(new CustomerBirthdayFilter(SomeDate), customers);

With higher order functions:

public IEnumerable<Customer> FilterCustomers(Func<Customer, bool> filter, IEnumerable<Customers> customers)
{
    foreach(var customer in customers)
    {
        if(filter(customer))
        {
            yield return customer;
        }
    }
}

Now the implementation and invocation become less cumbersome. We don't need to supply an IFilter implementation anymore. We don't need to implement classes for the filters anymore.

var filteredDataByName = FilterCustomers(x => x.Name.Equals("CustomerName"), customers);
var filteredDataByBirthday = FilterCustomers(x => x.Birthday == SomeDateTime, customers);

Of course, this can already be done by LinQ in C#. I just used this example to illustrate that it's easier and more flexible to use higher order functions instead of objects which implement an interface.


答:
I have worked on VMs before for development, both local VMs (running on the local PC) and remote ones.  The local ones were much nicer to work with than the remote ones.

Remote VMs, which we were connecting to by RDP, had a small amount of lag between every keystroke and action.  It's possible to develop under such conditions for a short time but day-in day-out it became very frustrating.

I happily developed under a local VM on VMWare because I needed to run Flash Builder on a Linux machine, and was quite happy with it as long as it had enough memory - it was quite usable.


问:
Is Silverlight only for eye-candy, or does it have a use in business?
Granted that Silverlight may make eye-popping websites of great beauty, is there any justification for using it to make practical web applications that have serious business purposes?  I'd like to use it (to learn it) for a new assignment I have, which is to build a web-based application that keeps track of the data interfaces used in our organization, but I'm not sure how to justify it, even to myself.

Any thoughts on this?  If I can't justify it then I will have to build the app using the same old tired straight ASP.NET approach I've used (it seems) a hundred times already.

答:
My current job is building a Silverlight business application (as was my previous one) so you could see that as an argument for saying "yes it is for business applications"!

The current application is at its early stages and there are issues with Silverlight (even SL 4) that may cause us problems, but we'll be able to work round them in the short term and address then when new versions are released.

One of the things that I (and my boss) think is that Silverlight offers you a way to build desktop type applications for the web. Ultimately it might not be the best technology for this, but at the moment it seems to be the one that offers the greatest chance of succeeding.


答:
If you want to change the behaviour of a function

```<code>doThis(Foo)
</code>```

you could pass another function

```<code>doThisWith(Foo, anotherFunction)
</code>```

which implements the behaviour you want to be different.

"doThisWith" is a higher-order function because it takes another function as an argument.

For example you could have

```<code>storeValues(Foo, writeToDatabase)
storeValues(Foo, imitateDatabase)
</code>```

Title: How is dependency inversion related to higher-order functions?

Body:
Today I've just seen this article which described the relevance of SOLID principle in F# development-

F# and Design principles – SOLID

And while addressing the last one - "Dependency inversion principle", the author said:

From a functional point of view, these containers and injection concepts can be solved with a simple higher order function, or hole-in-the-middle type pattern which are built right into the language.

But he didn't explain it further. So, my question is, how is the dependency inversion related to higher order functions?

Body:
If you want to change the behaviour of a function

doThis(Foo)

you could pass another function

doThisWith(Foo, anotherFunction)

which implements the behaviour you want to be different.

"doThisWith" is a higher-order function because it takes another function as an argument.

For example you could have

storeValues(Foo, writeToDatabase)
storeValues(Foo, imitateDatabase)


答:
If you want it 100% up-to-the-minute accurate ...

Calculate the current situation periodically and cache it, then go and retrieve changes since that time.

The time period of "periodically" is a careful balance based on the volume of data (lean towards a long period) and the volume of changes (lean towards a short period). Keep good statistics, so that you can shift as the balance changes.

Title: What is an efficient way to retrieve product counts at multiple levels of a hierarchy?

Body:
I'm working on an e-business website to sell books and also want to display the number of available books in the category list.

The category list contains the genre and the format (pocket, ebook, audiobook etc). In each element in genre and format I would like to display the number of available products from the stock list. Of course, when you go deeper into the hierarchy, you retrieve more specific information of available books at that level.

For instance there are 2000 available books in the "medicine" genre and if I select the "pocket" format then there are 200 available books left. In other words, you have combined "pocket" and "medicine" and you know now that there are 200 available pocket books in total in the "medicine" genre.

My question is:

How do you create that functionality without making lots of effort to ask the database about the amount of available products in each element? Do you need to buy a special application or plugin? Please remember that there are millions of books in the database.


答:
You've got it right. Be paranoid. Don't trust other code, even if it's your own code. You forget things, you make changes, code evolves. Don't trust outside code.

A good point was made above: what if the inputs are invalid but the program does not crash? Then you get garbage in the database and errors down the line.

When asked for a number (e.g. price in dollars or number of units) I like to enter "1e9" and see what the code does. It can happen.

Four decades ago, getting my B.S. in Computer Science from U.C.Berkeley, we were told that a good program is 50% error handling. Be paranoid.

Title: How should I handle invalid user input?


问:
DB centric iPhone app question
The iPhone app i have an idea for deals with processing of the data stored as part of Oracle database at work. It'll be an interface to a dynamic set of data that is updated tens of thousands of time a day. Each time you look, results are likely to be different.

That being said, the company i work for does not have an enterprise appstore, which (as i understand it) means that i would have to publish my app onto the regular appstore with some kind of access key.

Q1. Is this a common practice, given no company specific app store
  exists?

I wonder if any of the cocoa API allows for east access and synchronization with Oracle databases.

Q2. If you know of one and can point me in the right direction, i'd be
  very grateful.

Is there anything else i should know when dealing with such a problem? Security is obviously a concern, the data will likely be of absolutely no interest to an outsider, but then again, we do want to be as prudent as we can be.

Please let me know

答: There are many many apps in the App store that require logins to work.  All banking apps and even the Facebook app.  Make sure to give Apple a test login when submitting the app, and it might help to mention in the review notes how many hundreds of people in your company are waiting to use the app.  But it's up to Apple whether to approve each App store submission on a case by case basis.</p>

Title: DB centric iPhone app question


答:
The #1 rule of development is to keep your developers happy. You will find that near-impossible to do with remote VMs. Multi-monitor support is spotty, network lag and blips are troublesome, and cost savings are generally minimal.

Work on VMs, sure, but allow for local VMs too, and make the physical computer a ridiculously fast beast too.

I telecommute 100%, and between my personal ISP and the VPN--despite high reliability--they have enough blips that would drive me nuts if I couldn't work in offline mode.

I generally just spin up a variety of VirtualBox images and work from them. Copying a few hundred MBs over the wire isn't too time-intensive if you need a new one locally either.


问:
How do you learn a language's standard framework/API/functionality?
I understand how to code. I know how to get around the basics of the languages I use regularly. I know how to write slightly-above-basic regular expressions, I can talk to databases, I can accept input, print output, handle files, etc. I'm more or less assured of my basic ability to spit out the source code for moderately complex program.

My problem is that I never feel like it's enough. I feel like I only know a small portion of the standard library of my language, and that until I understand it all, at least in passing, I have no right to even try to get a job using it. I'm just out of (community/junior/whathaveyou) college, and my friends are getting jobs in the industry, but I still feel like a fake or a poser and that I'm just not good enough.

Is there a decent marker for "I know enough" that I could use to assure myself that I can code? Should I take the fact that I'm at least capable of coding up a FizzBuzz as an indicator that it's alright to apply for things? How can I learn more of these standard libraries, frameworks, and/or APIs relatively easily? I code on a regular basis, I read books, but my knowledge still feels so shallow.

HELP!

答:
"I know enough" and "I'm good for this job" are completely different.

IMO "I'm good for this job" is closer to "I know the basics, and I know - what to learn/where to search/who to ask/what to read - to complete my tasks".

(this doesn't mean they will hire you if you need 1-2 months to learn for example: write/read in XML files. I hope you understand what I mean.)

Also, I don't think any programmer would ever say "I know enough." (maybe "enough to get the job", "enough to be rich", "enough to...", but not "enough." :) )

EDIT:
When I say "basics" I mean

Basics of programming (bit, byte, variables, functions, parameters, loops, conditions, recursion)

Basics of the programming language with which you will work (how to compile a program, how to debug a program; how to use the IDE; 90% of the keywords and know what they do, when to use, how to use them; variable types; how to use the things from 1 in the language; most useful libraries; error handling)

"Connect 1 and 2 with your blood" :)

(Possibly you will need to use 2-3 languages at your work)

I agree with Saeed, dive into the work, working is the best way to learn things, you work with people who know more than you, you learn from them, see how they work, but they started just like you (or maybe they started with less knowledge than you have now).


答:
I think that most of us have been in that situation at some point sooner or later in our careers. And every time you pick up a new language, it all starts all over again. So the first piece of advice from me would be: Don't despair, you're not alone. And: you're probably better than you think, if only for the fact that you self reflect. Remember the old adage: Fools rush in where angels fear to tread.

Nowadays most languages have standard libraries that are simply too large for any single individual to know completely by heart. Add frameworks and APIs on top, and you cannot possibly know it all. The best you can do is know the basics and then figure out where to find out more. It gets better with experience, so the best advice is probably: just go and use the stuff!

There is no single "decent" marker. It all depends on the environment. What would be perfectly enough for one company/project, may be way off for another. If you can really do what you say you can, I would class you a rather decent junior and you should have no trouble finding decent work.

Title: How do you learn a language's standard framework/API/functionality?

Body:
I understand how to code. I know how to get around the basics of the languages I use regularly. I know how to write slightly-above-basic regular expressions, I can talk to databases, I can accept input, print output, handle files, etc. I'm more or less assured of my basic ability to spit out the source code for moderately complex program.

My problem is that I never feel like it's enough. I feel like I only know a small portion of the standard library of my language, and that until I understand it all, at least in passing, I have no right to even try to get a job using it. I'm just out of (community/junior/whathaveyou) college, and my friends are getting jobs in the industry, but I still feel like a fake or a poser and that I'm just not good enough.

Is there a decent marker for "I know enough" that I could use to assure myself that I can code? Should I take the fact that I'm at least capable of coding up a FizzBuzz as an indicator that it's alright to apply for things? How can I learn more of these standard libraries, frameworks, and/or APIs relatively easily? I code on a regular basis, I read books, but my knowledge still feels so shallow.

HELP!


问:
Adding unit tests to a legacy, plain C project
The title says it all. My company is reusing a legacy firmware project for a microcontroller device, written completely in plain C.

There are parts which are obviously wrong and need changing, and coming from a C#/TDD background I don't like the idea of randomly refactoring stuff with no tests to assure us that functionality remains unchanged. Also, I've seen that hard to find bugs were introduced in many occasions through slightest changes (which is something which I believe would be fixed if regression testing was used). A lot of care needs to be taken to avoid these mistakes: it's hard to track a bunch of globals around the code.

To summarize:

How do you add unit tests to existing tightly coupled code before refactoring?

What tools do you recommend? (less important, but still nice to know)

I am not directly involved in writing this code (my responsibility is an app which will interact with the device in various ways), but it would be bad if good programming principles were left behind if there was a chance they could be used.

答:
Grab a copy of Working Effectively With Legacy Code by Michael Feathers. It is meant to deal with such situations. Even though it is focused more on OO languages such as C++ and Java, I believe it may still help you a lot.

Looks like part of it (or an early draft article) is even available for free here.


问:
Is it out of line to give unsolicited constructive criticism to a programmer?
I recently started work at new office that uses a proprietary program written by a solo developer. He's occasionally around as part-time tech support, but the company has signed off on this software and he's no longer being paid to develop it.

As a user of his software there are many issues that leap out to me as a source of concern:

very simple to directly view the DB as a low-privilege user

passwords stored as plaintext

dictionary admin passwords

app uses the DB root account

DB doesn't meet 1NF (eg. appointment1, appointment2, etc.)

I feel like these are serious issues and that if I were him I'd want them pointed out to me, but I'm not a qualified programmer (I'm a social worker) and I don't know if it would be rude of me to just buttonhole him and start blabbering about salted hashes and normal forms, especially when this is no longer a paid task of his.

Is it out of line? If not, how would you broach it?

Edit - more info prompted by comments:

The application holds sensitive data.

It's for internal use, but it's running on lots of machines in several cities and many visitors come through our offices.

My concerns are for the developer's future projects as well as this specific one.

答:
First of all, as an end-user, you are one of the most important stakeholders in this software development project. Your views are totally valid, and they deserve to be heard by management!

Secondly, you do seem to know what you're talking about (you know when a DB isn't properly normalized), regardless of your job title or academic credentials.

Thirdly, you obviously feel very strongly about this matter.

So you should voice your concerns to management. Just make sure that you state your case articulately and in a highly respectful manner.


答: There's a fairly good chance that Apple will say no on the grounds that it's not useful enough for a large number of people, if it's a work project I'd really recommend looking at getting an enterprise developer license and going down that route.</p>

Title: DB centric iPhone app question

Body:
The iPhone app i have an idea for deals with processing of the data stored as part of Oracle database at work. It'll be an interface to a dynamic set of data that is updated tens of thousands of time a day. Each time you look, results are likely to be different.

That being said, the company i work for does not have an enterprise appstore, which (as i understand it) means that i would have to publish my app onto the regular appstore with some kind of access key.

Q1. Is this a common practice, given no company specific app store
  exists?

I wonder if any of the cocoa API allows for east access and synchronization with Oracle databases.

Q2. If you know of one and can point me in the right direction, i'd be
  very grateful.

Is there anything else i should know when dealing with such a problem? Security is obviously a concern, the data will likely be of absolutely no interest to an outsider, but then again, we do want to be as prudent as we can be.

Please let me know


答:
At my last job, we did quite exactly that:

We used a Windows Terminal Server, where every developer had an account. The developers still had regular PCs (because they were already there), but the PCs only ran the RDP client.

We did Java development, so the software used where Java compiler + IDE (mostly Eclipse), plus web browser, DB query tools, version control client, and occasionally office sw (OpenOffice.org in our case).

We did not encounter any real problems, and performance was quite decent.

The only real problem was that you really need to take care not to disrupt others in some situations, because you are sharing one system. When IT operations needed to do large file copies or run backups on the server, performance degraded for everyone. When we identified and solved this (by copying with low priority, or overnight), everything performed well.

So the caveat is: Evaluate performance as soon as possible, and plan your hardware and its use accordingly.


问:
Switching from SVN to Mercurial: one repository or many?
We currently have a large Subversion repository, with a tree like:

```<code>root
    /libraries
        /library1
            /trunk
        /library2
            /trunk
    /solutions
        /solution1
            /trunk
        /solution2
            /trunk
</code>```

There are 81 solutions and 22 libraries.  The trunk subdirectories were added so we could use branches, but in practice, we don't use branches at all.

My question is: if we migrate this to Mercurial, should be set up one big Mercurial tree with the same structure?  Or should we create 81+22 Mercurial repositories?

答:
Why not something in between? I strongly suspect the libraries should be subrepos (a bit like external in svn)

The solutions could either be seperate repos if they are unrelated, or if there is some relation between them, perhaps named branches in one (or a few repos)


问:
In a javascript only web application, what state information should the URL contain?
I'm writing a single page web application that talks to a business layer via asynchronous RPC (encoded with json).  I'm targeting fairly modern browsers, so I can at minimum control the URL after the hash.  However, the URL won't really be what drives the application's state (that will be maintained by a javascript model layer), so I don't have to do anything with it.  I could even keep it the same the whole time without any implementation problem.

The question is, what should go in the URL?  I won't go into the application because I'm hoping the question is generally useful.  What kinds of expectations do users have about backward and forward buttons?  About typing in a URL?  Are there currently any generally applicable best practices yet for this kind of application?

答:
The URL should be used for what it does: locating a resource.

You should put in the URL only things relative to the location of the resource, so users will be able to always find it (bookmark, permalink). With this in mind, you should avoid to insert variables in it or other custom data.

Just look at the link of this question for example, and how easy it is to share between social networks.

You should also consider that many users (like me) may prefer to navigate your site directly from the URL bar. For example playing with numbers. If I'm reading a blog article with a URL containing a folder named 2011, I could try to remove all the URL part up to the year folder, expecting to see a page which contains all the 2011 articles.

Then I could also change 2011 to 2010 to browser last year articles, and so on...

Too often websites provides very basic (and sometimes inefficient or completely absent) navigation commands. It's often easier to navigate a website directly via the URL bar.

Edit

I would also like to add that the URL should describe as much as possible what is the content of the linked resource, using clear keywords, not random numbers or misleading/useless words.


答:
One of the interfaces of web applications, is URL (address bar). It can be considered a counterpart to API (application programming interface) in the same facet that some of the behaviors of the application can be controlled directly from the URL. For example, you may directly type http://www.yoursite.com/update/john/phone-number-to/9195527768. This way, you can controls your web application directly from address bar and address bar becomes something similar to command line, and URL becomes a command.

Another usage of the URL as others said can be bookmarking. You may remember Back button problem of AJAX applications. It prevented users from being able too bookmark one specific state (or page, or resource) of a website. For example, consider that your site is http://www.yoursite.com. No matter how much your site's visitor interacts with it, he still sees http://www.yoursite.com. How the heck he/she is supposed to get a link to one specific resource of your site and send it to his/her friend? Via Firebug?

Also if you don't change the URL while changing the state of your application, no entry would be added to window.history object, thus if user click Back button, instead of being taken to the previous state of your site (or application), he/she would be taken to the previous domain (maybe google.com, maybe yahoo.com, any domain, but not yours). This is a seriously frustrating experience. Paralle Plesk's control panel works just like what you describe here, and it's awful.

Another usage of URL would be SEO (search engine optimization). Google, Yahoo, and Bing would know and index your site's content based on the URLs you submit to them. One URL, one index, less chance to be found on the net.

I strongly recommend that you redesign your work. No offense, but when we say best practice, we mean something that has been done by many people and organizations. What you want to do is so rare that I can't remember any example of such an application. Best practice comes from repeated implementation of something. I believe that there is no best practice for this architecture.

Title: In a javascript only web application, what state information should the URL contain?

Body:
I'm writing a single page web application that talks to a business layer via asynchronous RPC (encoded with json).  I'm targeting fairly modern browsers, so I can at minimum control the URL after the hash.  However, the URL won't really be what drives the application's state (that will be maintained by a javascript model layer), so I don't have to do anything with it.  I could even keep it the same the whole time without any implementation problem.

The question is, what should go in the URL?  I won't go into the application because I'm hoping the question is generally useful.  What kinds of expectations do users have about backward and forward buttons?  About typing in a URL?  Are there currently any generally applicable best practices yet for this kind of application?


答:
If you have a mainframe with 50 SSD disks in RAID10, and only use 3-4 machines on that mainframe, then it might work.

Otherwise they are laggy, really laggy (although in some rare cases snapshoting can offset that).


答:
My recommendation buddy:

stop thinking binary (0/1, not knowing/knowing, illiterate/literate) and start thinking fuzzy (I know to some extent). All of us know something and to some extent. Knowledge is a continuum and everyone is placed somewhere between the most illiterate person and the most knowledgeable, sophisticated guy. You can do the job, but at your level and under that. This is the rule. Don't be afraid. Don't wait for a day when you've learned everything of your framework, and IMHO that day won't come ever. Even developers of 20 years of experience are still reading to learn new things. Programming is so broad in nature that you shouldn't (or you can't) grab it all.

Dive into the work environment and don't be afraid. We all had the days when we couldn't do something. That's not a crime. It's part of our job. You don't know, you learn, you try to do the job, and you get it done.

I think what you need to have now, is not more knowledge. Rather, it's simply self-confidence.

Good Luck


问:
Does every ASP.NET Web Application has a Single Application Domain?
I am bit confused. Is there only one application domain for every single ASP.NET Web Application or there can be anywhere between 1 to 100 application domains present in a single application pool of a web application</p>

答:
An Application Domain is the logical and physical boundary created around every .NET application by the Common Language Runtime (CLR).

One web application runs in a single Application Domain but may communicate via web/remote services with applications in other domains.

The CLR may allow multiple .NET applications to be run in a single Application Domain, so it means that an Application Domain may be shared by different applications which can in that case communicate with each other "directly".

Most times though, the relationship between a web application and an application domain is one-to-one.

You may read the following article (very short, but nicely written) which explains what are Application Domains and how they may be useful: http://www.beansoftware.com/NET-Tutorials/Application-Domain.aspx.

Also, on his blog, Scott Forsyth explains the differences between an application (IIS term), a web application (ASP.NET term) and application domains.


问:
What is the difference between a prototype and a production level solution?
This question is purely for learning and to step-up my technical understanding.  I know there is no perfect solution and this question has possible never ending solution list but I think it's very important for every architect to understand the difference between demo and a live project.

I created many demo solutions in .Net in the past.  I now have been assigned to architect and implement a production level web solution so I wanted to ask - on a very high level, what is required to convert a demo into a production level solution.  From my understanding, this will require (other than functionally implementing clients' requirements):

Unit testing every method

Ensuring ~100% code coverage is achieved

Logging all exceptions and possible pointcuts - possible with AOP

Using interface design pattern, dependency injection, possibly by
using a framework e.g. spring.net

Using performance counters and
profilers for instrumentation

Applying appropriate security - i.e.
windows authentication (if that's whats required by client).

Transaction management on every single method

Back up of the web application files before new deployment of solution

What else?

My question is more related to technical side instead of functional/documentation because otherwise we will go into another path :-)

Thank you.

答:
Not all of those things are required, depending on your requirements, or there might be way more required.  If you know what I mean ;)  Unit testing and code coverage are good things, but depending on how you go about other parts of the process, might not be required.  Some would say that more important than performance profiling is well-documented code, or a training manual.  It varies!

I realise you're looking at the technical side but hopefully you will understand my point, it varies depending on the non-technical side.  Or at least, it should.

Using performance counters and profilers for instrumentation.. might be suitable, but might be massively overkill.  Might not be required.

What you're missing here is failing to account for the context, scope and business requirements of the project.

By context and scope I mean - are you creating something to be used internally by a business?  Customer-facing?  Used by end-users?  Is it in fact a jazzy version of Notepad, or a new RDBMS from scratch?  What should be included will vary massively (massively!) by the project you are looking at.

By business requirements I don't mean the use-cases for the software, but the requirements of the project management / production process.  If you insist you need all of those things for a production project, the cost will be reflected accordingly (very high).  That could either mean it's over budget, late, or not even given the green light to start development.

It could be that more important than having a fixed set of criteria now is simply having a good production/development framework, high visibility and regular releases so quality can be assessed that way.  It could be that no-one involved gives a crap about code coverage.

OwnerDisplayName: KnowledgeSeeker


答:
I think the most important difference is that a prototype's objective is:

1. To prove that a problem can be solved in a certain way  OR

2. Give client / management a feel of what the product would look and feel like

whereas the objective of a live system is:

1. To solve a certain problem / address an issue.

Notice that the objectives of the two are completely different.

Therefore, in my opinion a prototype should be thrown away before developing a live system.

This is also because a prototype is usually a 'quick and dirty' project, thrown together without any of the considerations you've rightly pointed in your question (like testing, performance, security and a lot more).

So you'd be better off starting a new, proper project, than trying to make a bad project better.

Title: What is the difference between a prototype and a production level solution?

Body:
This question is purely for learning and to step-up my technical understanding.  I know there is no perfect solution and this question has possible never ending solution list but I think it's very important for every architect to understand the difference between demo and a live project.

I created many demo solutions in .Net in the past.  I now have been assigned to architect and implement a production level web solution so I wanted to ask - on a very high level, what is required to convert a demo into a production level solution.  From my understanding, this will require (other than functionally implementing clients' requirements):

Unit testing every method

Ensuring ~100% code coverage is achieved

Logging all exceptions and possible pointcuts - possible with AOP

Using interface design pattern, dependency injection, possibly by
using a framework e.g. spring.net

Using performance counters and
profilers for instrumentation

Applying appropriate security - i.e.
windows authentication (if that's whats required by client).

Transaction management on every single method

Back up of the web application files before new deployment of solution

What else?

My question is more related to technical side instead of functional/documentation because otherwise we will go into another path :-)

Thank you.


答:
You have a great attitude! One of the fundamental factors in being successful is to never be complacent. Never settle. Never compromise yourself. That said, it's very hard to discern how exactly to do that (e.g. knowing the 'best practice' for doing task X isn't as simple as Googling it because everyone has their own opinion).

It's best to learn how to identify good code and the rationale behind it (how and why). For this, I'd recommend reading blogs of reputable professionals in our field as this will expose you to the sort of mindset to look for. Contributing to an open-source project is also one way to jump into the deep end, however, it'll give you the opportunity to learn from others as it currently progresses.


答:
Interestingly, I think points 1, 2, 4 and 7 should already be done during the conception of your prototype, except that I don't think you should test every method in every class. Test the critical code, not whether get/set methods behave correctly.

Depending on the purpose of your application, where security is a big problem, point 6 may be critical enough that you need to achieve it in the prototype. Depending on the purpose of your application, where performance is the key, point 5 may be critical... You know what I mean. My opinion is that points 3, 5, and 6 may be necessary in the prototype if they are considered critical (point 8 is really valid for production applications)

Edit: it seems that my opinion differs completely from sJhonny's because I imply that I consider the prototype to be the basis/shell/skeleton of your future developments, so for me the prototype is not to be thrown away.


答:
For techniques, probably the Michael Feathers book in Péter Török's answer will be pretty comprehensive. If you don't want to go to the book, I suggest a three-step process:

examine the non-testable code, and duplicate small parts of that code's functionality into testable functions. It's important that the new functions have behavior that's obviously equivalent to the function you're trying to duplicate - I'm not actually advocating writing unit-tests around the legacy code, so you need to be very careful, and limit your scope, in order to maintain confidence in the refactoring.

write unit tests around those new functions.

modify the original code to call the new functions.

Repeat this process a few times, and you should find the quality of the legacy code base has increased significantly.

As far as tools go, note that C++ can call into C, so any C++ unit-testing framework can be used to test C code. For example, we're using CPPUnit to unit-test a bunch of C code in our project.

Title: Adding unit tests to a legacy, plain C project

Body:
The title says it all. My company is reusing a legacy firmware project for a microcontroller device, written completely in plain C.

There are parts which are obviously wrong and need changing, and coming from a C#/TDD background I don't like the idea of randomly refactoring stuff with no tests to assure us that functionality remains unchanged. Also, I've seen that hard to find bugs were introduced in many occasions through slightest changes (which is something which I believe would be fixed if regression testing was used). A lot of care needs to be taken to avoid these mistakes: it's hard to track a bunch of globals around the code.

To summarize:

How do you add unit tests to existing tightly coupled code before refactoring?

What tools do you recommend? (less important, but still nice to know)

I am not directly involved in writing this code (my responsibility is an app which will interact with the device in various ways), but it would be bad if good programming principles were left behind if there was a chance they could be used.


问:
Is there any evidence that Intellisense reduces productivity?

Possible Duplicate:

  Should newbies use IDE autocomplete (Intellisense)?

I was having a conversation with another developer the other night about the pros and cons of Visual Studio. He was of the opinion that Intellisense reduces productivity. Of course I thought that was insane but I could be wrong. Is there any evidence to support the idea that Intellisense reduces productivity?

答:
The same sort of arguments happen around spellcheck, and the use of calculators in schools. The idea being that students having free access to calculators reduces their mental arithmetic ability.

I would agree that that effect is probably true, and would argue that it is also unimportant. Calculators are always available, and so it would be more productive to spend time learning to solve Second Order Differential equations than learning to do complicated division in your head.

If you use an IDE with a good implementation of something like Intellisense, then yes, certain skills will wither, and that's because you're spending more time doing other things. Things that are more productive for your code than remembering  the precise name of a particular member function.

If you plan to go back to a non-Intellisense IDE, then you might have a problem. In that case, turn it off. For the rest of us who assume that IDE's will only advance, we're OK.

Yes, Intellisense may encourage API designers to put too many arguments in, but writing something like C++ requires a lot of discipline to not do any of the many bad things it allows you to do, and this is just one more.

One final analogy: you don't turn off syntax highlighting just in case you have to edit a file in notepad later, do you?

OwnerDisplayName: craigmoliver


答:
I would say "No" to both questions, without hesitation.

Is it still worth it to protect our software against piracy?

No, and a lot of companies and independent developers have demonstrated that there's no need.

The Humble Indie Bundle is an exceptionally good example of one possible way of making a killing in spite of active "piracy." In a single 3-week event, five developers made, together, almost US$900,000 on their five games (plus one), without DRM, and even without a concerted effort to control access to the download links. And despite rampant sharing by people who paid, an average of US$10 per copy was paid, 30% of which went to charity. (This is, admittedly, a rather exceptional example in that it's not the norm even for this kind of sale event, but it is a good demonstration of how non-standard sales models can work extremely well.)

Companies like Introversion Software and Stardock make a lot of money despite a 90% piracy rate.

Another good example is Illumination Software Creator, which is doing very well for itself.

Or look at Minecraft, which has chosen a "freemium" model and is earning (as of this week) the author $100,000 per day.

Even when people stop fighting "piracy," they tend to do very well for themselves.

Are there are reasonably effective ways to prevent or at least make piracy difficult?

No, and frankly, it's rather pointless. Software can and will be copied as easily as you copy values within your program. No matter what efforts you make to protect your software against "piracy," so long as the end-user will at any point have a copy of the program, someone will distribute it to others without cost.

The only two ways to prevent "piracy" are: Make your software a service, such as a web application, or open your source code (or otherwise license your software for free distribution).

The only way to discourage "piracy" of software with a price tag is to set a price more in line with the value your customers perceive in the product, or to attach that price to actual services (like providing support). No one will pay $60 for something they can get for free in another product.

(On a side note, I object to the term "piracy," since its etymology implies theft. Copyright infringement is not theft, no matter how you look at it, and to equate the two is intellectually dishonest. I would prefer a term like "illegitimate customer" or "untapped market.")

Title: How do you prevent the piracy of your software?

Body: Is it still worth it to protect our software against piracy? Are there reasonably effective ways to prevent or at least make piracy difficult?</p>


问:
What is the most orthogonal programming language?
I find myself repeatedly annoyed by having to teach freshmen about special language rules (like array-to-pointer decay) that have absolutely nothing to do with programming in itself. So I wondered:

What is the programming language with the smallest number of special language rules, where everything is first class and can be composed without annoying technical restrictions? Wouldn't such a language be the perfect teaching language?

Moderator Note

We're looking for long answers that provide some explanation and context. Don't just list a language: please explain why you think the language answers the question. Answers that don't explain anything will be deleted. See Good Subjective, Bad Subjective for more information.

答:
When it comes to 'very few rules', I would argue, Lisp or Smalltalk would win. The bare Syntax can be written on one beer tab.

But in my experience, the simplicity of Lisp and Smalltalk does not mean they are simple to understand and easy to teach. While not the 'pure' way, in my experience the to-do-list-style of imperative languages is the easiest to grasp for newbies.

Therefore, I would suggest Python, Ruby or something of similar abstraction: You find (nearly) every basic concept in them (OK, no pointers), but you don't need to understand it from the start to make something working.


问:
What was the first hierarchical file system?
"Directories containing directories and files" seems to have been around forever, but there must have been a first.</p>

答:
An early hierarchical file system was developed for the Electronic Recording  Machine Accounting (ERMA) Mark  1, as presented in this 1958 Eastern Joint Computer Conference paper
Organization Generated  in and  Retrieval  of  Records a  Large-Scale  Engineering Project by G.A. Barnard III and L. Fein:

Fig.  3  is  self-explanatory.  It   shows the  arrangement  of the
records in the  file  folders.

This  file  system is  "closed"  in
the  sense  that   it  is  bounded  by  the   decimally  integral
coding of categories from 00 to  100  and  by  an  exahustive
listing  of  generic attributes   and  categories.  However,  it  is
expandable in the  sense that,  when necessary.  new  entries  are
permitted  within  the   subcategories  and  parameters   without
resorting to modification of the  original  file  structure.
For example,  categories  test  equipment-51,  external  equipment-52, and
tools-53, were added later  in the   only  reasonable  location;  in
the   50  series, auxiliary equipment.  This  method of adding new
categories to the  file  can be  likened to the  use of the  familiar
accordian file  in  which  a  suitable   pocket   can  be  stretched
to  fit  new  material,  but   the  structure  of the  containing
folds of the  file  and its  major   pockets remain unchanged;  This
is  in contrast  to  a  file  of  rigid  construction in which  the
only  recourse  for  addition is to append material  or  to make  a
new  container.

OwnerDisplayName: Kent Beck


答:
I'd say LISP, or Scheme or a language from that family would be the most orthogonal. With let, lambda, define, if, cons, list, and ( ) you can teach pretty much anything that you'd want to in an intro course. There's also no need for preprocessing directives or int main() and stuff like that which students just include but don't see a reason for.

In my intro CS courses, we did a lot of really cool things with Scheme: implement a Turing machine, implement a TC-201 computer, write a context free grammar, use recursion, write merge and insertion sort, implement adders, and tons of other stuff.

I had done Java in AP comp sci before college, but Scheme was great because I could cut the clutter and focus on the actual concepts in my program. It was a great class and I'd highly recommend you try it for your teaching.

Title: What is the most orthogonal programming language?

Body:
I find myself repeatedly annoyed by having to teach freshmen about special language rules (like array-to-pointer decay) that have absolutely nothing to do with programming in itself. So I wondered:

What is the programming language with the smallest number of special language rules, where everything is first class and can be composed without annoying technical restrictions? Wouldn't such a language be the perfect teaching language?

Moderator Note

We're looking for long answers that provide some explanation and context. Don't just list a language: please explain why you think the language answers the question. Answers that don't explain anything will be deleted. See Good Subjective, Bad Subjective for more information.


答:
I agree with the approach of pre-calculating the figures proposed by Mr. Wesley van Opdorp.
His approach will make your on-line processing unaffected by changes in the categories.

There is also another option you may want to consider.

You can create a statistics table with several columns, each representing a level within the tree you show  on the left hand-side.

Every time an operation of create, update or delete takes place on a book, the number in the corresponding column of the statistics table is either increased or decreased (update is mentioned here in case you update a category of a book, in which case 2 updates to the statistics table will take place). You can use the statistics table to show the tree.

This will keep the numbers accurate and will have make it very quickly to display your data.


问:
Can it be useful to build an application starting with the GUI?
The trend in application design and development seems to be starting with the "guts": the domain, then data access, then infrastructure, etc. The GUI seems to usually come later in the process. I wonder if it could ever be useful to build the GUI first...

My rationale is that by building at least a prototype GUI, you gain a better idea of what needs to happen behind the scenes, and so are in a better position to start work on the domain and supporting code.

I can see an issue with this practice in that if the supporting code is not yet written, there won't be much for the GUI layer to actually do. Perhaps building mock objects or throwaway classes (somewhat like is done in unit testing) would provide just enough of a foundation to build the GUI on initially.

Might this be a feasible idea for a real project? Maybe we could add GDD (GUI Driven Development) to the acronym stable...

答:
I think it is an extremely good way of approaching application design, especially in an agile development environment. Most of the succesful projects I have worked on have started with a prototype that eventually became the real thing.

You have to understand that the GUI is the window into the system (ie. database, filesystem,etc). In a situation where the project requirements are about as vague as a pile of slush, then you won't have a hope in hell in getting a correct solution by starting on the backend. Almost always, the well intentioned backend developer develops a bunch of API which has no relevance to user interactions.

By starting on the GUI, the customer gets a better idea of what they want. As this stage progresses, the developement of the GUI (using mocks and stubs) gives birth to a domain model. This domain model can then be transferred to the backend and the back end developers can start developing the persistance and transactional logic.

And why would you want to throw away the protoype? We are not dealing with stadiums built out of matchsticks. Just refactor the damn thing into something good.


问:
What are the steps in beginning a large project, when all I have is a big idea?
I am computer engineering student. I've been thinking about
how I can handle a big project. What should be my first step to reach my goal in a more efficient and effective way?

When I come up with a project, I don't know how I should start working on it. Many times, I just ignore it. However, I don't want to ignore my project ideas anymore.

Now, I am asking to all of you, can anyone share his/her experiences? How should I start a project when all I have is an idea?

答:
Split big things into smaller things.

You cannot work on "achieving world peace". Instead you work on banning Weapons Of Mass Destruction, you encourage democracy, you provide development aid, you encourage cultural and scientifical exchange and so on.


答:
In addition to what has been mentioned already, in a production project you need the following (among others):

0-Choose an implementation methodology

1-Finalize and publish major requirements (including use cases, etc.)

2-Get the architecture right

3-Select the correct tools

4-Design database for performance

5-Produce your class design and workflow design

6-Determine and implement a strategy to integrate backed databases/data sources/feeds

7-Define and Implement security requirements

8-Arrange for physical implementation (Servers, connectivity, licenses etc.)

9-Plan for storage requirements and determine performance measures

10-Produce all artifacts and install in production environment

11-Test

12-Deliver final solution and implement feedback


问:
Do you sign each of your source files with your name?

Possible Duplicate:

  How do you keep track of the authors of code?

One of my colleagues is in the habit of putting his name and email address in the head of each source file he works on, as author metadata.  I am not; I prefer to rely on source control to tell me who I should be speaking to about a given set of functionality.

Should I also be signing files I work on for any other reasons?  Do you?  If so, why?

To be clear, this is in addition to whatever metadata for copyright and licensing information is included, and applies to both open sourced and proprietary code.

答:
I think it's not so bad a habit.

Others argue, that VCS will do that for you. Well, up to a certain point, that is true.

If however you release code under a weak copyleft (MIT or whatever), you can almost bet, that somebody will integrate a snapshot of your code into their code base and will make his own modifications. They will not be able to tell the difference between original comments and the comments of the person, who made the original check-in.

Same thing applies when code bases move to other VCSs (for example from CVS to git). You can't really tell whether all that metadata will make it into the new VCS (I would expect there is some way to migrate it).

So to answer the question:

When it adds significant value to know the author of a piece of code (which is not always the case), than adding the author right into the source file is a good idea. That doesn't mean that you should document and sign every single change you make to a source file.


问:
Should Unit Testing be used in Prototypes?
When constructing prototypes, should we also create appropriate unit tests as if we were writing production code? Would it make a difference if we knew in advance that the code was or wasn't going to be re-used for the final solution?

答:
I don't write unit tests, unless the code is about solving a complex issue with complex requirements. In that case, I write a couple tests. I try to rely on existing/tested modules as much as possible to avoid re-inventing the wheel.

It is only later, when the decision is taken to move the prototype into production that I fully test it with a complete set of unit tests.

OwnerDisplayName: JVerstry


答: I usually don't write unit tests of prototypes, cause I don't reuse prototype code. If I knew that the prototype code would be promoted to production code at a later stage, I would definitely write unit tests up front.</p>

Title: Should Unit Testing be used in Prototypes?

Body: When constructing prototypes, should we also create appropriate unit tests as if we were writing production code? Would it make a difference if we knew in advance that the code was or wasn't going to be re-used for the final solution?

OwnerDisplayName: ThomasArdal


答:
Even in a prototype, it's good to know what each part is supposed to do. When you write a prototype, you still want to understand what's wrong with your code when something doesn't work as expected. Unit tests are the best solution to figure it out.

Furthermore, unit tests are a great way to clarify your mind about what each part of your prototype is supposed to do and most of the time, it can serve as base code to write the tests when you write the production version.

But... It really depends of the size of your project and of its complexity. For a small project it might be easier to go ahead and make things works.

OwnerDisplayName: Nicolas


答: Unit testing is about product and code quality. If you want to be sure about your product quality, use unit tests.</p>

OwnerDisplayName: Petr Klíma


答:
What is the purpose of creating a prototype, rather than version 0.1 of the application? It should be to provide some information about the application domain or an algorithm that you lack. The quality of the information you get can not be better than the quality of the prototype itself, so you should ask yourself:

If I do not create unit tests, will the resulting prototype have enough quality for me to rely on the information I get from it?

In most cases I beleive the answer is "no".

OwnerDisplayName: Raedwald


问:
How to tackle a boss/manager who likes to race the coders
After a recent restructuring happened in our corporation - I have got a new line manager. He is generally ok and not as sneaky as the previous one. By "sneaky" I don't mean he was an evil manager - I just refer by this term to someone who keeps most of the information to himself and doesn't share with other team members in order to be the only "go-to person" - you get the idea.

But nonetheless I had managed to maintain quite a good relationship with my previous manager - and I had been quite productive.

My new boss is more open, which is a good thing, but I really hate one his quality - he likes to race the coders - by giving the same task to a different developer in order to fix the issue ASAP. As you may have already understood the information does NOT flow freely in an environment like ours. So the person who my manager was talking to 10 minutes ago might be starting work on the same issue I am working on now. It happened a few times, and every time I overheard that there might be someone working on the same issue - I did go and ask my manager - who owns the issue - but he usually was very evasive in his answers.

So my question is - how to stop my manager from doing it? In our small team of half a dozen developers I am the most senior one and I am usually spared from the racing but when it hits me it really gets to my nerves.

And one more thing: I am not implying that my manager is a bad/evil boss, neither I believe in that the world is or should be fair, I just want to find a way to make him stop racing me. One thing at a time.

答:
First question is : why does he do that? Is it because he likes to compare different answers and pick the best one? Is it because he likes to see who can do it the quickest? That's rather important to tackle the behaviour.

I understood from the "racing" part it's the latter. Then a simple calculation can show him why this is not exactly the way to go.

Say he gives task A to coder A. He starts working and fixes the task in an hour. He also gives task A to coder B. That one starts working on it as well, and after 45 minutes gets to hear to problem is solved and he can go on to the next task B. He solves that in 1 hour, and coder A has been working on that one as well for one hour.

Apart from the problems that can arise when two coders mangle with the same part of the code, he got the task A fixed in one hour for the cost of 1h45 minutes, and task B in another hour for the cost of 2 hours.

Even if coder B would have fixed task A it in 1h30min, it would still have been cheaper. Especially because the 45 minutes from coder B are completely non-productive, and so lost money. Say that coder B would have fixed it in 1h30min, coder A could have solved task B in the meantime as well: 2 tasks fixed in 1h30 minutes for the price of 3hours, versus 2 tasks fixed in 2 hours for the price of 3h45minutes. Which one is more productive then?

To get more into manager speech :

racing will likely frustrate the coders that are working on something for some time and notice that it has been useless.

racing also will cause the impression that whenever you get a task, somebody else is working on it as well. So why hurry? (in case the coders are getting bonusses on accepted code, the racing will likely lead to faster and hence less secure coding. Opposite effect, same argument)

racing is not cost effective, as it gets less done in the same amount of time for a higher price.

If your manager knows something about programming, you can say that his approach is serial, and parallel goes faster.


答:
Send this question in an email to him. You discribed clearly what the problem is and why you didnt like it.

You also might want to have a word with your colligues. Chances are they feel just as annoyed as you. He will have to listen if sevral employees raise the issue with him.

Title: How to tackle a boss/manager who likes to race the coders

Body:
After a recent restructuring happened in our corporation - I have got a new line manager. He is generally ok and not as sneaky as the previous one. By "sneaky" I don't mean he was an evil manager - I just refer by this term to someone who keeps most of the information to himself and doesn't share with other team members in order to be the only "go-to person" - you get the idea.

But nonetheless I had managed to maintain quite a good relationship with my previous manager - and I had been quite productive.

My new boss is more open, which is a good thing, but I really hate one his quality - he likes to race the coders - by giving the same task to a different developer in order to fix the issue ASAP. As you may have already understood the information does NOT flow freely in an environment like ours. So the person who my manager was talking to 10 minutes ago might be starting work on the same issue I am working on now. It happened a few times, and every time I overheard that there might be someone working on the same issue - I did go and ask my manager - who owns the issue - but he usually was very evasive in his answers.

So my question is - how to stop my manager from doing it? In our small team of half a dozen developers I am the most senior one and I am usually spared from the racing but when it hits me it really gets to my nerves.

And one more thing: I am not implying that my manager is a bad/evil boss, neither I believe in that the world is or should be fair, I just want to find a way to make him stop racing me. One thing at a time.


答:
IMHO Your manager is wasting resources and time by having multiple people work on the same project.  If he's covertly trying to evaluate skill/productivity I feel that there are much better approaches, otherwise it might be valuable to understand what his actual reason for doing this is.

With that said, with any game there have to be players ... if the players won't participate then you don't have a game.  If you feel you can approach the manager directly and express that his behaviour is probably hurting the team (productivity, morale) more than helping, he might be inclined to rethink it.

The not so nice answer after that is that as a team you can respond passively to his behaviour by not participating in it.  Don't race.  Do your job, produce your solutions, but don't race.  It might mean that 1 coder on your team will race and look like a superstar to that manager ... that's something you'll have to live with.


问:
What's a good way to store/load a word list with thousands of entries?
I'm working on a project that requires a simple dictionary for checking spelling; it will be large, but will lack definitions. The solution we're currently working on has the base word list in a text file, and customizations (extra words, excluded words) in the DB.

The entire list needs to be loaded (best cached I think) for paginated display and customization using an existing JS widget, so what's the best way to store and load the base word list?

My initial thought was to have a text file with one word per line and write my own loader and cache object, but my boss suggested using a ResourceBundle to leverage the built-in caching. I'm thinking that could be done by using the words as keys with empty values and using the keyset of the bundle.

What would be the best solution to this?

答: Is this for a language that does not already have dictionary files out there?  I'm not 100% certain, but I was pretty sure that the Aspell open sourced dictionaries were available to developers...</p>


问:
Best resources for learning Play! Framework
Awhile back I discussed the possibility of moving to a startup that is going to be using Java, more specifically the Play! Framework; well, I'm going to go for it! I have been a .NET guy for a long time now and haven't really been in the Java game except for the occasional Android tinkering or messing around with Scala a little bit. I have looked at the Play! Framework before but only on a cursory level. I think I will be fine with Java as a language, as I've been given great advice before on learning materials.

My question, is aside from the very great site for the Play! Framework I haven't found much else out there except a few blogs. Does anyone know of any other good resources for the Play! Framework like books? An Amazon search turned up zero results.

I know there is an eBook floating around out there but it seems a little outdated at this point. Anyway, thanks for your input.

答:
Introduction to Play! Framework is an excellent introduction to Play.

In the recent days Play Framework Cookbook appeared that cover the framework in much detail. With this book, and willing to have a look at Play's code (it's really easy to follow!) you'll be able to move with Play! at ease.

Also you should sign in Play Framework Google Group and follow Play Framework Knowledge Base for news and articles.


问:
If you could only have one programming related book on your bookshelf what would it be and why?
One per answer please. I'll add my favourite as an answer.</p>

答:
The Structure and Interpretation of Computer Programs, aka SICP

When I saw that SICP was not listed yet, I grimaced in pain.  :)

Why: There's nothing more to add to Norvig's praising this book as the greatest introduction to computer science ever written.  Well OK, since the Why? was requested: SICP covers the fundamentals of software in a satisfyingly deep way, raising many perspectives and questions about the nature of computation — quite a few of which remain open issues — while leading the reader to see beyond the superficial aspects of telling the machine what to do, or how to do it.

alt text http://ecx.images-amazon.com/images/I/41CPGEDXMDL._SL500_AA300_.jpg

Click the image to get to the free text online.  You can also readily find the video lectures by the authors, complete with '80s style color and clothing no less.


答:
Pascal was specifically designed to teach programming.
It's easy to learn (it was one of the first programming languages I learned).</p>


问:
Is there a canonical book for learning Java as an experienced developer?
I have been a .NET developer now for about the past 5/6 years give or take. I have never done any professional Java development and the last time I really touched it was probably back in college. I have been toying with the Scala language a little bit but nothing serious. Recently, I've been offered an opportunity to do some pretty cool work, but using Java instead of .NET. I think I can get by alright with my current skill set, meaning I already know how to program well and am familiar with languages such as C# and C++, etc. So, the syntax and all that language stuff are really not a problem. What I need is a really good reference book and a book about how to think in Java. Each language/Framework/Stack tries to address things a certain way and I'm sure Java is no different.

What are some great Java books that you simply can't live without? Are there any books that talk about the most important parts of Java that must be understood before all else?

As a side note, I will be doing mostly Java web development. Not really 100% on what types of stuff they are using for persistence, framework, server, etc.

答:
Just like Uri's answer, go for official sun docs, and Effective Java to get deeper into the language.

Then go straight with play docs and books, like the play framework e-book play framework cookbook, here you have a sample chapter

it's no use you put yourself to study about the standard j2ee web development stack (you know, spring, struts, tomcat, jsf, etc) because play takes a very different approach to web development... if you go with hibernate as a persistence framework I would recommend to have a look at hibernate's docs


问:
The worst anti-patterns you have came across
What are the worst anti-patterns you have came across in your career as a programmer?

I'm mostly involved in java, although it is probably language-independent.

I think the worst of it is what I call the main anti-pattern. It means program consisting of single, extremely big class (sometimes accompanied with a pair of little classes) which contains all logic. Typically with a big loop in which all business logic is contained, sometimes having tens of thousands of lines of code.

答: A former co-worker had the habit of re-using objects by overwriting their properties, instead of simply creating new ones. I could never have imagined the amount of problems this has caused when implementing new features.</p>

OwnerDisplayName: стривігор


问:
A local/internal deployment of something like Campfire for developers
I've been looking at Campfire by 37Signals and it looks like a great tool for collaboration between developers but we need something that can be deployed internally. Any good options out there?</p>

答: Teambox appears to have similar features. You can test it on the hosted version, then head to the github project for the source code and installation instructions.</p>