问:
How should I test randomness?
Consider a method to randomly shuffle elements in an array. How would you write a simple yet robust unit test to make sure that this is working?

I've come up with two ideas, both of which have noticeable flaws:

Shuffle the array, then make sure its order differs from before. This sounds good, but fails if the shuffle happens to shuffle in the same order. (Improbable, but possible.)

Shuffle the array with a constant seed, and check it against the predetermined output. This relies on the random function always returning the same values given the same seed. However, this is sometimes an invalid assumption.

Consider a second function which simulates dice rolls and returns a random number. How would you test this function? How would you test that the function...

never returns a number outside the given bounds?

returns numbers in a valid distribution? (Uniform for one die, normal for large numbers of dice.)

I'm looking for answers offering insight into testing not only these examples but random elements of code in general. Are unit tests even the right solution here? If not, what sort of tests are?

Just to ease everyone's mind I'm not writing my own random number generator.

答: Well, you'll never be 100% certain, so the best you can do is that it's probable that the numbers are random.  Pick a probability -- say that a sample of numbers or items will come up x times given a million samples, within a margin of error.  Run the thing a million times, and see if it's within the margin.  Fortunately, computers make this sort of thing easy to do.</p>

Title: How should I test randomness?


答:
There are two parts to this: testing randomization and testing things that use randomization.

Testing randomization is relatively straightforward. You check that the period of the random number generator is as you expect it to be (for a few samples using a few kinda-random seeds, within some threshold) and that the distribution of the output over a large sample size is as you expect it to be (within some threshold).

Testing things that use randomization is best done with a deterministic psuedo-random number generator. Since the output of the randomization is known based on the seed (its inputs), then you can unit test as normal based on inputs vs expected outputs. If your RNG is not deterministic, then mock it with one that is deterministic (or simply not random). Test the randomization in isolation from the code that consumes it.

ContentLicense: CC BY-SA 3.0

Title: How should I test randomness?

Body:
Consider a method to randomly shuffle elements in an array. How would you write a simple yet robust unit test to make sure that this is working?

I've come up with two ideas, both of which have noticeable flaws:

Shuffle the array, then make sure its order differs from before. This sounds good, but fails if the shuffle happens to shuffle in the same order. (Improbable, but possible.)

Shuffle the array with a constant seed, and check it against the predetermined output. This relies on the random function always returning the same values given the same seed. However, this is sometimes an invalid assumption.

Consider a second function which simulates dice rolls and returns a random number. How would you test this function? How would you test that the function...

never returns a number outside the given bounds?

returns numbers in a valid distribution? (Uniform for one die, normal for large numbers of dice.)

I'm looking for answers offering insight into testing not only these examples but random elements of code in general. Are unit tests even the right solution here? If not, what sort of tests are?

Just to ease everyone's mind I'm not writing my own random number generator.


答:
1. Unit test your algorithm

For the first question I would build a fake class that you feed a sequence of random numbers for which you know the outcome of your algorithm. That way you make sure the algorithm you build on top of your random function works. So something along the lines of:

```<code>Random r = new RandomStub([1,3,5,3,1,2]);
r.random(); //returns 1
r.random(); //returns 3
...
</code>```

2. See if your random function makes sense

To the unit test you should add a test that runs multiple times and asserts that the results

are within the boundaries that you set (so, a dice roll is between 1 and 6) and

show a sensible distribution (do multiple test runs and see if the distribution is within x% of what you expected, e.g. for the dice roll you should see a 2 come up between 10% and 20% (1/6 = 16.67%) of the time given that you rolled it 1000 times).

3. Integration test for the algorithm and the random function

How often would you expect your array is sorted in the original sorting? Sort a couple hundred of times and assert that only x% of the time the sorting does not change.

This is actually already an integration test, you are testing the algorithm together with the random function. Once you are using the real random function you can't get away with single test runs anymore.

From experience (I wrote a genetic algorithm) I would say combining the unit test of your algorithm, the distribution test of your random function and the integration test is the way to go.

Title: How should I test randomness?

Body:
1. Unit test your algorithm

For the first question I would build a fake class that you feed a sequence of random numbers for which you know the outcome of your algorithm. That way you make sure the algorithm you build on top of your random function works. So something along the lines of:

Random r = new RandomStub([1,3,5,3,1,2]);
r.random(); //returns 1
r.random(); //returns 3
...

2. See if your random function makes sense

To the unit test you should add a test that runs multiple times and asserts that the results

are within the boundaries that you set (so, a dice roll is between 1 and 6) and

show a sensible distribution (do multiple test runs and see if the distribution is within x% of what you expected, e.g. for the dice roll you should see a 2 come up between 10% and 20% (1/6 = 16.67%) of the time given that you rolled it 1000 times).

3. Integration test for the algorithm and the random function

How often would you expect your array is sorted in the original sorting? Sort a couple hundred of times and assert that only x% of the time the sorting does not change.

This is actually already an integration test, you are testing the algorithm together with the random function. Once you are using the real random function you can't get away with single test runs anymore.

From experience (I wrote a genetic algorithm) I would say combining the unit test of your algorithm, the distribution test of your random function and the integration test is the way to go.


答:
An aspect of PRNGs that seems forgotten about is that all of its properties are statistical in nature: you can't expect that shuffling an array will result in a different permutation from the one you started with. Basically, if you are using a normal PRNG, the only thing you're guaranteed is that it doesn't use a simple pattern (hopefully) and that it has even distribution among the set of numbers it returns.

A proper test for a PRNG will involve running it at least 100 times and then checking the distribution of the output (which is a direct answer to the second part of the question).

An answer to the first question is almost the same: run the test about 100 times with {1, 2, ..., n} and count the number of times each element has been at each position. They should be all roughly equal if the shuffle method is any good.

An entirely different matter is how to test cryptography-grade PRNGs. This is a matter in which you probably shouldn't dwell, unless you really know what you are doing. People have been known to destroy (read: open catastrophic holes in) good cryptosystems with just a few 'optimizations' or trivial edits.

EDIT: I have thoroughly reread the question, the top answer and my own. While the points I make still stand, I would second Bill The Lizard's answer. Unit tests are Boolean in their nature - they either fail, or they succeed, and are therefore unsuited for testing "how good" are the properties of a PRNG (or a method using a PRNG), since any answer to this question would be quantitative, rather than polar.

Title: How should I test randomness?


答:
General pointers I've found useful when dealing with code that takes randomized input:
Check the edge cases of expected randomness (max and min values, and the max+1 and min-1 values if applicable).
Check places (on, above, and below) where numbers have inflection points (ie -1, 0, 1, or greater than 1, less than 1 and non-negative for cases where a fractional value might mess up the function).
Check a few places completely outside the allowed input.
Check a few typical cases.
You can also add a random input, but for a unit test that has the undesirable side effect that the same value isn't under test each time the test is run (a seed approach can work though, test the first 1,000 random numbers from seed S or somesuch).

For testing the output of a random function, it is important to identify the goal.  In the case of cards, is the goal to test the uniformity of the 0-1 random generator, to determine if all 52 cards appear in the result, or some other goal (maybe all of this list and more)?

In the specific example, you have to assume your random number generator is opaque (just like it doesn't make sense to unit test the OS syscall or malloc- unless you write OSes).  It may be useful to measure the random number generator, but your goal isn't to write a random generator, just to see that you get 52 cards each time, and that that they change order.

That's a long way of saying that there are really two test tasks here: testing that the RNG is producing the right distribution, and checking that your card shuffle code is using that RNG to produce randomized results.  If you are writing the RNG, use statistical analysis to prove your distribution, if you're writing the card shuffler, make sure there are 52 non-repeated cards in each output (it's a better case for test by inspection that you're using the RNG).

Title: How should I test randomness?


答:
You can rely on secure random number generators

I just had a horrible thought: you're not writing your own random number generator are you?

Assuming you're not, then you should test the code that you are responsible for, not other people's code (such as the SecureRandom implementation for your framework).

Testing your code

To test that your code responds correctly, it is normal to use a low visibility method to produce the random numbers so that it can be easily overridden by a unit test class. This overridden method effectively mocks out the random number generator and gives you complete control over what is produced and when. Consequently you can fully exercise your code which is the goal of unit testing.

Obviously you will check edge conditions and ensure that the shuffling takes place exactly as your algorithm dictates given the appropriate inputs.

Testing the secure random number generator

If you are uncertain that the secure random number generator for your language is not truly random or is buggy (provides out of range values etc), then you need to perform a detailed statistical analysis of the output over several hundred million iterations. Plot the frequency of occurrence of each number and it should show up with equal probability. If the results skew one way or another you should report your findings to the framework designers. They will definitely be interested in fixing the problem since secure random number generators are fundamental to many encryption algorithms.

Title: How should I test randomness?


答:
I don't think unit tests are the right tool for testing randomness.  A unit test should call a method and test the returned value (or object state) against an expected value.  The problem with testing randomness is that there isn't an expected value for most of the things you'd like to test.  You can test with a given seed, but that only tests repeatability.  It doesn't give you any way to measure how random the distribution is, or if it's even random at all.

Fortunately, there are a lot of statistical tests you can run, such as the Diehard Battery of Tests of Randomness.  See also:

How to unit test a pseudo random number generator?

Steve Jessop recommends that you find a tested implementation of the same RNG algorithm that you're using and compare its output with selected seeds against your own implementation.

Greg Hewgill recommends the ENT suite of statistical tests.

John D. Cook refers readers to his CodeProject article Simple Random Number Generation, which includes an implementation of the Kolmogorov-Smirnov test mentioned in Donald Knuth's volume 2, Seminumerical Algorithms.

Several people recommend testing that the distribution of the numbers generated is uniform, the Chi-squared test, and testing that the mean and standard deviation are within the expected range.  (Note that testing the distribution alone is not enough.  [1,2,3,4,5,6,7,8] is a uniform distribution, but it's certainly not random.)

Unit Testing with functions that return random results

Brian Genisio points out that mocking your RNG is one option for making your tests repeatable, and provides C# sample code.

Again, several more people point to using fixed seed values for repeatability and simple tests for uniform distribution, Chi-squared, etc.

Unit Testing Randomness is a wiki article that talks about many of the challenges already touched on when trying to test that which is, by its nature, not repeatable.  One interesting bit that I gleaned from it was the following:

I've seen winzip used as a tool to measure the randomness of a file of values before (obviously, the smaller it can compress the file the less random it is).

Title: How should I test randomness?

ContentLicense: CC BY-SA 4.0


问:
Unit testing: about easy- and hard-first strategies
I've never written a unit test.

I'm reading The art of Unit Testing by Osherove, and he explains a way to choose where to start when you're writing tests for legacy code. Basically you end up with two kinds of tests to write: easy (on components with few dependencies) and hard (on components with many dependencies).

Then he says that starting from the hard ones you have to be more experienced, but that it lets you refactor and make testable a wide part of the system, making later work much easier.

But isn't it true the way around too? I mean, if you start from easy tests, shouldn't you end up making hard tests easier?

答: The legacy components with many dependencies are going to be hard no matter how many of the easier components you do. The reason is simple, in order to test you have to break the hard-coded dependencies without breaking the dependent component. Typically, the component with a lot of dependencies is doing a lot of stuff and mixing those dependencies in ungodly ways. So the job of breaking out and testing those dependencies while maintaining the same behavior is that much tougher and won't be improved by your efforts on simpler components.</p>


问:
JAAS - What is the required control flag used for?
The Java Authentication and Authorization Service (JAAS) defines that if a login module has the flag "REQUIRED", the authentication should proceed down the login module list on success or failure, and that the module is required to succeed for the overall authentication process to succeed.

The question is: What could this flag be used for? Since the login module is required to succeed, why does the authentication process need to continue down the login module list when a REQUIRED module fails to authenticate a Subject?

答:
The Configuration doc has an example which explains one reason to use required over requisite:

```<code>Login {
com.sun.security.auth.module.UnixLoginModule required;
com.sun.security.auth.module.Krb5LoginModule optional
               useTicketCache="true"
               ticketCache="${user.home}${/}tickets";
};
</code>```

This Configuration specifies that an application named, "Login", requires users to first authenticate to the com.sun.security.auth.module.UnixLoginModule, which is required to succeed. Even if the UnixLoginModule authentication fails, the com.sun.security.auth.module.Krb5LoginModule still gets invoked. This helps hide the source of failure. Since the Krb5LoginModule is Optional, the overall authentication succeeds only if the UnixLoginModule (Required) succeeds.

As you're probably aware, using the requisite flag tells JAAS to immediately return control to the application.

Another reason it might be useful would be if a later LoginModule tracked login attempts, you would want to be sure that it was processed.

Body:
The Configuration doc has an example which explains one reason to use required over requisite:

Login {
com.sun.security.auth.module.UnixLoginModule required;
com.sun.security.auth.module.Krb5LoginModule optional
               useTicketCache="true"
               ticketCache="${user.home}${/}tickets";
};

This Configuration specifies that an application named, "Login", requires users to first authenticate to the com.sun.security.auth.module.UnixLoginModule, which is required to succeed. Even if the UnixLoginModule authentication fails, the com.sun.security.auth.module.Krb5LoginModule still gets invoked. This helps hide the source of failure. Since the Krb5LoginModule is Optional, the overall authentication succeeds only if the UnixLoginModule (Required) succeeds.

As you're probably aware, using the requisite flag tells JAAS to immediately return control to the application.

Another reason it might be useful would be if a later LoginModule tracked login attempts, you would want to be sure that it was processed.


问:
Does C# Cache Calculation Results?
I am recently building a basic ray tracer in C# from scratch, as a learning/teaching project. A previous release of the project (let's call it A) does reflections and diffuse shading. The program renders the scene at around 900ms. Now I've just made a release B which adds specular highlights. Naturally, I assumed rendering time would increase. Imagine my surprise when the same scene rendered in a speedy 120ms! The results are absolutely the same (since the objects in the scene don't actually have specular highlights).

Curious, I tried to narrow down what part of the code is actually making it faster. I think I've narrowed it down to a calculation that is made in both the reflection component, and the specular component (calculating the reflection vector). For each iteration of the ray tracing, both calculate the same vector (same inputs, same output), but there is no data sharing between the two. So I was wondering if C# is somehow caching the results which would account for the performance increase?

Here's the code for the reflection rendering

```<code>private Color TraceReflection(Ray ray, Vector3D normal, Vector3D hitPoint, IPrimitive hitObject, int Level)
    {
        //Calculate reflection direction
        var reflectionDir = (ray.Direction - (2 * (ray.Direction * normal) * normal)).Normalize();

        //Create reflection ray from just outside the intersection point, and trace it
        var reflectionRay = new Ray(hitPoint + reflectionDir * Globals.Epsilon, reflectionDir);

        //Get the color from the reflection
        var reflectionColor = RayTrace(reflectionRay, Level + 1);

        //Calculate final color
        var resultColor = reflectionColor * hitObject.PrimitiveMaterial.ReflectionCoeff;

        return resultColor;
    }
</code>```

And here's the specular highlight function:

```<code>public  Color GetColor(IPrimitive HitObject, ILight Light, Vector3D ViewDirection, Vector3D LightDirection, Vector3D Normal)
    {
        //Caulcate reflection vector
        var reflectionDirection = (LightDirection - (2 * LightDirection * Normal) * Normal).Normalize();

        var dot = reflectionDirection * ViewDirection; //if the dot product is zero or less that means the angle between the two vectors is 90 or more and no highlighting occurs.

        if (dot > 0)
        {
            var specularPower = HitObject.PrimitiveMaterial.SpecularCoeff * Math.Pow(dot, HitObject.PrimitiveMaterial.SpecularExponent);
            var highlightColor = HitObject.PrimitiveMaterial.DiffuseColor * specularPower;

            return highlightColor;
        }

        return new Color();
    }
</code>```

UPDATE

The previous numbers were when both programs were running in debug mode. I just switched them both to release, and the numbers are what I was expecting them to be in the first place (270ms without specular. 380ms with specular). So it seems the debug mode, somehow, is the culprit.

答: It's highly unlikely that C# added some tricks that would increase the speed by anything that great.  It's more likely that either 1) you improved your algorithm or 2) you had previously ran it in debug mode and not release mode.  It's very hard to look at this without seeing what the program was before and what it is now or seeing the performance analysis that was done on it.</p>

Title: Does C# Cache Calculation Results?


问:
When is unit testing inappropriate or unnecessary?
It seems to be generally assumed (on Stack Overflow at least) that there should always be unit tests, and they should be kept up to date. But I suspect the programmers making these assertions work on different kinds of projects from me - they work on high quality, long-lasting, shipped software where bugs are A Really Bad Thing.

If that's the end of the spectrum where unit testing is most valuable, then what's the other end? Where are unit tests least valuable? In what situations would you not bother? Where would the effort of maintaining tests not be worth the cost?

答: IMO unit tests are inappropriate (not unnecessary!) in any codebase where it would require tons of hours of refactoring or even an outright rewrite in order to introduce unit testing, because it would be a very hard sell to management to allow for that time allotment.</p>


问:
Should a git commit message mention the file that was modified?
In the first line of a git commit message I have a habit of mentioning the file that modified if a change doesn't span multiple files, for example:

```<code>Add [somefunc] to [somefile]
</code>```

Is this a good thing to do or is it unnecessary?

答:
If it's relevant information in the narrative of the commit message, then yes, include it.  If the only bit of information is the filename itself, then no.

For example this make sense: "Moved the build_foo() function from fooutil.c to foobase.c, since most programs that want to use build_foo() are already including foobase.c"

This one doesn't: "Updated the build_foo() in fooutil.c to take a bar parameter."

OwnerDisplayName: Matty


答:
AFAIK, C# does not do that, and neither does any of the other mainstream platforms and languages.

But there are tons of other possible explanations. You may have hit an edge case in the optimizer; or the extra code may cause more beneficial branch prediction behavior, more beneficial garbage collection, or a more beneficial distribution of cache misses.

The latter would be my first guess, but without actual profiling, there is no way to tell for sure.

Title: Does C# Cache Calculation Results?

Body:
I am recently building a basic ray tracer in C# from scratch, as a learning/teaching project. A previous release of the project (let's call it A) does reflections and diffuse shading. The program renders the scene at around 900ms. Now I've just made a release B which adds specular highlights. Naturally, I assumed rendering time would increase. Imagine my surprise when the same scene rendered in a speedy 120ms! The results are absolutely the same (since the objects in the scene don't actually have specular highlights).

Curious, I tried to narrow down what part of the code is actually making it faster. I think I've narrowed it down to a calculation that is made in both the reflection component, and the specular component (calculating the reflection vector). For each iteration of the ray tracing, both calculate the same vector (same inputs, same output), but there is no data sharing between the two. So I was wondering if C# is somehow caching the results which would account for the performance increase?

Here's the code for the reflection rendering

```<code>private Color TraceReflection(Ray ray, Vector3D normal, Vector3D hitPoint, IPrimitive hitObject, int Level)
    {
        //Calculate reflection direction
        var reflectionDir = (ray.Direction - (2 * (ray.Direction * normal) * normal)).Normalize();

        //Create reflection ray from just outside the intersection point, and trace it
        var reflectionRay = new Ray(hitPoint + reflectionDir * Globals.Epsilon, reflectionDir);

        //Get the color from the reflection
        var reflectionColor = RayTrace(reflectionRay, Level + 1);

        //Calculate final color
        var resultColor = reflectionColor * hitObject.PrimitiveMaterial.ReflectionCoeff;

        return resultColor;
    }
</code>```

And here's the specular highlight function:

```<code>public  Color GetColor(IPrimitive HitObject, ILight Light, Vector3D ViewDirection, Vector3D LightDirection, Vector3D Normal)
    {
        //Caulcate reflection vector
        var reflectionDirection = (LightDirection - (2 * LightDirection * Normal) * Normal).Normalize();

        var dot = reflectionDirection * ViewDirection; //if the dot product is zero or less that means the angle between the two vectors is 90 or more and no highlighting occurs.

        if (dot > 0)
        {
            var specularPower = HitObject.PrimitiveMaterial.SpecularCoeff * Math.Pow(dot, HitObject.PrimitiveMaterial.SpecularExponent);
            var highlightColor = HitObject.PrimitiveMaterial.DiffuseColor * specularPower;

            return highlightColor;
        }

        return new Color();
    }
</code>```

UPDATE

The previous numbers were when both programs were running in debug mode. I just switched them both to release, and the numbers are what I was expecting them to be in the first place (270ms without specular. 380ms with specular). So it seems the debug mode, somehow, is the culprit.


问:
HTML/CSS in Other Spoken languages?

Possible Duplicate:

  Do people in non-English-speaking countries code in English?

Do developers who don't natively speak English still code using english property and tag names? Like, would a Japanese front end web developer still need to know what border-radius means in English to use it, or would Japanese sites use Japanese CSS?

I ask because I'm an English speaking web developer who aspires to be multilingual someday, and I might try to use that combination of skills to travel the world a little. Will I still code in English, even while building sites in China or Japan? If so, would that improve my chances of getting a job?

答:
CSS properties and HTML entities are not localized.

A Japanese or Hebrew or any other language site would still use  and  elements in their HTML, and similarly in CSS.

Yes, they will need to understand what the characters border-radius end up meaning in terms of CSS and how they effect styling, even if they have no idea how to pronounce them or what their exact semantics are.

They will know that they need to use  for items that go into the HTML header, but they might not know and understand where the word head comes from and what it means in other contexts.

Title: HTML/CSS in Other Spoken languages?

Body:
CSS properties and HTML entities are not localized.

A Japanese or Hebrew or any other language site would still use <head> and <body> elements in their HTML, and similarly in CSS.

Yes, they will need to understand what the characters border-radius end up meaning in terms of CSS and how they effect styling, even if they have no idea how to pronounce them or what their exact semantics are.

They will know that they need to use <head> for items that go into the HTML header, but they might not know and understand where the word head comes from and what it means in other contexts.


问:
Is it a responsibility of the software developer to understand what the customer meant with his request?
Kind of a yes / no question and why?

Is it the responsibility of the software developer to understand what the customer meant with his/her request or is it the responsibility of the customer to properly explain his/her request to the developer?

The situation at work is currently "the customer already explained us, what he wants. It's your responsibility to understand the request, not ask more questions".

While English is not my strong suite, all the requests are written in obscure English with misplaced words and hard to understand sentences, some requests assume previous understanding of the system on my part.

I'm the 3rd or 4th developer of the system (the last developers quit the job) and that might be the reason the customer expects some understanding on the developers side.

The system itself is quite messy both in the UI and source code level. This looks like monkey coding to me - code and hope you get the request right, while not actually understanding the request.

I'm actually thinking about quitting the job, but haven't yet, given I'm not sure about who's right and who's wrong.

答:
This is based on some new information in comments on the original question.

The statement that

the customer already explained us, what he wants. It's your
  responsibility to understand the request, not ask more questions

comes from the project leader; the stated rationale is

that since I'm not the first developer on the system we shouldn't
  bother the client's representitive with more questions, but try to and
  if necessary, spend extra time interpreting the question

So what you're specifically being told to avoid is bothering the customer with questions.

Asking you to "spend extra time interpreting the question" isn't necessarily unreasonable. You should make a reasonable effort, or perhaps even a slightly unreasonable effort, to figure out what the requirements are based on what the customer has actually said. If nothing else, that's a valuable skill.

If that fails (and it sounds like it already has, for various reasons), then ask your project leader for help. Try to be as specific as possible in your questions, showing that you've done your homework. For example, rather than

what do these people want???"

ask something like,

In paragraph 17 of the requirements document, it says that the foobar must frizzle the frozzle; which of these three frozzles does that refer to?"

Or, if the requirements are really so badly written that you can't decipher them, tell him that.

I'd say that it's ultimately the project leader's responsibility to make sure that the requirements are understood correctly (it's certainly in his best interest for the project to succeed). But as a member of the team, you share some of that responsibility. If you show that you've made some effort yourself, and the project leader refuses to help you, then he's made it entirely your responsibility. If it gets to that point, make sure he knows that.


答: It's entirely possible that, in debug mode, the compiler is much more relaxed about when and where it optimizes code - so that your non-specular implementation is compiled as a significantly less optimized executable (since it's not doing that badly), while the specular implementation hits a threshold and is bumped to a slower but more optimized compilation mode.</p>

Title: Does C# Cache Calculation Results?


答:
The amount and quality of unit testing to be done in a project is directly proportional to the pace of development and the required stability of the product.

At one end, for a one-off script, trivial demo, or in a quick-paced-startup environment during the very early stages, it's unlikely unit tests will matter or be useful for anything whatsoever. They are almost always, almost certainly, a waste of time and resources.

At the other end, when writing software to control pace makers, or pilot rocket-ships, or when working at maintaining stable, highly complex, software systems (say, a compiler with heavy adoption across the multiverse) multiple layers of unit test, and other coverage, are crucial.

[There are loads of other situation specific factors which each contribute one way or the other, such as the size of your team, your budget, the talent of your developers, your preferred software dev strategy, etc... Generally, and at the highest level of abstraction, I find these two make the largest difference]

Title: When is unit testing inappropriate or unnecessary?

Body:
It seems to be generally assumed (on Stack Overflow at least) that there should always be unit tests, and they should be kept up to date. But I suspect the programmers making these assertions work on different kinds of projects from me - they work on high quality, long-lasting, shipped software where bugs are A Really Bad Thing.

If that's the end of the spectrum where unit testing is most valuable, then what's the other end? Where are unit tests least valuable? In what situations would you not bother? Where would the effort of maintaining tests not be worth the cost?


问:
Class Design -- Multiple Calls from One Method or One Call from Multiple Methods?
I've been working on some code recently that interfaces with a CMS we use and it's presented me with a question on class design that I think is applicable in a number of situations.  Essentially, what I am doing is extracting information from the CMS and transforming this information into objects that I can use programatically for other purposes.  This consists of two steps:

Retrieve the data from the CMS (we have a DAL that I use, so this is essentially just specifying what data from the CMS I want--no connection logic or anything like that)

Map the parsed data to my own [C#] objects

There are basically two ways I can approach this:

One call from multiple methods

```<code>public void MainMethodWhereIDoStuff()
{
    IEnumerable<MyObject> myObjects = GetMyObjects();
    // Do other stuff with myObjects
}

private static IEnumerable<MyObject> GetMyObjects()
{
    IEnumerable<CmsDataItem> cmsDataItems = GetCmsDataItems();
    List<MyObject> mappedObjects = new List<MyObject>();
    // do stuff to map the CmsDataItems to MyObjects
    return mappedObjects;
}

private static IEnumerable<CmsDataItem> GetCmsDataItems()
{
    List<CmsDataItem> cmsDataItems = new List<CmsDataItem>();
    // do stuff to get the CmsDataItems I want
    return cmsDataItems;
}
</code>```

Multiple calls from one method

```<code>public void MainMethodWhereIDoStuff()
{
    IEnumerable<CmsDataItem> cmsDataItems = GetCmsDataItems();
    IEnumerable<MyObject> myObjects = GetMyObjects(cmsDataItems);
    // do stuff with myObjects
}

private static IEnumerable<MyObject> GetMyObjects(IEnumerable<CmsDataItem> itemsToMap)
{
    // ...
}

private static IEnumerable<CmsDataItem> GetCmsDataItems()
{
    // ...
}
</code>```

I am tempted to say that the latter is better than the former, as GetMyObjects does not depend on GetCmsDataItems, and it is explicit in the calling method the steps that are executed to retrieve the objects (I'm concerned that the first approach is kind of an object-oriented version of spaghetti code).

On the other hand, the two helper methods are never going to be used outside of the class, so I'm not sure if it really matters whether one depends on the other.  Furthermore, I like the fact that in the first approach the objects can be retrieved from one line-- most likely anyone working with the main method doesn't care how the objects are retrieved, they just need to retrieve the objects, and the "daisy chained" helper methods hide the exact steps needed to retrieve them (in practice, I actually have a few more methods but am still able to retrieve the object collection I want in one line).

Is one of these methods right and the other wrong? Or is it simply a matter of preference or context dependent?

答:
I think you should look it in more of a maintainability and code-correctness point of view.

For example, in the first case getMyObjects and getCMSObjects are coupled so that the only objects that getMyObjects will ever be able to map are the objects freshly returned from getCmsObjects, while on the second example the method operates on whatever argument it receives.

If your implementation of getMyObjects is flexible enough to allow for any list of objects as input, the you should err for the second example, since it is more flexible and doesn't cost very much. However, if the logic in getMyObjects only works on a list of freshly returned cms objects, putting a parameter will only serve as a place to let you introduce errors (by passing the wrong parameter) so you should prefer the parameter-less version instead.


问:
switch statement - handling default case when it can't be reached
If I'm using a switch statement to handle values from an enum (which is owned by my class) and I have a case for each possible value - is it worth adding code to handle the "default" case?

```<code>enum MyEnum
{
    MyFoo,
    MyBar,
    MyBat
}

MyEnum myEnum = GetMyEnum();
switch (myEnum)
{
    case MyFoo:
        DoFoo();
        break;
    case MyBar:
        DoBar();
        break;
    case MyBat:
        DoBat();
        break;
    default:
        Log("Unexpected value");
        throw new ArgumentException()
}
</code>```

I don't think it is because this code can never be reached (even with unit tests).
My co-worker disagrees and thinks this protects us against unexpected behavior caused by new values being added to MyEnum.

What say you, community?

答:
I was just talking with a co-worker about this this morning as well -- it's really unfortunate, but I think handling the default is required for safety, for two reasons:

First, as your co-worker mentions, it future-proofs the code against new values being added to the enum. This may or may not seem like a possibility, but it's always there.

More importantly, depending on the language/compiler, it may be possible to have values that aren't members of the enum in your switched variable. For example, in C#:

```<code>MyEnum myEnum = (MyEnum) 3; // This could come from anywhere, maybe parsed from text?
// ... code goes on for a while

switch ( myEnum )
{
    case MyEnum.A:
        // ... handle A case
        break;
    case MyEnum.B:
        // ... handle B case
        break;
}

// ... code that expects either A or B to have happened
</code>```

By adding the simple case default: and throwing an exception, you've protected yourself against this weird case where "nothing" happens but "something" should have happened.

Unfortunately, basically any time I write a switch statement anymore, it's because I'm checking the cases of an enum. I really wish the "throw by default" behavior could be enforced by the language itself (at least by adding a keyword).

Body:
I was just talking with a co-worker about this this morning as well -- it's really unfortunate, but I think handling the default is required for safety, for two reasons:

First, as your co-worker mentions, it future-proofs the code against new values being added to the enum. This may or may not seem like a possibility, but it's always there.

More importantly, depending on the language/compiler, it may be possible to have values that aren't members of the enum in your switched variable. For example, in C#:

MyEnum myEnum = (MyEnum) 3; // This could come from anywhere, maybe parsed from text?
// ... code goes on for a while

switch ( myEnum )
{
    case MyEnum.A:
        // ... handle A case
        break;
    case MyEnum.B:
        // ... handle B case
        break;
}

// ... code that expects either A or B to have happened

By adding the simple case default: and throwing an exception, you've protected yourself against this weird case where "nothing" happens but "something" should have happened.

Unfortunately, basically any time I write a switch statement anymore, it's because I'm checking the cases of an enum. I really wish the "throw by default" behavior could be enforced by the language itself (at least by adding a keyword).


问:
The modern way to perform error handling...
I've been pondering this problem for a while now and find myself continually finding caveats and contradictions, so I'm hoping someone can produce a conclusion to the following:

Favour exceptions over error codes

As far as I'm aware, from working in the industry for four years, reading books and blogs, etc. the current best practice for handling errors is to throw exceptions, rather than returning error codes (not necessarily an error code, but a type representing an error).

But - to me this seems to contradict...

Coding to interfaces, not implementations

We code to interfaces or abstractions to reduce coupling. We don't know, or want to know, the specific type and implementation of an interface. So how can we possibly know what exceptions we should be looking to catch? The implementation could throw 10 different exceptions, or it could throw none. When we catch an exception surely we're making assumptions about the implementation?

Unless - the interface has...

Exception specifications

Some languages allow developers to state that certain methods throw certain exceptions (Java for example, uses the throws keyword.) From the calling code's point of view this seems fine - we know explicitly which exceptions we might need to catch.

But - this seems to suggest a...

Leaky abstraction

Why should an interface specify which exceptions can be thrown? What if the implementation doesn't need to throw an exception, or needs to throw other exceptions? There's no way, at an interface level, to know which exceptions an implementation may want to throw.

So...

To conclude

Why are exceptions preferred when they seem (in my eyes) to contradict software best practices? And, if error codes are so bad (and I don't need to be sold on the vices of error codes), is there another alternative? What is the current (or soon to be) state of the art for error handling that meets the requirements of best practices as outlined above, but doesn't rely on calling code checking the return value of error codes?

答:
Favour exceptions over error codes

Both should coexist.

Return error code when you anticipate certain behaviour.

Return exception when you did not anticipate some behaviour.

Error codes are normally associated with a single message, when exception type remains, but a message may vary

Exception has a stack trace, when error code doesn't. I don't use error codes to debug broken system.

Coding to interfaces not implementations

This might be specific to JAVA, but when I declare my interfaces I do not specify what exceptions might be thrown by an implementation of that interface, it just doesn't make sense.

When we catch an exception surely we're making assumptions about the
  implementation?

This is entirely up to you. You may try and catch a very specific type of exception and then catch a more general Exception. Why not let exception propagate up the stack and then handle it? Alternatively you can look at aspect programming where exception handling becomes a "pluggable" aspect.

What if the implementation doesn't need to throw an exception, or
  needs to throw other exceptions?

I don't understand why is it a problem for you. Yes, you may have one implementation that never fails or throws exceptions and you may have a different implementation that constantly fails and throws exception. If that's the case, then don't specify any exceptions on the interface and your problem is solved.

Would it change anything if instead of exception your implementation returned a result object? This object would contain outcome of your action along with any errors/failures if any. You can then interrogate that object.


问:
Exclusive use of a Jini server during long-running call
I'm trying to use Jini, in a "Masters/Workers" arrangement, but the Worker jobs may be long running. In addition, each worker needs to have exclusive access to a singleton resource on that machine.

As it stands, if a Worker receives another request while a previous request is running, then the new request is accepted and executed in a second thread.

Are there any best-practices to ensure that a Worker accepts no further jobs until the current job is complete?

Things I've considered:

synchronize the job on the server, with a lock on the singleton resource. This would work, but is far from ideal. A call from a Master would block until the current Worker thread completes, even if other Workers become free in the meantime

unregister the Worker from the registry while the job is running, then re-register when it completes. Might work OK, but something doesn't smell right with this idea...

Of course, I'm quite happy to be told that there are more appropriate technologies than Jini... but I wouldn't want anything too heavyweight, like rolling out EJB containers all over the place.

答:
To answer my own question, and probably earn myself a "breaking Stack Exchange etiquette" badge...:

A service can unexport itself from the registry to prevent it being requested again.

See:

```<code>Exporter.unexport(bool)
</code>```

In this instance, I need to pass "true" so the unexport happens immediately - otherwise it'll wait until the current call completes, defeating the object of this exercise. I'll probably synchronize access to the whole server object too, in a half-arsed attempt to prevent a "two calls happen at the same time" race.

OwnerDisplayName: Matthew Flint

Body:
To answer my own question, and probably earn myself a "breaking Stack Exchange etiquette" badge...:

A service can unexport itself from the registry to prevent it being requested again.

See:

Exporter.unexport(bool)

In this instance, I need to pass "true" so the unexport happens immediately - otherwise it'll wait until the current call completes, defeating the object of this exercise. I'll probably synchronize access to the whole server object too, in a half-arsed attempt to prevent a "two calls happen at the same time" race.


问:
What to charge for a ready-built piece of software?
Recently I was contacted by someone interested buying a piece of software that I wrote to automate a process. The 'client' knows little about the program, except what it outputs and how easy it is to use. They are now interested in purchasing it, and I need to give a reasonable price.

I've never done anything like this before, so as you might be able to guess, I do not know where to start with a price. I spent a good 12 hours+ working on the program itself. The client will probably want some changes also.

My question: How can I work out what to charge for a piece of software that I built in my own time?

答:
My employer pays me X per hour. My employer charges clients at X * 4 per hour.

I charge for my freelance work at (X * 4) * 1.2 where 1.2 represents my free time.

This of course varies with experience, education, reputation and your business relationships.


答: Don't forget you're not just charging for your time, you're charging for what your client will save in time by using your software. If you're trying to figure out what to charge based on how much time you've put into it, you may be heading down the wrong path!</p>

Title: What to charge for a ready-built piece of software?

Body:
Recently I was contacted by someone interested buying a piece of software that I wrote to automate a process. The 'client' knows little about the program, except what it outputs and how easy it is to use. They are now interested in purchasing it, and I need to give a reasonable price.

I've never done anything like this before, so as you might be able to guess, I do not know where to start with a price. I spent a good 12 hours+ working on the program itself. The client will probably want some changes also.

My question: How can I work out what to charge for a piece of software that I built in my own time?


答:
It'll be practically impossible give you the "right answer" until you rename your methods and give them a better semantic meaning rather than just "DoStuff".

Only then we will be able to to identify responsibilities and separate them respectively.

Title: Class Design -- Multiple Calls from One Method or One Call from Multiple Methods?

Body:
I've been working on some code recently that interfaces with a CMS we use and it's presented me with a question on class design that I think is applicable in a number of situations.  Essentially, what I am doing is extracting information from the CMS and transforming this information into objects that I can use programatically for other purposes.  This consists of two steps:

Retrieve the data from the CMS (we have a DAL that I use, so this is essentially just specifying what data from the CMS I want--no connection logic or anything like that)

Map the parsed data to my own [C#] objects

There are basically two ways I can approach this:

One call from multiple methods

```<code>public void MainMethodWhereIDoStuff()
{
    IEnumerable<MyObject> myObjects = GetMyObjects();
    // Do other stuff with myObjects
}

private static IEnumerable<MyObject> GetMyObjects()
{
    IEnumerable<CmsDataItem> cmsDataItems = GetCmsDataItems();
    List<MyObject> mappedObjects = new List<MyObject>();
    // do stuff to map the CmsDataItems to MyObjects
    return mappedObjects;
}

private static IEnumerable<CmsDataItem> GetCmsDataItems()
{
    List<CmsDataItem> cmsDataItems = new List<CmsDataItem>();
    // do stuff to get the CmsDataItems I want
    return cmsDataItems;
}
</code>```

Multiple calls from one method

```<code>public void MainMethodWhereIDoStuff()
{
    IEnumerable<CmsDataItem> cmsDataItems = GetCmsDataItems();
    IEnumerable<MyObject> myObjects = GetMyObjects(cmsDataItems);
    // do stuff with myObjects
}

private static IEnumerable<MyObject> GetMyObjects(IEnumerable<CmsDataItem> itemsToMap)
{
    // ...
}

private static IEnumerable<CmsDataItem> GetCmsDataItems()
{
    // ...
}
</code>```

I am tempted to say that the latter is better than the former, as GetMyObjects does not depend on GetCmsDataItems, and it is explicit in the calling method the steps that are executed to retrieve the objects (I'm concerned that the first approach is kind of an object-oriented version of spaghetti code).

On the other hand, the two helper methods are never going to be used outside of the class, so I'm not sure if it really matters whether one depends on the other.  Furthermore, I like the fact that in the first approach the objects can be retrieved from one line-- most likely anyone working with the main method doesn't care how the objects are retrieved, they just need to retrieve the objects, and the "daisy chained" helper methods hide the exact steps needed to retrieve them (in practice, I actually have a few more methods but am still able to retrieve the object collection I want in one line).

Is one of these methods right and the other wrong? Or is it simply a matter of preference or context dependent?


答:
Since it's a finished product, the 12 hours you spent to create it are irrelevant to the pricing. It's in your interest to keep the client in the dark that it took you a mere 12 hours to make. The only thing that is relevant is how bad the client wants it, and if there are any alternatives they have to get something similar.

Err on the side of pricing high so if they try to negotiate it down, you won't be sold too short. If they go for the high price, then good for you.

If you give specifics of exactly what you made I can give you a guesstimate in US dollars.


答:
To test that a source of random numbers is generating something that at least has the appearance of randomness, I would have the test generate a fairly large sequence of bytes, write them to a temporary file, and then shell out to Fourmilab's ent tool.  Give ent the -t (terse) switch so it will generate easy-to-parse CSV.  Then check the various numbers to see that they are "good."

To decide what numbers are good, use a known source of randomness to calibrate your test.  The test should almost always pass when given a good set of random numbers.  Because even a truly random sequence has a probability of generating a sequence that appears to be non-random, you can't get a test that is certain to pass.  You just pick thresholds that make it unlikely that a random sequence will cause a test failure.  Isn't randomness fun?

Note: You cannot write a test that shows that a PRNG generates a "random" sequence.  You can only write a test that, if it passes, indicates some probability that the sequence generated by the PRNG is "random."  Welcome to the joy of randomness!

Title: How should I test randomness?


问:
Do privacy concerns prevent us from accessing location-based user data?
Every time my team begins to explore the scenarios that are possible with mobile device location data, location data that is part of user data, or even location data that may be retrieved or inferred from IP address or browser cookies, we are stopped dead in our tracks by the risk of violating a user's privacy. It's frustrating, because working with location data creates whole new areas for providing a great user experience.

I have taken a look at the Mobile Device Privacy Act, related online opinions, such as the ars technica article, and the Electronic Frontier Foundation's recent Mobile User Privacy Bill of Rights, but there isn't really an authoritative (or even de facto) standard and opinions differ.

Is it as simple as obtaining a user's permission to make use of location-based data and then safeguarding the data? I would like to know how others are addressing or even skirting this issue. Do you obtain user permission before utilizing location data? Are you just riding it out for now and waiting to see if a national law is passed?

答: I'd say make the product that makes the most sense.  If the users like your product, they won't mind giving up a bit of privacy.  (Ask their permission if the is a common way to so do, otherwise don't worry about it.)</p>


答:
Some loosely connected advice for best practices (IMHO anyway):

1. Ask for permission

Put the fact that you are collecting positioning data in the ToS, but ask for permission nevertheless when it comes to collecting them. Of course, put "Always remember" to not annoy your users.

2. Process the data locally

This applies in some contexts, e.g. an app containing routes you've taken along with stats. There is no point in uploading this data, unless you want to provide sync service.

3. Transfer the data encrypted

In case local processing is not an option, always use an encrypted protocol to transfer the data to your servers.

4. Forget the user

Once you have finished the processing, resist the temptation to store the user location. Moreover if your site gets cracked and someone gets a hold of this info, you're in big trouble and a class action is surely on the way (IANAL, of course, but just ask Sony about PSN).

5. Allow the user to delete his info

There are proposed laws in the EU that would force you to do so - Right to be forgotten, and it will also make your users happier. Forcing lock-in is something nobody likes.

6. Hash personally identifiable information

If you have to store the user location, store it along with a hashed version of his e-mail/username. Then, even if your service is hacked, the attacker will not gain direct knowledge of user/location pairs. This is what saved Valve from serious trouble some time ago.

7. Use lower accuracy data than available

This one is also very useful: you often do not need GPS-accuracy for the data you collect. For most statistical purposes, you can simply go with a city name or even just the country.

Note that I am not a lawyer and these are just suggestions, but I believe if you design your app in this manner, you will reduce risks of lawsuits to a minimum. The general rule is IMHO handle user data like a double-edged sword: it may help you, but in other hands, it's a weapon against you.

Title: Do privacy concerns prevent us from accessing location-based user data?

Body:
Every time my team begins to explore the scenarios that are possible with mobile device location data, location data that is part of user data, or even location data that may be retrieved or inferred from IP address or browser cookies, we are stopped dead in our tracks by the risk of violating a user's privacy. It's frustrating, because working with location data creates whole new areas for providing a great user experience.

I have taken a look at the Mobile Device Privacy Act, related online opinions, such as the ars technica article, and the Electronic Frontier Foundation's recent Mobile User Privacy Bill of Rights, but there isn't really an authoritative (or even de facto) standard and opinions differ.

Is it as simple as obtaining a user's permission to make use of location-based data and then safeguarding the data? I would like to know how others are addressing or even skirting this issue. Do you obtain user permission before utilizing location data? Are you just riding it out for now and waiting to see if a national law is passed?


答:
Leaky abstraction

Why should an interface specify which exceptions can
  be thrown? What if the implementation doesn't need to throw an
  exception, or needs to throw other exceptions? There's no way, at an
  interface level, to know which exceptions an implementation may want
  to throw.

In my experience, the code that receives the error (be it via exception, error code or anything else) would not normally care for the exact cause of the error - it would react the same way to any failure, except for possible reporting of the error (be it an error dialog or some kind of log); and this reporting would be done orthogonally to the code that called the failing procedure. For example, this code could pass the error to some other piece of code that knows how to report specific errors (e.g. format a message string), possibly attaching some context information.

Of course, in some cases it is needed to attach specific semantics to errors and react differently based on which error occured. Such cases should be documented in the interface specification. However, the interface may still reserve the right to throw other exceptions with no specific meaning.

Title: The modern way to perform error handling...

Body:
I've been pondering this problem for a while now and find myself continually finding caveats and contradictions, so I'm hoping someone can produce a conclusion to the following:

Favour exceptions over error codes

As far as I'm aware, from working in the industry for four years, reading books and blogs, etc. the current best practice for handling errors is to throw exceptions, rather than returning error codes (not necessarily an error code, but a type representing an error).

But - to me this seems to contradict...

Coding to interfaces, not implementations

We code to interfaces or abstractions to reduce coupling. We don't know, or want to know, the specific type and implementation of an interface. So how can we possibly know what exceptions we should be looking to catch? The implementation could throw 10 different exceptions, or it could throw none. When we catch an exception surely we're making assumptions about the implementation?

Unless - the interface has...

Exception specifications

Some languages allow developers to state that certain methods throw certain exceptions (Java for example, uses the throws keyword.) From the calling code's point of view this seems fine - we know explicitly which exceptions we might need to catch.

But - this seems to suggest a...

Leaky abstraction

Why should an interface specify which exceptions can be thrown? What if the implementation doesn't need to throw an exception, or needs to throw other exceptions? There's no way, at an interface level, to know which exceptions an implementation may want to throw.

So...

To conclude

Why are exceptions preferred when they seem (in my eyes) to contradict software best practices? And, if error codes are so bad (and I don't need to be sold on the vices of error codes), is there another alternative? What is the current (or soon to be) state of the art for error handling that meets the requirements of best practices as outlined above, but doesn't rely on calling code checking the return value of error codes?


答:
If you had any idea how mach time can be saved by insisting on the default case, you would not need to ask the question. Silently doing nothing in an error condition is not acceptable- do you silently catch exceptions that should never happen? Leaving "mines" for programmers that follow you, similarly unacceptable.

If your code is never going to be changed or modified, and is 100% bug free, leaving out the default case may be OK.

Ada (the grandfather of robust programming languages) won't compile a switch on an enum, unless all the enums are covered or there is a default handler - this feature is on my wish list for every language. Our Ada coding standard states that with switches on enums, explicit handling of all values, with no default is the preferred way to handle this situation.

Title: switch statement - handling default case when it can't be reached

Body:
If I'm using a switch statement to handle values from an enum (which is owned by my class) and I have a case for each possible value - is it worth adding code to handle the "default" case?

```<code>enum MyEnum
{
    MyFoo,
    MyBar,
    MyBat
}

MyEnum myEnum = GetMyEnum();
switch (myEnum)
{
    case MyFoo:
        DoFoo();
        break;
    case MyBar:
        DoBar();
        break;
    case MyBat:
        DoBat();
        break;
    default:
        Log("Unexpected value");
        throw new ArgumentException()
}
</code>```

I don't think it is because this code can never be reached (even with unit tests).
My co-worker disagrees and thinks this protects us against unexpected behavior caused by new values being added to MyEnum.

What say you, community?


答:
You need to know two things to set a price.
a)Cost plus - what it will cost you plus a margin. Note: as you have already written the software, that cost is $0 - you need to look at costs directly associated with the sale.

b) Value Add - what is it worth to the client. How much will he pay for it and be happy with the purchase.

If a) is more than b), don't do business.
If a) is less than b) - negotiate.

For your software and situation, I can't help with b), but with a) maybe some insight:

I expect from the post that the software was written by you, for you, for a specific job. If so, the cost to sell it to one person is a *5 - *10 multiplier (A magic number taught to me at the school of life) - if it took 10 hours, it will need another 40 - 100 to make it usable for the customer.

Then there is the cost of sales, post sales and post sales support. You cost of sales is low (he phoned you). Post sales support is not technical support - it's the stuff you to keeping in happy, discussing the next new feature of bug fix etc. It is not the fixing or improving his software. Then there's the cost associated with supporting the software when he wants changes.

All the above need to be worked out before you can set a price.

The other way is to give it to him, you won't make any money, but you won't loose any either.


答:
Case 1: Testing a shuffle:

Consider an Array [0, 1, 2, 3, 4, 5], shuffle it, what can go wrong? The usual stuff: a) no shuffle at all, b) shuffling 1-5 but not 0, shuffling 0-4 but not 5, shuffling, and always generating the same pattern, ...

One test to catch them all:

Shuffle 100 times, add the values in each slot. The sum of each slot should be similar to each other slot. Avg/Stddev can be calculated. (5+0)/2=2.5, 100*2.5 = 25. Expected value is around 25, for example.

If the values are out of range, there is a small chance, that you got a false negative. You can calculate, how big that chance is. Repeat the test. Well - of course there is a small chance, that the test fails 2 times in a row. But you don't have a routine which automatically deletes your source, if the unit-test fails, do you? Run it again!

It can fail 3 times in a row? Maybe you should try your luck at the lottery.

Case 2: Roll a dice

The dice-roll question is the same question. Throw the dice 6000 times.

```<code>for (i in 0 to 6000)
    ++slot [Random.nextInt (6)];
return (slot.max - slot.min) < threshold;
</code>```

Title: How should I test randomness?

Body:
Case 1: Testing a shuffle:

Consider an Array [0, 1, 2, 3, 4, 5], shuffle it, what can go wrong? The usual stuff: a) no shuffle at all, b) shuffling 1-5 but not 0, shuffling 0-4 but not 5, shuffling, and always generating the same pattern, ...

One test to catch them all:

Shuffle 100 times, add the values in each slot. The sum of each slot should be similar to each other slot. Avg/Stddev can be calculated. (5+0)/2=2.5, 100*2.5 = 25. Expected value is around 25, for example.

If the values are out of range, there is a small chance, that you got a false negative. You can calculate, how big that chance is. Repeat the test. Well - of course there is a small chance, that the test fails 2 times in a row. But you don't have a routine which automatically deletes your source, if the unit-test fails, do you? Run it again!

It can fail 3 times in a row? Maybe you should try your luck at the lottery.

Case 2: Roll a dice

The dice-roll question is the same question. Throw the dice 6000 times.

for (i in 0 to 6000)
    ++slot [Random.nextInt (6)];
return (slot.max - slot.min) < threshold;


问:
Looking for good testing in multithreaded C or C++ open source projects
I have read a lot about the importance of unit testing, and testing in general.  In particular I have read about TDD which, in theory, seems like a good way to ensure effective test coverage for a project.

However, when I look at open source projects, or code that is available as open source, I am having difficulty finding good examples of testing in real projects that I can learn from.  In particular I haven't seen much in the way of unit testing (at least not that I can understand).

For example I just downloaded the source code for the Java HotSpot JVM.  I thought it would be very useful for me to look at and learn from because a JVM (written in C or C++) will have to deal with many complex issues associated with multithreading and low-level system interaction.  Which are the very same things that I'm having difficulty in figuring out how to develop unit tests for.  But unfortunately it seems like the amount of code written specifically for testing is quite limited.  There is a test directory but it looks like it contains examples of code that can be used to test various different bugs, rather than any formal regression tests or unit tests.

So my question is are there examples of open source projects that use unit testing that I could look at to learn from?  Something like a JVM is perfect for me because it is more complex than the project that I am working on, but would face many of the same issues associated with thread interaction and memory management.

答:
Look at boost.

Boost generally does not accept libraries for submission without complete unit tests. Boost even has a unit test framework of it's own.


问:
When should I use parallelism?
After asking this question, I got to realize that parallelism may not always be good.

So far I can see that parallelism (under c#) is

A little complicated code-wise

Will probably insert some concurrency complications

Will not always be faster

I am looking inside parallelism because I want to make existing and new applications work faster, but now I see that it is no silver bullet.

When should I use it? are there any best practices?
Is it just a waste of time in most cases?
Is it suitable for a specific kind of applications?

I am looking forward for your insights on this matter.

答:
Parallelism is a very important tool to have in your belt but to learn it well you must use it a lot until you get the hang of it. You're lucky to be using C# because TPL is the greatest library I've ever seen and combined with LINQ and method extensions it's just killer.

Answering your questions specifically.

When should I use it?

There are basically two reasons you might want to use TPL:

Background processing: you want to make sure that your application is still responsive while doing an operation that might take a while. You must study and understand how to make calls asynchronously.

Parallel processing: you want to make sure several threads are being used to execute your tasks in parallel making your code run faster (which works better on multi-core systems).

TPL will help you greatly in both scenarios (C# 5.0 has some new special tricks that turns asynchronous programming into kid's stuff).

Are there any best practices?

Yes there are. For Windows Forms for example you could use BackgroundWorker because it helps you deal with the fact that no call can be made to UI objects outside of their own threads.

There are many other but they will vary depending on what exactly you're doing (ASP.NET, WPF, Silverlight, WinForms and so on). Most of the time I use MSDN and StackOverflow but the fact is the more  you use TPL in general the more you'll gain knowledge and the easier it gets to use it and to know when parallelism is an adequate solution or when it's not.

Is it just a waste of time in most cases? Is it suitable for a specific kind of applications?

There's no universal answer to this question, every project has to be put in perspective and analyzed. There are certainly specific types of applications that are more suitable to parallelism. In parallel processing for example:

games

number crunching applications

image and video processing

data processing

In background processing any kind of application that has a UI and manages tasks that take more than a couple seconds. You can find excellent articles about C# 5.0 async in here:

Link

Mobile applications are bringing the attention back to this subject because mobile platforms simply don't have the same level of processing power than desktops and usually users have very short patience when running an app. See this article for example about how background processing can create the impression your application is lightning fast:

http://speakerdeck.com/u/mikeyk/p/secrets-to-lightning-fast-mobile-design?slide=82

If you want to learn, nothing beats trying it over and over until you see the results for yourself (good or bad).

Title: When should I use parallelism?


问:
Good resource for getting up to speed on windows forms development
I'm a .NET developer comfortable with C# and web application development.  I need to improve my knowledge of Winforms.  What is a good book or online resource that particularly covers the Winforms life cycle.  Which events to use for what?  How does OnLoad compare to Form_load etc.</p>

答:
I learned WinForm by myself without reading any book so basically I used a lot of web sites as source of information.

I'd suggest the following:

MSDN: http://msdn.microsoft.com

This is not only an API documentation site. They have some serious articles explaining a lot of they key concepts behind their technology. But of course the API documentation comes in handy a lot!

The Official WPF and Windows Forms site: http://windowsclient.net/

A bunch of articles and blogs talking about WPF and Windows Forms. Very entertaining when you simply don't know what you want to read. Pick anything.

Code Project: http://www.codeproject.com/

I recommend this site because there are a lot of interesting projects with in depth details from the author plus you get to ask questions (or see what questions were asked). I found very good code examples in this web site that helped me to understand lots of different concepts (I'm not advocating you should copy any of their source code though).

Stack Overflow: [I'll let you guess how to get there]

It helps you to answer those quick questions on how to do certain things or why this is not working. Also very helpful to understand some cryptic behaviors or error messages that you'll see along the way.


问:
Does your company have a coding standard?
I recently saw that Microsoft released a coding standards document (All-In-One Code Framework Coding Standards) and it got me thinking...  The company that I work for has no formal coding standards at all.  There are only a few developers and we have been together long enough to have evolved into similar styles and its never been an issue.

Does the company you work for have a documented coding standards?  If no, why not?  Does having a standard make a difference?  Is it worth writing a standard from scratch or should you adopt another standard as your own (ie. make Microsoft's standards yours)?

答:
Coding Standard discussions come down to this:

Yes you need them, consistency and clean code is a cornerstone of good development.

What they are almost doesn't matter, so long as everyone follows the same standards.

Don't write your own, you're end up in an endless and painful discussion.  There are plenty out there that are popular.

Using public standards (like those on MSDN) gives you an agnostic 3rd party that can't be argued with.  If you want to argue with them, refer to point 2.

If you're developing in C# in Visual Studio, then StyleCop is a silver bullet.  If you're also using ReSharper, then the StyleCop for ReSharper plugin is just awesome.

ContentLicense: CC BY-SA 2.5


问:
What were the "core" API packages of Java 1.0?
Reading about the Google v Oracle case, I came across these questions (apparently from the presiding Judge)

...

  Is it agreed that the following is true, at least as of 1996?

The following were the core Java Application Programming Interface: java.lang, java.util and java.io.

Does the Java programming language refer to or require any method, class or package outside the above three?

  ...

source: Groklaw

There are obviously lots of legal ramifications, Google and Oracle probably disagree on some points, and I don't care.  Leave law to the lawyers.

However, I suspect there's an interesting bit of history in here.

My question is (as someone who first did any Java coding around 2001 in version 1.3), in version 1.0 of Java was anything required outside of java.lang, java.util, and java.io to compile a valid Java program?

As an example (using C# 5.0), the await keyword is dependent upon Task<T> GetAwaiter() (amongst other things).  The compiler couldn't function to spec without that class.

Equivalently, were there any core runtime features (like ClassLoader*) that were dependent on other packages?

I'll admit I ask out of curiosity, exactly what is necessary for minimum-viable Java (the language, ignoring all the legal bits around it) is interesting.

*I am assuming that ClassLoader was even a feature in Java 1.0, it's part of the spec in 7.0 and presumably many earlier versions.

答: There were less than a dozen packages in the original JDK -- these plus applet, awt, awt.peer. That may have been it! It is absolutely likely -- 99% certain -- that these three packages included all classes that were explicitly known to the core JVM itself, and that there were no classes outside these packages mentioned in the language spec.</p>

OwnerDisplayName: Kevin Montrose

OwnerDisplayName: Ernest Friedman-Hill


答:
Per Wikipedia, the first formally released version of Java was 1.0.2, on Jan 23 1996.

The first stable version was the JDK 1.0.2. is called Java 1

There's an archive of Java 1.0.2 and all related documentation here:

JDK 1.0.2 API reference (book format)

JDK 1.0.2 API reference (javadoc format)

Java tutorial

Java language specification (link broken, wayback'd here)

Java virtual machine specification

There appears to be a download of the JDK 1.0.2 bits here

http://www.pascal-man.com/download/download-jdk.shtml

It works for me at the time of writing.

BEHOLD THE RAW UNMITIGATED POWER OF JAVA 1.0.2

In the language spec, the following classes are referred to (single citation, not exhaustive citations):

Class (section 4.3.1)

String (section 4.3.1)

Object (section 4.3.2)

Random (section 4.4)

Thread (section 17.2)

ThreadGroup (section 17.2)

Throwable (section 11)

Error (section 11.2)

loads and loads of errors, all under java.lang (section 11.5.2.1 - 11.5.2.2)

RuntimeException (section 11.2.1)

the "Array classes", [I, and so on (section 10.8)

... at which point I stopped looking because, technically, [I, et. al. aren't in the java.lang, java.util, or java.io packages.

Example:

```<code>class Test {
  // Compare namespaces of built-ins object and int[]
  public static void main(String[] args){
    int[] arr = new int[0];
    Object obj = new Object();

    Class arrClass = arr.getClass();
    Class objClass = obj.getClass();

    Class arrSuper = arrClass.getSuperclass();

    System.out.println("plain jane Object - " + objClass.getName());
    System.out.println();
    System.out.println("int[] - "+arrClass.getName());
    System.out.println("super of int[] - "+arrSuper.getName());
  }
}
</code>```

Outputs

Behavior is consistent between modern and 1.0.2

Title: What were the "core" API packages of Java 1.0?

Body:
Reading about the Google v Oracle case, I came across these questions (apparently from the presiding Judge)

...

  Is it agreed that the following is true, at least as of 1996?

The following were the core Java Application Programming Interface: java.lang, java.util and java.io.

Does the Java programming language refer to or require any method, class or package outside the above three?

  ...

source: Groklaw

There are obviously lots of legal ramifications, Google and Oracle probably disagree on some points, and I don't care.  Leave law to the lawyers.

However, I suspect there's an interesting bit of history in here.

My question is (as someone who first did any Java coding around 2001 in version 1.3), in version 1.0 of Java was anything required outside of java.lang, java.util, and java.io to compile a valid Java program?

As an example (using C# 5.0), the await keyword is dependent upon Task<T> GetAwaiter() (amongst other things).  The compiler couldn't function to spec without that class.

Equivalently, were there any core runtime features (like ClassLoader*) that were dependent on other packages?

I'll admit I ask out of curiosity, exactly what is necessary for minimum-viable Java (the language, ignoring all the legal bits around it) is interesting.

*I am assuming that ClassLoader was even a feature in Java 1.0, it's part of the spec in 7.0 and presumably many earlier versions.

Body:
Per Wikipedia, the first formally released version of Java was 1.0.2, on Jan 23 1996.

The first stable version was the JDK 1.0.2. is called Java 1

There's an archive of Java 1.0.2 and all related documentation here:

JDK 1.0.2 API reference (book format)

JDK 1.0.2 API reference (javadoc format)

Java tutorial

Java language specification (link broken, wayback'd here)

Java virtual machine specification

There appears to be a download of the JDK 1.0.2 bits here

http://www.pascal-man.com/download/download-jdk.shtml

It works for me at the time of writing.

BEHOLD THE RAW UNMITIGATED POWER OF JAVA 1.0.2

In the language spec, the following classes are referred to (single citation, not exhaustive citations):

Class (section 4.3.1)

String (section 4.3.1)

Object (section 4.3.2)

Random (section 4.4)

Thread (section 17.2)

ThreadGroup (section 17.2)

Throwable (section 11)

Error (section 11.2)

loads and loads of errors, all under java.lang (section 11.5.2.1 - 11.5.2.2)

RuntimeException (section 11.2.1)

the "Array classes", [I, and so on (section 10.8)

... at which point I stopped looking because, technically, [I, et. al. aren't in the java.lang, java.util, or java.io packages.

Example:

class Test {
  // Compare namespaces of built-ins object and int[]
  public static void main(String[] args){
    int[] arr = new int[0];
    Object obj = new Object();

    Class arrClass = arr.getClass();
    Class objClass = obj.getClass();

    Class arrSuper = arrClass.getSuperclass();

    System.out.println("plain jane Object - " + objClass.getName());
    System.out.println();
    System.out.println("int[] - "+arrClass.getName());
    System.out.println("super of int[] - "+arrSuper.getName());
  }
}

Outputs

Behavior is consistent between modern and 1.0.2


答:
Concurrent programming and parallelism within one process through multi-threading is very powerful but also complicated to get right because of all the problems with shared data: deadlocks, lost updates, etc.

However, there are situations in which it can be very useful (or even necessary):

For efficiency: if you have multiple cores you can run different threads on different cores.

For modularity: you split your implementation into different tasks and run them separately.

Because it is a requirement of your application, e.g. you want to fetch data from a server while your application continues to interact with the user.

Regarding 2, I find this approach very effective for implementing workflows in which there are different (virtual) processors that transform streams of data. Processors communicate through some kind of pipes, e.g. the output data stream of processor A is the input stream of processor B.

In this case all the effort in managing concurrency can be localized in the implementation of the data stream class (some kind of thread-safe queue with methods, say, push_front(), pop_back()): you can encapsulate all the management of data concurrency in the implementation of this queue class and then program each workflow node as if it were the only thread running on the system.

Following a similar but more general idea, it might be interesting to have a look at the actor model. In this model you see each thread as an object that sends and receives messages so you do not have to deal with threads directly. Languages that include a standard actor support are Erlang and Scala.
Otherwise you need an appropriate library for this, e.g. akka (Scala, Java), Theron (C++).
For implementations of the actor model in C#, look at the answers to this question.

Bottom-line, threads can very useful but if you intend to use them in a non-trivial way, I would advise you to use a more abstract approach using some library.

Title: When should I use parallelism?

Body:
After asking this question, I got to realize that parallelism may not always be good.

So far I can see that parallelism (under c#) is

A little complicated code-wise

Will probably insert some concurrency complications

Will not always be faster

I am looking inside parallelism because I want to make existing and new applications work faster, but now I see that it is no silver bullet.

When should I use it? are there any best practices?
Is it just a waste of time in most cases?
Is it suitable for a specific kind of applications?

I am looking forward for your insights on this matter.


问:
Using BSD Licensed source code
Someone wrote a .NET library to use the Google Maps API (link to the project).  I downloaded the entire repository and there are only source files, no LICENSE.txt, readme, etc.  However, I guess Google makes you pick a license when creating a new project so the author specified "New BSD License".

What I would like to do is download the source and rework it (maybe include JSON.net, add features, etc) and keep it in my github account.

So I have a few questions related to this:

Is the license valid even though the author doesn't have an explicit file with his name, copyright, etc?

If the license is valid, then do I just put his name and year into that BSD License Template?

In general, if there is a license included with a project, how do I make sure I am doing right by the author?  Would I just leave their license information in tact and then add my own on top of it?

Am I over thinking this and some of these licenses just amount to a "do whatever you want just don't sue me" (kind of my feelings, since I would be delighted if anyone wanted to use my code for anything at all)?

答:
If it is marked BSD, then why not believe it. BSD is a very friendly license that does not restrict your use of the software. You are supposed to provide attribution (as you noted), though the original author is under no such obligation; create the license info per your second bullet, and perhaps also offer the license-explicit code it back as a github pull request. </p>

<p>You are doing right by the author if you honor the license. Pour your code in on top and have fun. </p>

Title: Using BSD Licensed source code

Body:
If it is marked BSD, then why not believe it. BSD is a very friendly license that does not restrict your use of the software. You are supposed to provide attribution (as you noted), though the original author is under no such obligation; create the license info per your second bullet, and perhaps also offer the license-explicit code it back as a github pull request.

You are doing right by the author if you honor the license. Pour your code in on top and have fun.


问:
AJAX IRCX Client and Server
I am currently developing an IRCX AJAX Chat Based system and have a few questions regarding the Server and Client implementation. Any suggestions are welcome:

Server:

Should this be implemented as a Web Service or a Windows Form application? I have experience in developing Windows forms based servers however I am wondering if this would be better implemented as a Web Service, if so why?

Client:

How are Web Based Clients implemented today and what is the preferred way to implement a web based client?

My solution so far are:

ASP.NET Web Forms with an AJAX Update Panel (This seems the most viable)

Using jQuery connecting to the web service with a JavaScript timeout

Polling:

How frequently should the server be polled for new messages?

0.5 seconds seems a bit excessive and anything between 2 or 3 seconds seems sluggish?

Thanks for your input

答:
I recently came accross this blog post from the Trello team: The Trello Tech Stack

This is not the only way to do it, but I have been very impressed by Trello and I'll certainly use it as an example of good practices for such applications.

The Stack Exchange chat is also impressive and I suggest you to read the blog of its author.

Title: AJAX IRCX Client and Server


问:
Refactoring Switch Statements and is there any real use for Switch Statements at all?
I was reading this article and was wondering, do we get rid of all switch statements by replacing them with a Dictionary or a Factory so that there are no switch statements at all in my projects.

Something did not quite add up.

The question is, do switch statements have any real use or do we go ahead and replace them with either a dictionary or a factory method (in using a factory method, of course, there will be a minimum use of switch statements for creating the objects using the factory...but that is about it).

答:
Switch statements as case differentiation do have a real use. Functional programming languages use something called pattern matching which allows you to define functions differently depending on the input. However in object oriented languages the same goal can be reached more elegantly by using polymorphism. You simply call the method and depending on the actual type of the object, the corresponding implementation of the method will be executed. This is the reason behind the idea, that switch statements are a code smell. However, even in OO languages, you might find them useful to implement the abstract factory pattern.

tl;dr - they are useful, but quite often you can do better.


答:
java.net was also among the first packages available and it was great from the start, especially with the threading facility (now the Thread model appears outdated compared to what you have in more recent languages but it was great then).

I remember having coded a web browser (very incomplete, even compared to what existed at the time) in order to learn the freshly published 1.02 and, just after, a complete web application server (still used in industry). That was long before the servlet api and everybody being persuaded that you have to use heavy frameworks to make fast and reliable http applications in java.

With java.net (and the GC, and Threads, and exceptions and java.util) java was bound to be a major technology server side (at the opposite side, java.applet was painful since the first day...)


问:
Can two developers form an agile team?
I am working on a company's project alone at the moment, but the company is getting soon a junior developer whom I will be mentoring. Considering he will be learning a lot in first few days I am planning on using pair programming for first couple of weeks. I believe that doing pair programming would make daily standup a redundant practice. I definitely will keep the retrospective as well as tdd.

I wanted to ask if you would suggest any other agile practices that would benefit our small team of two developers? What have worked for you?

答:
You're assuming that daily stand-up is just for the developers. While it does have some benefit for them, it also has benefit for BAs, QA, etc. in having a regular time that they can hear what's going on and discover issues of miscommunication (most of the problems in software development), or which jobs are taking longer than initially predicted (allowing for minor reprioritisation, within the sprint, and for QA to know when they expect jobs to be delivered).

I have also worked on a team of two who used Agile estimation techniques and who kept a task board up to date, which is both useful and satisfying for the developers themselves and a very visible, constant representation of a sprint to the other stakeholders.

Title: Can two developers form an agile team?


答:
I am doing it with a team of one currently (I have been promised help in the near future).

But I find it useful for planning (I drag in other developers to help in estimation processes so it is not just me) and tracking progress (for both me and the management team).

Also when other team members join they will be able to see what tasks are currently available to work on and be able to jump in and help.

During planning it still works for prioritization and the demo are still cool.

Title: Can two developers form an agile team?

Body:
I am working on a company's project alone at the moment, but the company is getting soon a junior developer whom I will be mentoring. Considering he will be learning a lot in first few days I am planning on using pair programming for first couple of weeks. I believe that doing pair programming would make daily standup a redundant practice. I definitely will keep the retrospective as well as tdd.

I wanted to ask if you would suggest any other agile practices that would benefit our small team of two developers? What have worked for you?


问:
Good ways to jump to a particular state in a yielding stateful function?
I'm working on some embedded code using C. Various pieces of functionality need non-blocking stateful functions, which are mostly implemented using a switch on various states. For example, a modem connection manager (pseudo-code):

```<code>void manage_connection(void) {
    static states state = IDLE;
    switch (state) {
        case IDLE:
            if (connection_requested()) state = BACKOFF;
            break;
        case BACKOFF:
            if (random_delay_timeout()) {
                do_connect();
                state = CONNECTED;
            }
            break;
        case CONNECTED:
            result = send_data();
            if (result == DATA_SENT) {
                state = IDLE;
            } else if (result == ERROR) {
                // Go straight to backoff state and connect ASAP
                state = BACKOFF;
            }
            break;
    }
}
</code>```

State machines are nasty at the best of times, so I've started to move to a different paradigm using coroutine-style functions, using a "yield" statement. Of course, C doesn't provide a "yield" statement, but I'm using protothreads to achieve this. Protothreads is great, and gives me exactly what I want to implement the above non-blocking state machine in a structured-programming style. The above function roughly translates to (pseudo-code):

```<code>void manage_connection(void) {
    WAIT_UNTIL(connection_requested()); // or, while(!condition) yield;
    WAIT_UNTIL(random_delay_timeout());
    do_connect();
    WAIT_UNTIL((result = send_data()));

    if (result == DATA_SENT) {
        // RESTART starts from top. It is part of the protothreads API.
        RESTART();
    } else if (result == ERROR) {
        // This is the part which doesn't translate so well.
        // Could use an ugly goto:
        goto backoff;
        // Or similar alternatives, none of which scale well:
        // - Set a flag to skip the states I don't want, and RESTART();
        // - Use while loops or other control logic to branch appropriately.
    }
}
</code>```

As you can see, the protothreads version is, on the whole, much clearer & simpler in terms of the flow of logic (once you learn how protothreads work, and look past some very minor boilerplate which I haven't included in the example).

But jumping to a particular state in a state machine is a common pattern that I'm come across, which the state machine version handles elegantly, but the procedural version does not. Of course, that's why the procedural version is less bug-prone and clearer -- because you can't jump all over the place on a whim (except for goto, which I'd like to avoid for the usual reasons).

However, when you have a good reason to want to jump, it adds significant bug-prone lack of clarity to what is otherwise a very straightforward function.

Obviously there are plenty ways to achieve the necessary functionality, but none of them scale well to more than a few states. Bear in mind this is the simplest possible example -- my real-world functions fill half a screen.

What are some ways to solve this problem in a way that doesn't muddy the otherwise-lucid flow of logic?

答:
Unfortunately, I don't think there's a clear way out of this in plain C.

Your "otherwise-lucid flow of logic" (be it implemented with protothreads, threads or fibers) is still a state machine (as any program is), which is only apparently clean, because it's missing its lateral cases: transitions into error states, or transitions back (on failure or timeout); if you plug these transitions in, you find that you need to goto or muddy up the design, which, as you have observed, tends to get ugly.

One potentially cleaner solution is to set up a declarative state machine: you can use an array of state transition entries, each entry holding the state of origin, the final state, and at least two function pointers: a transition checker (can I perform this transition?), and a transition action (what to do when the transition is performed). When you need to perform a transition, go through the array entries with state of origin == current state, run the first one for which the checker returns TRUE, execute its action, and move to the new state. Mind that the checkers should be light or NULL (maybe just context checking - because you run them all the time), and the actions should be heavy (do stuff).

This is a good pattern for dense SMs (with lots of transitions); its only drawback is that it separates implementation (the checkers and actions) from the SM declaration (which may lead to a bit of yo-yo-ing when trying to understand what it does).

You can further improve this model with stuff such as:

Actions which execute every time a state is reached (regardless of the state of origin), before or after the transition;

Exceptions (actions which execute when the transition reports a failure somehow);

Nested SMs


答:
Both switch statements and polymorphism have their use. Note though that a third option exists too (in languages which support function pointers / lambdas, and higher-order functions): mapping the identifiers in question to handler functions. This is available in e.g. C which is not an OO language, and C# which is*, but not (yet) in Java which is OO too*.

In some procedural languages (having no polymorphism nor higher-order functions) switch / if-else statements were the only way to solve a class of problems. So many developers, having accustomed to this way of thinking, continued to use switch even in OO languages, where polymorphism is often a better solution. This is why it is often recommended to avoid / refactor switch statements in favour of polymorphism.

At any rate, the best solution is always case dependent. The question is: which option gives you cleaner, more concise, more maintainable code in the long run?

Switch statements can often grow unwieldy, having dozens of cases, making their maintenance hard. Since you have to keep them in a single function, that function can grow huge. If this is the case, you should consider refactoring towards a map based and/or polymorphic solution.

If the same switch starts to pop up in multiple places, polymorphism is probably the best option to unify all these cases and simplify code. Especially if more cases are expected to be added in the future; the more places you need to update each time, the more possibilities for errors. However, often the individual case handlers are so simple, or there are so many of them, or they are so interrelated, that refactoring them into a full polymorphic class hierarchy is overkill, or results in a lot of duplicated code and/or tangled, hard to maintain class hierarchy. In this case, it may be simpler to use functions / lambdas instead (if your language allows you).

However, if you have a switch in a single place, with only a few cases doing something simple, it may well be the best solution to leave it like it is.

*I use the term "OO" loosely here; I am not interested in conceptual debates over what is "real" or "pure" OO.

Title: Refactoring Switch Statements and is there any real use for Switch Statements at all?

Body:
I was reading this article and was wondering, do we get rid of all switch statements by replacing them with a Dictionary or a Factory so that there are no switch statements at all in my projects.

Something did not quite add up.

The question is, do switch statements have any real use or do we go ahead and replace them with either a dictionary or a factory method (in using a factory method, of course, there will be a minimum use of switch statements for creating the objects using the factory...but that is about it).