答:
Short Answer: Install the version that fits your bill

There is no down-side from installing the higher end version of Visual Studio, except the disk space that it will potentially be occupied during the install AND during the actual run and debug processes.

As you may know or not, Visual Studio creates a number of temporary files on your disk. Cleaning them up or setting process to do that automatically might be handy for you.

shortcut to clean “Temporary ASP.NET Files” folder before runing application?

detailed info from MSDN - Managing Solutions, Projects, and Files

The Ultimate and professional versions are having same requirements for minimum system configuration to run them. Here is a detailed product comparison article for VS 2010 - COMPARE PRODUCT FEATURES. I also assume that there will be no big changes in VS 2012 as well.

Title: Is there a downside to installing Visual Studio Ultimate if I don't need all the features?

Body:
Microsoft released today the final builds of Visual Studio 2012 on MSDN. I'm trying to decide from this version comparison page which edition to install (I can install any edition I want for free). I'm a solo developer who develops mostly web apps and console apps in C# and Python. Some of the features in Ultimate/Premium look potentially cool (like UML and "historical debugging"), but most of the features I will not need, or have never heard of.

On the one hand, it would be nice to have the features in case I want them someday. On the other hand, for some software products, the extra features cause the higher end editions to (1) be slower and use more memory, and (2) have a more cluttered UI.

Is this the case with Visual Studio?


问:
Is there a downside to installing Visual Studio Ultimate if I don't need all the features?
Microsoft released today the final builds of Visual Studio 2012 on MSDN. I'm trying to decide from this version comparison page which edition to install (I can install any edition I want for free). I'm a solo developer who develops mostly web apps and console apps in C# and Python. Some of the features in Ultimate/Premium look potentially cool (like UML and "historical debugging"), but most of the features I will not need, or have never heard of.

On the one hand, it would be nice to have the features in case I want them someday. On the other hand, for some software products, the extra features cause the higher end editions to (1) be slower and use more memory, and (2) have a more cluttered UI.

Is this the case with Visual Studio?

答: From a practical point the only issue with installing Ultimate is whether the person that manages your code after you will also have Ultimate. It's pretty easy to use features only available in the higher end SKU's for your project which will make it more difficult to maintain by someone with a lesser SKU. Especially Ultimate vs Professional. If that will never be a problem definitely go with Ultimate it has too many great features to not install it.</p>

ContentLicense: CC BY-SA 3.0


问:
Reverse engineering: what is it really good for?
I have some innocent/beginner questions:

What is reverse engineering good for?

As a programmer, should I learn the art of reverse engineering?

What are the benefits to a programmer who is experienced with it?

答: I would argue that the skill-set for reverse-engineering and the skill-set for debugging are exactly the same - if you are a fantastic debugger, you are also a fantastic reverse-engineer, and vice-versa.</p>


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答: The main reason to use the 2nd method is that it keeps the if and the else on the same tab, which greatly improves readability.

ContentLicense: CC BY-SA 2.5


问:
Best way to load application settings
A simple way to keep the settings of a Java application is represented by a text file with ".properties" extension containing the identifier of each setting associated with a specific value (this value may be a number, string, date, etc..). C# uses a similar approach, but the text file must be named "App.config". In both cases, in source code you must initialize a specific class for reading settings: this class has a method that returns the value (as string) associated with the specified setting identifier.

```<code>// Java example
Properties config = new Properties();
config.load(...);
String valueStr = config.getProperty("listening-port");
// ...

// C# example
NameValueCollection setting = ConfigurationManager.AppSettings;
string valueStr = setting["listening-port"];
// ...
</code>```

In both cases we should parse strings loaded from the configuration file and assign the converted values to the related typed objects (parsing errors could occur during this phase). After the parsing step, we must check that the setting values belong to a specific domain of validity: for example, the maximum size of a queue should be a positive value, some values may be related (example: min < max), and so on.

Suppose that the application should load the settings as soon as it starts: in other words, the first operation performed by the application is to load the settings. Any invalid values for the settings must be replaced automatically with default values: if this happens to a group of related settings, those settings are all set with default values.

The easiest way to perform these operations is to create a method that first parses all the settings, then checks the loaded values and finally sets any default values. However maintenance is difficult if you use this approach: as the number of settings increases while developing the application, it becomes increasingly difficult to update the code.

In order to solve this problem, I had thought of using the Template Method pattern, as follows.

```<code>public abstract class Setting
{
    protected abstract bool TryParseValues();

    protected abstract bool CheckValues();

    public abstract void SetDefaultValues();

    /// <summary>
    /// Template Method
    /// </summary>
    public bool TrySetValuesOrDefault()
    {
        if (!TryParseValues() || !CheckValues())
        {
            // parsing error or domain error
            SetDefaultValues();
            return false;
        }
        return true;
    }
}

public class RangeSetting : Setting
{
    private string minStr, maxStr;
    private byte min, max;

    public RangeSetting(string minStr, maxStr)
    {
        this.minStr = minStr;
        this.maxStr = maxStr;
    }

    protected override bool TryParseValues()
    {
        return (byte.TryParse(minStr, out min)
            && byte.TryParse(maxStr, out max));
    }

    protected override bool CheckValues()
    {
        return (0 < min && min < max);
    }

    public override void SetDefaultValues()
    {
        min = 5;
        max = 10;
    }
}
</code>```

The problem is that in this way we need to create a new class for each setting, even for a single value.
Are there other solutions to this kind of problem?

In summary:

Easy maintenance: for example, the addition of one or more parameters.

Extensibility: a first version of the application could read a single configuration file, but later versions may give the possibility of a multi-user setup (admin sets up a basic configuration, users can set only certain settings, etc..).

Object oriented design.

答:
At least in .NET, you can pretty easily create your own strongly-typed configuration objects -- see this MSDN article for a quick example.

Protip: wrap your config class in an interface and let your application talk to that. Makes it easy to inject fake configuration for tests or for profit.

Title: Best way to load application settings


答:
Sometimes it's used to get some parts/software to inter-operate as far as I understand. Some weird interfaces, bugs in implementation, etc.

But from what I understand, it's a very slippery subject, and so, the already complex laws of software development are taken to the extreme with reverse-engineering.

Title: Reverse engineering: what is it really good for?

Body:
I have some innocent/beginner questions:

What is reverse engineering good for?

As a programmer, should I learn the art of reverse engineering?

What are the benefits to a programmer who is experienced with it?


答:
I'm a big fan of YAGNI principal (though it's defined for software development, I do believe that it's applicable to real-world scenarios too). If you don't need it, then don't buy it. Buy it just when you need it.

If you don't need it, don't install it, no matter how small would be the resources dedicated to it. This is a culture. After a while you see that you have many services and applications on your computer, while you don't really need all of them.


问:
Overloading Operators - C++
I was experimenting with new overloaded operators, I have created one void operator and another one that returns something when it's called:

```<code>#include <iostream>

struct chichachicha{
    int operator()(){
        return 25;
    };
};

struct boomboom{
    void operator()() {
        std::cout << "Hi folks!" << std::endl;
    };
};

int main(){
    chichachicha objC;
    int f = objC();
    std::cout << f << std::endl;
    boomboom objB;
    objB();
    return(0);
}
</code>```

Is this the best way to write a code that does that?

How can I write an operator that can be called from anywhere in the code without instantiating the associated struct, that returns void/nothing and only prints a string of text? I'm not considering static methods, just operators.

答:
Despite "I'm not considering static methods, just operators", the statement immediately before it suggests you are asking for a static operator(). If this were possible, the most vexing parse would be much more vexing!

Upon further inspection, it reads like you are basically in the market for a static function. The whole purpose of operator() is to make a functor. If you want a polymorphic version of operator(), I'm afraid you'll have to instantiate something somewhere.

Title: Overloading Operators - C++


问:
Validating best practices, property vs dto, simple type vs object
Consider an application where adds an email address to his profile and submits it.

We have some dispute in our team over how to validate this email address. Some developers (including me) believe that we should validate this simple string via an extension method:

```<code>bool isValid = newEmail.IsEmail();
</code>```

They argue that any validation mechanism other than a single method call would be overhead, and an anti-pattern (against KISS principal).

While others argue that this email should first be added to a new instance of UserEmail DTO, then that DTO should be passed to a the relevant validator:

```<code>UserEmail userEmail = new UserEmail() { Email = newEmail };
bool isValid = new UserEmailValidator().Validate(userEmail);
</code>```

The second group argues that validating a single property makes no sense, because a property can't exist on its own. Thus we should always validate an object, not a property (I mean, value type properties, like strings and integers, etc.)

What advantages and disadvantages could each approach have?

答:
The second group argues that validating a single property makes no
  sense, because a property can't exist on its own.

Just because a property can't exist without a class doesn't mean that an email address needs to be inside a class to be validated. An email address doesn't need any other properties other than itself to be validated - IsEmail() looks nice and simple to me. Of course if you want to bundle together all of your validation in one place then create a validator class.


问:
Choosing the right programmer among a class of undergrads
I am a CS undergrad but I landed a programming job last year and I like it a lot. We are currently 3 programmer in the development section of the company and we have to work with pretty much anything were asked to do. We deal with many different languages and learn them as needed for some quick jobs etc etc.

We want to hire a 4th programmer and I'm asked to suggest some students in my class, a year younger, since I failed a class. I don't really know any of these guys except my teammates which I wouldn't suggest. We don't really want to interview them all so I thought we could make a little challenge to help us choose who to interview. We're in need of someone who understand the business even though they're new to it, and likes to learn new stuff and code. Any idea on a programming challenge or a kind of letter saying why we should take them?

TL;DR: We need a new undergrad programmer, we want the best to come to us without interviewing them all. Any challenge or test you could suggest?

答:
Run them through the Programmer Competency Matrix and see where they fall.

Identify problem solvers. People who get 100% on assignments are great, but might not be the most out of the box thinkers. Look for people who ask questions and work around problems without following traditional routes.

We don't really want to interview them all so I thought we could make a little challenge to help us choose who to interview.

This line in particular worries me. You should sit down with every applicant for at least five minutes unless the interaction you have shows such a gross lack of knowledge it would be worthless. You might end up (as mentioned above) with people who are great at finishing specific tasks but lack an overall "big picture" view.


问:
Are there deprecated practices for multithread and multiprocessor programming that I should no longer use?
In the early days of FORTRAN and BASIC, essentially all programs were written with GOTO statements.  The result was spaghetti code and the solution was structured programming.

Similarly, pointers can have difficult to control characteristics in our programs.  C++ started with plenty of pointers, but use of references are recommended.  Libraries like STL can reduce some of our dependency.  There are also idioms to create smart pointers that have better characteristics, and some version of C++ permit references and managed code.

Programming practices like inheritance and polymorphism use a lot of pointers behind the scenes (just as for, while, do structured programming generates code filled with branch instructions).  Languages like Java eliminate pointers and use garbage collection to manage dynamically allocated data instead of depending on programmers to match all their new and delete statements.

In my reading, I have seen examples of multi-process and multi-thread programming that don't seem to use semaphores.  Do they use the same thing with different names or do they have new ways of structuring protection of resources from concurrent use?

For example, a specific example of a system for multithread programming with multicore processors is OpenMP.  It represents a critical region as follows, without the use of semaphores, which seem not to be included in the environment.

```<code>th_id = omp_get_thread_num();
#pragma omp critical
{
  cout << "Hello World from thread " << th_id << '\n';
}
</code>```

This example is an excerpt from: http://en.wikipedia.org/wiki/OpenMP

Alternatively, similar protection of threads from each other using semaphores with functions wait() and signal() might look like this:

```<code>wait(sem);
th_id = get_thread_num();
cout << "Hello World from thread " << th_id << '\n';
signal(sem);
</code>```

In this example, things are pretty simple, and just a simple review is enough to show the wait() and signal() calls are matched and even with a lot of concurrency, thread safety is provided.  But other algorithms are more complicated and use multiple semaphores (both binary and counting) spread across multiple functions with complex conditions that can be called by many threads.  The consequences of creating deadlock or failing to make things thread safe can be hard to manage.

Do these systems like OpenMP eliminate the problems with semaphores?

Do they move the problem somewhere else?

How do I transform my favorite semaphore using algorithm to not use semaphores anymore?

答:
The latest rage in academic circles seems to be Software Transactional Memory (STM) and it promises to take all the hairy details of multi-threaded programming out of the hands of the programmers by using sufficiently smart compiler technology. Behind the scenes it is still locks and semaphores but you as the programmer don't have to worry about it. The benefits of that approach are still not clear and there are no obvious contenders.

Erlang uses message passing and agents for concurrency and that is a simpler model to work with than STM. With message passing you have absolutely no locks and semaphores to worry about because each agent operates in its own mini universe so there are no data related race conditions. You still have some weird edge cases but they are nowhere near as complicated as livelocks and deadlocks. JVM languages can make use of Akka and get all the benefits of message passing and actors but unlike Erlang the JVM does not have built-in support for actors so at the end of the day Akka still makes use of threads and locks but you as the programmer don't have to worry about it.

The other model I'm aware of that doesn't use locks and threads is by using futures which is really just another form of async programming.

I'm not sure how much of this technology is available in C++ but chances are if you are seeing something that is not explicitly using threads and locks then it will be one of the above techniques for managing concurrency.


答:
Answer to the Question

The general consensus is shared mutable state is Bad™, and immutable state is Good™, which is proven to be accurate and true again and again by functional languages and imperative languages as well.

The problem is mainstream imperative languages are just not designed to handle this way of working, things aren't going to change for those languages over night. This is where the comparison to GOTO is flawed. Immutable state and message passing is a great solution but it isn't a panacea either.

Flawed Premise

This question is based on comparisons to a flawed premise; that GOTO was the actual problem and was universally deprecated some how by the Intergalatic Universal Board of Language Designers and Software Engineering Unions©! Without a GOTO mechanism ASM wouldn't work at all. Same with the premise that raw pointers are the problem with C or C++ and some how smart pointers are a panacea, they aren't.

GOTO wasn't the problem, programmers were the problem. Same goes for shared mutable state. It in and of itself isn't the problem, it is the programmers using it that is the problem. If there was a way to generate code that used shared mutable state in a way that never had any race conditions or bugs, then it would not be an issue. Much like if you never write spaghetti code with GOTO or equivilent constructs it isn't an issue either.

Education is the Panacea

Idiot programmers are what were deprecated, every popular language still has the GOTO construct either directly or indirectly and it is a best practice when properly used in every language that has this type of constructs.

EXAMPLE: Java has labels and try/catch/finally both of which directly work as GOTO statements.

Most Java programmers that I talk to don't even know what immutable actually means outside them repeating the String class is immutable with a zombie like look in their eyes. They definitely don't know how to use the final keyword properly to create an immutable class. So I am pretty sure they have no idea why messaging passing using immutable messages is so great and why shared mutable state is so not great.

Title: Are there deprecated practices for multithread and multiprocessor programming that I should no longer use?

Body:
In the early days of FORTRAN and BASIC, essentially all programs were written with GOTO statements.  The result was spaghetti code and the solution was structured programming.

Similarly, pointers can have difficult to control characteristics in our programs.  C++ started with plenty of pointers, but use of references are recommended.  Libraries like STL can reduce some of our dependency.  There are also idioms to create smart pointers that have better characteristics, and some version of C++ permit references and managed code.

Programming practices like inheritance and polymorphism use a lot of pointers behind the scenes (just as for, while, do structured programming generates code filled with branch instructions).  Languages like Java eliminate pointers and use garbage collection to manage dynamically allocated data instead of depending on programmers to match all their new and delete statements.

In my reading, I have seen examples of multi-process and multi-thread programming that don't seem to use semaphores.  Do they use the same thing with different names or do they have new ways of structuring protection of resources from concurrent use?

For example, a specific example of a system for multithread programming with multicore processors is OpenMP.  It represents a critical region as follows, without the use of semaphores, which seem not to be included in the environment.

```<code>th_id = omp_get_thread_num();
#pragma omp critical
{
  cout << "Hello World from thread " << th_id << '\n';
}
</code>```

This example is an excerpt from: http://en.wikipedia.org/wiki/OpenMP

Alternatively, similar protection of threads from each other using semaphores with functions wait() and signal() might look like this:

```<code>wait(sem);
th_id = get_thread_num();
cout << "Hello World from thread " << th_id << '\n';
signal(sem);
</code>```

In this example, things are pretty simple, and just a simple review is enough to show the wait() and signal() calls are matched and even with a lot of concurrency, thread safety is provided.  But other algorithms are more complicated and use multiple semaphores (both binary and counting) spread across multiple functions with complex conditions that can be called by many threads.  The consequences of creating deadlock or failing to make things thread safe can be hard to manage.

Do these systems like OpenMP eliminate the problems with semaphores?

Do they move the problem somewhere else?

How do I transform my favorite semaphore using algorithm to not use semaphores anymore?


问:
Is it practical to abandon STL in C++ development?
I know in some areas (game industry, for example), STL is not recommended.
So my question is: is it really a good practice not to use STL in some cases? If so, what's the biggest reasons of not using the modern C++'s STL?</p>

答: There is one big valid reason not to use the C++ standard template library: One of your target platforms doesn't have a fully conforming implementation of it (or no implementation of it at all) and you know that it won't be getting one within the next years.</p>


问:
Not specifying a return in a function, good or bad?
I have coded like this many times, and I've never encountered an issue, but the compiler always warns when it expects a return and there is none.

For instance, look at this:

```<code>-(NSString *)outputStringForInteger:(NSInteger)int
{
    if (int == 0)
    {
        return @"Number is Zero";
    }
    else
    {
        return @"Number is not Zero";
    }
    //no "failsafe" or other explicit return
}
</code>```

If the function will never get to the last line, ever, is it important to still have a failsafe option, or do you guys just deal with compiler warnings?

答:
In D, except in a few trivial cases where the compiler can statically prove that the end of the function is unreachable without a return statement being executed or an exception being thrown, you must put either a return statement, a throw statement or an assert(0) at the end of the function.  In other languages I think this is usually good practice, though not necessarily in cases like your example, where a reader could trivially and statically tell that the end of the function is unreachable and a decent compiler should be able to prove this.

You shouldn't have a default return value that you believe is unreachable.  If it ever gets used your code is by definition in a state that you never intended for it to be in.  An assert(0) conveys your intentions both to the reader and the compiler much better.


答:
Patrick has mentioned the reason to not use the whole of the STL, namely that your platform(s) doesn't have one.

All in all I think the question is missing the point. It's mostly not an all or nothing decision, but one of pick and choose. You may well decide to go with the containers and algorithms, but decide to use something outside the Std Lib for strings and i/o.

Title: Is it practical to abandon STL in C++ development?

Body:
I know in some areas (game industry, for example), STL is not recommended.
So my question is: is it really a good practice not to use STL in some cases? If so, what's the biggest reasons of not using the modern C++'s STL?</p>


答:
Let's consider this from two points of view: the API to get the configuration values, and the storage format. They are often related, but it's helpful to consider them separately.

Configuration API

The Template Method pattern is very general, but I question whether you really need that generality. You'd need a class for each type of config value. Do you really have that many types? I'd guess that you could get by with just a handful: strings, ints, floats, booleans, and enums. Given these, you could have a Config class that has a handful of methods on it:

```<code>int getInt(name, default, min, max)
float getFloat(name, default, min, max)
boolean getBoolean(name, default)
String getString(name, default)
<T extends Enum<T>> T getEnum(name, Class<T> enumClass, T default)
</code>```

(I think I got the generics on that last one right.)

Basically each method knows how to handle parsing of the string value from the config file and to handle errors and to return the default value if appropriate. Range checking for the numeric values is probably sufficient. You might want to have overloads that omit the range values, which would be equivalent to providing a range of Integer.MIN_VALUE, Integer.MAX_VALUE. An Enum is a type-safe way of validating a string against a fixed set of strings.

There are some things this doesn't handle, such as multiple values, values that are interrelated, dynamic table lookups, etc. You could write specialized parsing and validation routines for these, but if this gets too complicated, I'd start to question whether you're trying to do too much with a config file.

Storage Format

Java properties files seem fine for storing individual key-value pairs, and they support the types of values I described above pretty well. You could also consider other formats such as XML or JSON, but these are probably overkill unless you have nested or repeated data. At that point it seems way beyond a config file....

Telastyn mentioned serialized objects. This is a possibility, although serialization does have its difficulties. It's binary, not text, so it's hard to see and edit the values. You have to deal with serialization compatibility. If values are missing from the serialized input (e.g., you added a field to the Config class and you're reading an old serialized form of it), the new fields are initialized to null/zero. You have to write logic to determine whether to fill in some other default value. But does a zero indicate absence of a config value, or was it specified to be zero? Now you have to debug this logic. Finally (not sure if this is a concern) you still may need to validate values in the serialized object stream. It's possible (though inconvenient) for a malicious user to modify a serialized object stream undetectably.

I'd say to stick with properties if at all possible.

Title: Best way to load application settings

Body:
A simple way to keep the settings of a Java application is represented by a text file with ".properties" extension containing the identifier of each setting associated with a specific value (this value may be a number, string, date, etc..). C# uses a similar approach, but the text file must be named "App.config". In both cases, in source code you must initialize a specific class for reading settings: this class has a method that returns the value (as string) associated with the specified setting identifier.

```<code>// Java example
Properties config = new Properties();
config.load(...);
String valueStr = config.getProperty("listening-port");
// ...

// C# example
NameValueCollection setting = ConfigurationManager.AppSettings;
string valueStr = setting["listening-port"];
// ...
</code>```

In both cases we should parse strings loaded from the configuration file and assign the converted values to the related typed objects (parsing errors could occur during this phase). After the parsing step, we must check that the setting values belong to a specific domain of validity: for example, the maximum size of a queue should be a positive value, some values may be related (example: min < max), and so on.

Suppose that the application should load the settings as soon as it starts: in other words, the first operation performed by the application is to load the settings. Any invalid values for the settings must be replaced automatically with default values: if this happens to a group of related settings, those settings are all set with default values.

The easiest way to perform these operations is to create a method that first parses all the settings, then checks the loaded values and finally sets any default values. However maintenance is difficult if you use this approach: as the number of settings increases while developing the application, it becomes increasingly difficult to update the code.

In order to solve this problem, I had thought of using the Template Method pattern, as follows.

```<code>public abstract class Setting
{
    protected abstract bool TryParseValues();

    protected abstract bool CheckValues();

    public abstract void SetDefaultValues();

    /// <summary>
    /// Template Method
    /// </summary>
    public bool TrySetValuesOrDefault()
    {
        if (!TryParseValues() || !CheckValues())
        {
            // parsing error or domain error
            SetDefaultValues();
            return false;
        }
        return true;
    }
}

public class RangeSetting : Setting
{
    private string minStr, maxStr;
    private byte min, max;

    public RangeSetting(string minStr, maxStr)
    {
        this.minStr = minStr;
        this.maxStr = maxStr;
    }

    protected override bool TryParseValues()
    {
        return (byte.TryParse(minStr, out min)
            && byte.TryParse(maxStr, out max));
    }

    protected override bool CheckValues()
    {
        return (0 < min && min < max);
    }

    public override void SetDefaultValues()
    {
        min = 5;
        max = 10;
    }
}
</code>```

The problem is that in this way we need to create a new class for each setting, even for a single value.
Are there other solutions to this kind of problem?

In summary:

Easy maintenance: for example, the addition of one or more parameters.

Extensibility: a first version of the application could read a single configuration file, but later versions may give the possibility of a multi-user setup (admin sets up a basic configuration, users can set only certain settings, etc..).

Object oriented design.

Body:
Let's consider this from two points of view: the API to get the configuration values, and the storage format. They are often related, but it's helpful to consider them separately.

Configuration API

The Template Method pattern is very general, but I question whether you really need that generality. You'd need a class for each type of config value. Do you really have that many types? I'd guess that you could get by with just a handful: strings, ints, floats, booleans, and enums. Given these, you could have a Config class that has a handful of methods on it:

int getInt(name, default, min, max)
float getFloat(name, default, min, max)
boolean getBoolean(name, default)
String getString(name, default)
<T extends Enum<T>> T getEnum(name, Class<T> enumClass, T default)

(I think I got the generics on that last one right.)

Basically each method knows how to handle parsing of the string value from the config file and to handle errors and to return the default value if appropriate. Range checking for the numeric values is probably sufficient. You might want to have overloads that omit the range values, which would be equivalent to providing a range of Integer.MIN_VALUE, Integer.MAX_VALUE. An Enum is a type-safe way of validating a string against a fixed set of strings.

There are some things this doesn't handle, such as multiple values, values that are interrelated, dynamic table lookups, etc. You could write specialized parsing and validation routines for these, but if this gets too complicated, I'd start to question whether you're trying to do too much with a config file.

Storage Format

Java properties files seem fine for storing individual key-value pairs, and they support the types of values I described above pretty well. You could also consider other formats such as XML or JSON, but these are probably overkill unless you have nested or repeated data. At that point it seems way beyond a config file....

Telastyn mentioned serialized objects. This is a possibility, although serialization does have its difficulties. It's binary, not text, so it's hard to see and edit the values. You have to deal with serialization compatibility. If values are missing from the serialized input (e.g., you added a field to the Config class and you're reading an old serialized form of it), the new fields are initialized to null/zero. You have to write logic to determine whether to fill in some other default value. But does a zero indicate absence of a config value, or was it specified to be zero? Now you have to debug this logic. Finally (not sure if this is a concern) you still may need to validate values in the serialized object stream. It's possible (though inconvenient) for a malicious user to modify a serialized object stream undetectably.

I'd say to stick with properties if at all possible.


答:
I can think of only one valid reason and it's really rare: Hard real time. Many things in the standard library allocate memory internally and that is not deterministic enough for hard real-time applications, so they have to be avoided. These applications are usually quite simple, though they take  disproportionate time to develop due to the very rigorous review and testing.

I can think of one invalid, but very common reason: Developers who don't understand computational complexity, misuse STL and then blame the library.

STL is usually faster at runtime than either C-style solutions with callback pointers or polymorphism-based solutions with virtual methods (see also this Bjarne Stroustrup's keynote). However when the developer does not understand the complexity specifications given and misuses the library by creating something like vector of vectors of some complex objects (in C++11 it's no longer a problem, though!), cause a performance problem and than defend themselves with "you see, the vectors are rather slow", it can cause a perception that standard library is slow. And once managers get such perception, it can live very long in the organization.

Obviously you can't use anything that the platform you are targeting does not support. However we are currently targeting four most common mobile platforms (Android, iOS, Bada and old WinCE) and use standard library and some parts of Boost on all of them.

Much of the standard library used to be unsupported by Microsoft early in WinCE (IIRC iostreams only came out with Visual Studio 2005), but it was possible to use STLport long before that instead. And you can usually get that to compile to anything. So I would call this reason invalid as well.

Besides, for quite long time it's not "STL", but ANSI C++ Standard Library. It's defined by the very same standard document that defines the language itself. Anything that does not support it does not really deserve to be called C++.


答:
I do not know about complexity (efficiency of implementation) but I am using Qt containers and strings extensively instead of the std ones and they work fine. I also find the Qt implementation of sets and lists easier to use.

So, it can be practical to abandon the STL if you can use another library that fits your needs.


答:
It is not practical, unless there's a heavy reason to do so. Some of such reasons which I can think of include only partial or lacking implementation of STL(or any other part of the standard library) or a resource limitation(memory, CPU speed, storage, ...) which you have to get around by rolling your own tools which adhere to what you need to accomplish.

In game industry most(even smaller to some extent) studios have their internal libraries and implementations of many standard library parts which are highly tailored for the target platform and in some cases target engnie or even game itself. Simply put when developing a game for consoles the hardware is very limited by today's standards. There are thousands and thousands of lines of hand-crafted assembly for a reason. It's very important to minimize all kinds of resource footprints in your code so that the game runs faster which allows more content in the game world(or a bigger world for example) which hopefully results in a better product.

"Every succesful game starts by rolling out your own linked list implementation."


问:
OSS - GPL v3 plugins in non-copyleft codebase.
I've been working on software to modify a game's resource files, and I'm planning on releasing it in open source.  I'm perfectly fine with releasing my code under gpl v3.  However, I'm afraid that that would deter others from writing extensions for my software, as I have had others offer to do so - the community which I'm working with is very much afraid of open source leeches, and as a result, the majority of popular released projects are closed source.  As such, I'd be more comfortable with something like BSD or MIT.

The codebase is extremely modular, and one window might consist of the end products of many different plugins.  One plugin which I am working with is the work (licensed under gpl v3) of a person who I have communicated with, who was enthusiastic of me using his software.  As one other person has contributed to that software, I don't think he can simply release his source to me under a different license.  In the future, I'd like to have more plugins for a variety of things which would be difficult to manually implement (as doing so would require large amounts of reverse engineering).

Tl;dr: As I am in good terms with these people, is there any means for me to use their code as plugins?  I would have permission, but licensing would be the issue, since others have contributed to the codebases.  If so, would it be okay if i distributed their plugins with my built software (in a plugins folder)?  How about placing them in the code repository and visual studio solution?

Any other advice would be appreciated.

Thanks!

答:
As the initial software author, you have quite a bit of latitude in determining what the boundaries of your software are. The Linux kernel is GPLv2, and explicitly says that applications are outside its legal copyright boundary.

If you state explicitly that the plugin interface is an external interface and third party plugins are not considered to be a derivative work of your program, then the working of the GPL (and any other license) will stop at that boundary.

Of course, if you also distribute those plugins, you will still have to abide by all their terms. In GPL terms, that's considered an "aggregate" work, and imposes no additional requirements.


问:
Can an open source solution match or surpass Team Foundation Server's features?
Team Foundation Server offers a version control system, but with many more side features, such as bug tracking, user stories, project planning, and it is all integrated into visual studio.
Someone put a more complete list of features over here:

Over the past year I have been working with Mercurial and from the moment I typed "hg init" I was in love. My new colleagues are convinced that even though other scm solutions are probably better, TFS provides a better complete package for teams.

What I would like to know is whether it is better to just use TFS, or to go the open source route and select various solutions and integrate them to get a better result, and if its even possible to get that level of integration?

So in summation: Can it be done and is it better to go for various OSS tools?

答:
As you know Mercurial is just a small part of a larger puzzle. There are various hosting sites out there that offer many of the other jigsaw pieces eg. Bug tracking, issue management, documentation/wiki, code review etc.

A good free example is bitbucket.com

A good commercial example is FogBugz/Kiln


问:
Condition based function declarations
I recently came across a weird piece of code

```<code>if(foo == bar){
 function foo_bar(){
   // Function definition
 }
}
</code>```

Is this a good practice of coding ?

答:
There is one valid use case:

```<code>if( !function_exists("helloWorld") ) {
    function helloWorld() {
        ...
    }
}
</code>```

Other than that, it would be preferable to avoid defining your functions inside if blocks.

Title: Condition based function declarations

Body:
There is one valid use case:

if( !function_exists("helloWorld") ) {
    function helloWorld() {
        ...
    }
}

Other than that, it would be preferable to avoid defining your functions inside if blocks.


问:
Choosing the right license for a testing framework
I've finished a first working, releasable version of a testing framework. Prior to release, I want to apply a proper license to it. Normally I'd choose something like GPLv3 but here I am pretty unsure. If I put the testing framework under GPLv3, does that mean users won't be able to test their commercial applications without also putting them under the GPL? Would a license like the MIT be a better fit?

I've just had a look at several popular testing frameworks (JUnit, Jasmine) and none of them uses the GPL.

EDIT

Forgot to mention the project is open sourced.

答:
If you don't feel strongly about the politics of the GPL, I recommend avoiding it. Choose something more liberal that (arguably) helps more people. A lot of people and organizations simply won't use GPL and LGPL-based software out of principle (or perhaps out of ignorance).

A liberal license like BSD or MIT will probably let your software be used by more people.


答: Well, with reverse engineering you can be able to reuse code minimising your work.For example,in Symfony2, you can convert a database made from the normal MySQL and convert it to the doctrine format and this is a reverse engineered process made possible in Symfony....and with reverse engineering,you are able to see the code let say 'in 2D'</p>


问:
Static functions vs classes
Let's say that I want to build some utility functions to do some basic maths with the BigDecimals, for example I want to have a function that computes the average of a List<BigDecimal>.

What is the best approach? A static function or a utility class?

```<code>public static BigDecimal computeAverage(List<BigDecimal> numbers)
</code>```

or

```<code>public class BigDecimalUtil

public computeAverage(List<BigDecimal> numbers)
</code>```

答:
If I'm not wrong and Java cotinues to be a pure OO language, you cannot have functions without wraping them in a class.

So your answer is: both, a static function wraped in a static utility class, not unlike Math class.

Title: Static functions vs classes


答:
I'm not sure if you have a large enough candidate base for this, but you could try coming up with a set of problems similar to the puzzles from Facebook, ITA and Google. Each problem should have many different possible solutions. The idea is to look at the submissions and evaluate them based on:

Fulfilling requirements

Coding standards

Design

Performance

Testing

Documentation

etc

Invite the best candidates in for interviews, discuss their solutions with them (to validate they actually wrote the code and to further see how they think/work) and then make your pick.

Title: Choosing the right programmer among a class of undergrads

Body:
I am a CS undergrad but I landed a programming job last year and I like it a lot. We are currently 3 programmer in the development section of the company and we have to work with pretty much anything were asked to do. We deal with many different languages and learn them as needed for some quick jobs etc etc.

We want to hire a 4th programmer and I'm asked to suggest some students in my class, a year younger, since I failed a class. I don't really know any of these guys except my teammates which I wouldn't suggest. We don't really want to interview them all so I thought we could make a little challenge to help us choose who to interview. We're in need of someone who understand the business even though they're new to it, and likes to learn new stuff and code. Any idea on a programming challenge or a kind of letter saying why we should take them?

TL;DR: We need a new undergrad programmer, we want the best to come to us without interviewing them all. Any challenge or test you could suggest?


问:
Why should I declare a class as an abstract class?
I know the syntax, rules applied to abstract class and I want know usage of an abstract class

Abstract class can not be instantiated directly but can be extended by other class

What is the advantage of doing so?

How it is different from an Interface?

I know that one class can implement multiple interfaces but can only extend one abstract class. Is that only difference between an interface and an abstract class?

I am aware about usage of an Interface. I have learned that from Event delegation model of AWT in Java.

In which situations I should declare class as an abstract class? What is benefits of that?

答:
Abstract classes are for "is a" relationships and interfaces are for "can do".

Abstract classes let you add base behavior so programmers don't have to code everything, while still forcing them to follow your design.


问:
Why do developers need to keep up to date with technologies and methodologies?
I am always given the advice that developers need to stay up to date with the latest in technology - things like webrtc, updates on html5 and css3 and new js libraries, software methodologies like TDD, DDD, and BDD.

The question is why? Why do we need to constantly update ourselves? Can't we just stick with what we know and become better with it?

答:
New technologies surface for a reason. Usually that reason is because they are more efficient or powerful at accomplishing a particular task.

There is still value to be had in sticking with old technology for the sake of legacy systems, but when they eventually reach their end of life you'll be behind the game.

Business reasons aside, constantly learning new technologies keeps you on your toes and will open your eyes to different ways of approaching tasks, even in old technologies and so on, so forth.


答:
Although it is certainly possible to build a career on a single technology stack if you get lucky1, it is a near certainty that the technology is going to change more than once during the time when you are gainfully employed. You can (and you should) get better at what you already know, but learning new things ahead of time will help you cut down on the learning curve when the next technology shift comes to your corner of the industry.

There is a less apparent side to it, too: learning new things very often help you see the things that you already know from a different perspective, in the same way that learning a new language helps you learn more things about your current language2.

Finally, a pure entertainment value of learning new things should not be underestimated: to me, it beats watching TV hands down.

1For example, by picking COBOL over PL/I at the start of your career in 1965.

2This works for natural and programming languages alike.

Title: Why do developers need to keep up to date with technologies and methodologies?

Body:
I am always given the advice that developers need to stay up to date with the latest in technology - things like webrtc, updates on html5 and css3 and new js libraries, software methodologies like TDD, DDD, and BDD.

The question is why? Why do we need to constantly update ourselves? Can't we just stick with what we know and become better with it?


答:
Can't we just stick with what we know and become better with it?

You can, but it's really easy to fall into the trap of never wanting to learn anything new. Your job prospects dwindle, your teammates stop wanting to work with you because you're "that programmer who's completely out of touch".

Mostly, you need to keep a balance. Trying to learn everything new all the time is going to lead you to be poor at many things, perceived as a flighty tinkerer. Learn a few things well, and focus at least on knowing what exists, even if you can't use it effectively.


问:
Object-Oriented Design: What to do when responsibility of the class is big
I applied principles of the GRASP and ended up having a class called Environment.
This class's responsibilities are to:

Keep information about services in the environment,i.e. environment definition (Service is another class)

Start/stop services meeting some criteria

Apply configuration changes to different service and keep list of updated services

Restart services with configuration change

Revert configuration changes at the end of session

Search/Give  Service class based on criteria (name etc.)

According to OOD, this is not a problem: very cohesive responsibility is assigned to this class.

But on the other hand it's a problem since the class is too big, even though all responsibility assigned to it makes sense. If I want to divide this responsibility to between separate classes, then all these classes need to know about "environment definition", which makes coupling worse and those classes will have "feature envy".

What design patterns are applicable for such situation? Or what other principals can be applied to have cohesive, less coupled classes?

Thanks in advance.

答:
I'm not sure what design-pattern this is (if any), but in this particular case (if I understand this correctly) I would go for several classes, each for its own set of responsibilities plus front-end class which would serve as a proxy to those who responsible for a particular action.

Yes, the functionality is cohesive, but that does not mean you cannot decompose it to several cohesive and less complex classes, does it?

OwnerDisplayName: Azho KG

OwnerDisplayName: akond


答:
You probably meant to have Environment as a Facade (facade pattern) and not to implement every detail in it.

Break out all functionality into other classes. Imho each of the responsibilities below should be handled by a separate class that the Environment class uses internally.

Keep information about services in the environment,i.e. environment definition (Service is another class)

Start/stop services meeting some criteria

Apply configuration changes to different service and keep list of updated services

Restart services with configuration change

Revert configuration changes at the end of session

Search/Give Service class based on criteria (name etc.)

Those should give you six new classes. It will probably lead to some other classes too so that you for instance can manage configuration from different classes.

Title: Object-Oriented Design: What to do when responsibility of the class is big

Body:
I applied principles of the GRASP and ended up having a class called Environment.
This class's responsibilities are to:

Keep information about services in the environment,i.e. environment definition (Service is another class)

Start/stop services meeting some criteria

Apply configuration changes to different service and keep list of updated services

Restart services with configuration change

Revert configuration changes at the end of session

Search/Give  Service class based on criteria (name etc.)

According to OOD, this is not a problem: very cohesive responsibility is assigned to this class.

But on the other hand it's a problem since the class is too big, even though all responsibility assigned to it makes sense. If I want to divide this responsibility to between separate classes, then all these classes need to know about "environment definition", which makes coupling worse and those classes will have "feature envy".

What design patterns are applicable for such situation? Or what other principals can be applied to have cohesive, less coupled classes?

Thanks in advance.

OwnerDisplayName: jgauffin


问:
Why null pointer instead of class cast?
In Java:

```<code>int count = (Integer) null;
</code>```

throws a java.lang.NullPointerException.

Why doesn't this throw a Class Cast Exception for ease in programmer understanding?

Why was this exception chosen over any other exception?

答:
Java successfully casts null to an Integer reference that references no object.

That's OK because being unistantiated is a valid state for a reference.

It's the calling of a method of a non existing object that can't be performed.

Performing the cast (Integer)null is the same as declaring an Integer variable and then failing to assign it an new (or already existing) Integer object instance.

Title: Why null pointer instead of class cast?


问:
B.A Computer Science Vs B.S Inf Tech?
Would a recruiter prefer a B.A in Comp Science from a more prestigious university or a B.S in Inf Tech from just an average university? Would it matter for someone already established in the field with plenty of experience?

The only difference in the B.A and B.S is essentially the mathematics.  The B.S is geared for those going on to master's programs, although one isn't excluded from going on to a masters program with a BA, many do require more mathematics.

Just for those curious, the information tech degree is typically geared more to real-world problems then the computer science and the quality of it will vary widely. Some inf tech programs are as in-depth as an ABET C.S degree, the information tech from Drexel looks extremely strong. The Management Information Systems is generally provided via the business school and is more of a traditional business degree.

I'm not sure really how well versed the recruiters/g.p are in the actual differences in all of these programs. Some non ABET BS Comp Science may only require 1 or 2 Calculus versus the ABET certified programs.

答: Personally, I expect candidates to know C.S. fundamentals, but I don't pay much attention to their degree. I've hired lots of people with degrees in E.E. and other fields; I assess these skills myself.</p>

Title: B.A Computer Science Vs B.S Inf Tech?


问:
Use constructor or setter method?
I am working on a UI code where I have an Action class, something like this -

```<code>public class MyAction extends Action {
    public MyAction() {
        setText("My Action Text");
        setToolTip("My Action Tool tip");
        setImage("Some Image");
    }
}
</code>```

When this Action class was created, it was pretty much assumed that the Action class won't be customizable (in a sense - its text, tooltip or image will be not be changed anywhere in the code). Now, we are in need of changing the action text at some location in code. So, I suggested my co-worker to remove the hardcoded action text from the constructor and accept it as an argument, so that everybody is forced to pass the action text. Something like this code below -

```<code>public class MyAction extends Action {
    public MyAction(String actionText) {
        setText(actionText);
        setTooltip("My Action tool tip");
        setImage("My Image");
    }
}
</code>```

He, however, thinks that since setText() method belongs to base class it can be flexibly used to pass the action text wherever action instance is created. That way, there is no need to change the existing MyAction class. So his code would look something like this.

```<code>MyAction action = new MyAction(); //this creates action instance with the hardcoded text
action.setText("User required new action text"); //overwrite the existing text.
</code>```

I am not sure if that is a correct way to deal with problem. I think in above mentioned case user is anyway going to change the text, so why not force him while constructing the action? The only benefit I see with the original code is that user can create Action class without much thinking about setting text.

答:
In the following proposed solution, superclass is abstract and has all three members set to a default value.

Subclass has different constructors so the programmer can instantiate it.

If first constructor is used, all members will have the default values.

If second constructor is used, you give an initial value to actionText member leaving other two members with the default value...

If third constructor is used, you instantiate it with a new value for actionText and toolTip, leaving imageURl whith the default value...

And so on.

```<code>public abstract class Action {
    protected String text = "Default action text";
    protected String toolTip = "Default action tool tip";
    protected String imageURl = "http://myserver.com/images/default.png";

    .... rest of code, I guess setters and getters
}

public class MyAction extends Action {

    public MyAction() {

    }

    public MyAction(String actionText) {
        setText(actionText);
    }

    public MyAction(String actionText, String toolTip_) {
        setText(actionText);
        setToolTip(toolTip_);
    }

    public MyAction(String actionText, String toolTip_; String imageURL_) {
        setText(actionText);
        setToolTip(toolTip_);
        setImageURL(imageURL_);
    }

}
</code>```

Title: Use constructor or setter method?

Body:
In the following proposed solution, superclass is abstract and has all three members set to a default value.

Subclass has different constructors so the programmer can instantiate it.

If first constructor is used, all members will have the default values.

If second constructor is used, you give an initial value to actionText member leaving other two members with the default value...

If third constructor is used, you instantiate it with a new value for actionText and toolTip, leaving imageURl whith the default value...

And so on.

public abstract class Action {
    protected String text = "Default action text";
    protected String toolTip = "Default action tool tip";
    protected String imageURl = "http://myserver.com/images/default.png";

    .... rest of code, I guess setters and getters
}

public class MyAction extends Action {

    public MyAction() {

    }

    public MyAction(String actionText) {
        setText(actionText);
    }

    public MyAction(String actionText, String toolTip_) {
        setText(actionText);
        setToolTip(toolTip_);
    }

    public MyAction(String actionText, String toolTip_; String imageURL_) {
        setText(actionText);
        setToolTip(toolTip_);
        setImageURL(imageURL_);
    }

}


问:
How will quantum computing change programming?
How is programming a quantum algorithm different? What would a C like language look like if it was designed for qubits? Would types change?</p>

答:
What would a C like language look like if it was designed for qubits? Would types change?

It would be so drastically different as to be incomprehensible as C.

The main issue (as I understand it) is that quantum computing does not work in a nice imperative manner 'do this, then that, then this other thing'. Trying to force C's ability to do that into the 'processor' of quantum computer will be if not impossible, wildly inefficient.

Programming algorithms for quantum computers (again, as I understand them) tend to be closer to functional programming style map/reduce, since quantum computing allows all of the candidates in the 'reduce' part to exist concurrently and "fall out" of the computer when observed.

Note that there are some existing algorithms for quantum computers, even though the devices don't exist to run them. Simon's algorithm for example.


答:
When I looked into this some time ago, it was clear that quantum algorithms, while not particularly fast, permit exponentially massive parallelism.
So they will shine in cases involving search in spaces that are not practical with sequential hardware, even massively parallel sequential hardware.

One property of quantum algorithms is that they have to be reversible.
Any given algorithm can be translated into one that is reversible, by adding to it enough record-keeping to allow it to be run backward.

Another property is that getting an answer out of a quantum algorithm is a hit-and-miss affair, because what you get at the end of a computation is multiple answers, each with its own probability. It needs to be run in such a way that the answer you want has high probability.
This may involve running the algorithm forward and backward multiple times.

Check out Grover's Search Algorithm.

INSERTED to show the fundamental operation of Grover's algorithm. Suppose there is a search problem. The possible answers are 0, 1, 2, and 3, but the right answer is 2. So the quantum computer is put in a superposition of all four states, and it goes through a sequence of steps to see which one is correct, and inverts its amplitude, like the black dots and arrows below:

You can see that arrow 2 has been inverted inside the machine, but there's no way to tell that outside, because only probabilities are visible outside, which are amplitudes squared, and when squared they are all equal.

However, the amplitudes have a mean, indicated by the red line, and the computer can be made to go through a sequence of steps that inverts each amplitude about the mean.
When that is done, the amplitudes, and the probabilities, transfer to state 2, the right answer !
So if the machine is observed, state 2 shines forth.

It's not quite this simple. Generally it takes multiple cycles of the machine, forward and backward, inverting at the end of each cycle, to maximize the probability of the right answer. Also, one must take care not to do it any more than that number of times, because it can just as easily reverse itself.

So why do they say quantum computers are so fast?
Because every time you double the number of qubits, you square the parallelism, but you don't square the length of time, so eventually it wins.

Isn't that fun?

I was personally interested in how this could be applied to verification of software correctness.
Now we test software by throwing a bunch of test inputs at it and (to be overly simple) seeing if it hits an Assert.
In a quantum computer it might be possible to run it in parallel against a much denser set of inputs and see if any of those cases hit an Assert.

Like if the input to the algorithm were 128 bytes, or 1024 bits, there are 2^1024 or 10^308 possible different inputs. There is no way to test that many inputs on a conventional computer, but a quantum computer could try them all in parallel.

Title: How will quantum computing change programming?

Body: How is programming a quantum algorithm different? What would a C like language look like if it was designed for qubits? Would types change?</p>


问:
Should I build a multi-threaded system that handles events from a game and sorts them, independently, into different threads based on priority?
Can I build a multi-threaded system that handles events from a game and sorts them, independently, into different threads based on priority, and is it a good idea?

Here's more info:

I am about to begin work on porting a mid-sized game from Flash/AS3 to Java so that I can continue development with multi-threading capabilities.

Here's a small bit of background about the game:

The game contains numerous asynchronous activities, such as "world updating" (the game environment is constantly changing based on a set of natural laws and forces), procedural generation of terrain, NPCs, quests, items, etc.,  and on top of that, the effects of all of the player's interactions with his environment are programmatically calculated in real time, based on a set of constantly changing "stats" and once again, natural laws and forces.

All of these things going on at once, in an asynchronous manner, seem to lend themselves to multi-threading very well.

My question is:

Can I build some kind of central engine that handles the "stacking" of all of these events as they are triggered, and dynamically sorts them out amongst the available threads, and would it be a good idea?

As an example:

Essentially, every time something happens (IE, a magic missile being generated by a spell, or a bunch of plants need to grow to their next stage), instead of just processing that task right then and adding the new object(s) to a list of managed objects, send a reference to that event to a core "event handler" that throws it into a stack of all other currently queued events, which then sorts them out and orders them according to urgency, splits them between a number of available threads for as-fast-as-possible multithreaded execution.

答:
Ahhh concurrency in Java :-). Right, so I'm going to give some general advice here:

Model your asynch processing on a whiteboard, then get someone else to come in and challenge your assumptions, especially the assumption that you need it in the first place (it sounds like you do, but it never hurts to challenge that). There's a whole bunch of concurrent data structures you could use to model what you're trying to achieve, see my mention of Brian's book to get a good practical guide on these things (in Java).

Concurrency in Java is hard - Objects are mutable by default, implicit locking is hard to get right and you often have to deal with the low-level construct that is Thread itself. If you are going to do the work in Java, then read Brian Goetz's excellent Java Concurrency in Practice to make sure you avoid the major pitfalls. Java 7 improves things again, but there's still some fundamental issues that make it hard (for now).

Given 2. it's well worth looking at a framework or even another language on the JVM that abstracts away from this.  Popular choices today include the Akka framework (that both Scala and Java support), GPars (Groovy) or out and out Clojure (If you like Lisp).

HTH a little!


答:
Sure, that would work.  And based upon the requirements of your environment, it makes sense.

Essentially, you're just creating a more sophisticated version of the Thread pool pattern by adding prioritized queues.

Title: Should I build a multi-threaded system that handles events from a game and sorts them, independently, into different threads based on priority?

Body:
Can I build a multi-threaded system that handles events from a game and sorts them, independently, into different threads based on priority, and is it a good idea?

Here's more info:

I am about to begin work on porting a mid-sized game from Flash/AS3 to Java so that I can continue development with multi-threading capabilities.

Here's a small bit of background about the game:

The game contains numerous asynchronous activities, such as "world updating" (the game environment is constantly changing based on a set of natural laws and forces), procedural generation of terrain, NPCs, quests, items, etc.,  and on top of that, the effects of all of the player's interactions with his environment are programmatically calculated in real time, based on a set of constantly changing "stats" and once again, natural laws and forces.

All of these things going on at once, in an asynchronous manner, seem to lend themselves to multi-threading very well.

My question is:

Can I build some kind of central engine that handles the "stacking" of all of these events as they are triggered, and dynamically sorts them out amongst the available threads, and would it be a good idea?

As an example:

Essentially, every time something happens (IE, a magic missile being generated by a spell, or a bunch of plants need to grow to their next stage), instead of just processing that task right then and adding the new object(s) to a list of managed objects, send a reference to that event to a core "event handler" that throws it into a stack of all other currently queued events, which then sorts them out and orders them according to urgency, splits them between a number of available threads for as-fast-as-possible multithreaded execution.


答:
I'd say you can ignore a lot of what's out there.  Much of it is hype and fad and new names for old technology.  The real advances will soon be replaced by even newer ones that don't really depend on the old ones, even though the old timers say you ought to understand the old ones to understand the new.  If you left the field for 10 years, when you came back you'd only be 2 years behind.

That said, spotting the real new technogy can be tricky.  I'm glad I didn't miss OOP, but it sure looked like just a handful of buzz words at first.  And you often need to use current technology to do a job, even if everyone will have forgotten it in 3 years.

The software technology hype and confusion multiplies the change we have to deal with day-to-day.  But electronic technology actually is advancing rapidly, and pushing software along with it.  There's a lot of real change out there.  We're still driving the cars, flying the planes, and going into space with the same vehicles we used in 1965.  But the electronic hardware from 1995 is hopelessly obsolete.

So the deep answer to your question is that the scientists and engineers working with electricity have been very busy.  The software needs to evolve to take advantage of the hardware.  Worse (or rather--better?), I think the software's been left way behind by the hardware.  If the hardware people all retired tomorrow, software would evolve furiously for the next two decades at least.

If you need the new technology to do a job, you need to learn it.  If there's a chance it's a new technology that will still be here 20 years from now, you need to keep an eye on it--and if you watch 20 techs that die for every one that lives, you're doing pretty good.  And you actually can ignore everything else.  Except for that one bit of obvious smoke that will underlie all the software of the 2020's.


问:
What simple techniques do you use to improve performance?
I'm talking about the way we write simple routines in order to improve performance without making your code harder to read... for instance, this is the typical for we learned:

```<code>for(int i = 0; i < collection.length(); i++ ){
   // stuff here
}
</code>```

But, I usually do this when a foreach is not applicable:

```<code>for(int i = 0, j = collection.length(); i < j; i++ ){
   // stuff here
}
</code>```

I think this is a better approach since it will call the length method once only... my girlfriend says it's cryptic though. Is there any other simple trick you use on your own developments?

答:
If this is C++, you should get in the habit of ++i rather than i++.  ++i will never be worse, it means exactly the same as a stand-alone statement, and in some cases it could be a performance improvement.

It's not worth changing existing code on the off-chance that it will help, but it's a good habit to get into.


答:
All of these things going on at once, in an asynchronous manner, seem to lend themselves to multi-threading very well.

To me it seems like the exact opposite.

Your "world" is one gigantic bunch of mutable state, which leads to all kinds of nightmares when combined with multithreading.

The big question is: What happens when two events that are processed in parallel affect the same part of the world in contradicting ways and how do you prevent event processor code from seeing inconsistent world states? There are many subtly different variations of this question you'll run into.

Perhaps it will turn out in the end that such cases are rare and any resulting inconsistencies tolerable, but if not, it's going to cause massive headaches that can kill the project.

Here's an interesting (though rather short) article about multi threaded game architectures. And here a more in-depth article that also mentions synchronization as a problem and reason why many games use a single-threaded game loop. It claims that such problems can be largely avoided by doing "non-preemptive multithreading", but I'm not sure how that would work exactly.


问:
SQL Server 2000 vs 2008 Express?
Due to not wanting to pay licenses my company is still using SQL Server 2000 for new projects.

This is very limiting for multiple reasons.

I'm wondering what are the limitations of using SQL Server Express 2008?

Is there any reason NOT to use it to power ASP.Net MVC3 websites?

答:
Sql Server 2008 R2 Express has the following limitation:

10GB size limit per database

No agent to run scheduled tasks

Limited to run on 1 physical cpu (will use multiple cores on the single cpu)

1GB ram limit

If you can run your app within these limits then you could upgrade from SQL Server 2000 to 2008 Express.

Pricing:

SQL Server 2012 Standard licensing runs around $1800 / core (not physical socket) (with a 4 core minimum requirement) or $900 server license + $200 per CAL (Client Access License)

The database is the heart of the company and stores all their information, it's a worth while investment to spend $7200 to upgrade to an updated and currently supported version of the database server software.

Title: SQL Server 2000 vs 2008 Express?


问:
How to understand Linux kernel source code for a beginner?
I am a student interested in working on Memory Management, particularly the page replacement component of the linux kernel.

What are the different guides that can help me to begin understanding the kernel source?

I have tried to read the book Understanding the Linux Virtual Memory Manager by Mel Gorman and Understanding the Linux Kernel by Cesati and Bovet, but they do not explain the flow of control through the code. They only end up explaining various data structures used and the work various functions perform. This makes the code more confusing.

My project deals with tweaking the page replacement algorithm in a mainstream kernel and analyse its performance for a set of workloads. Is there a flavor of the linux kernel that would be easier to understand (if not the linux-2.6.xx kernel)?

答:
The debugger option could be useful.

Some more things that can be done after building the kernel with the debugger option is to write some sample test applications calling various system calls which will invoke the kernel and you can traverse through one piece of kernel code at a time and understand it's implementation.


问:
Learning the Operating Systems concepts and Programming Languages for elderly
I am not sure if this would be the right forum to ask the question (Please let me know and I will move the question to appropriate forum).

I would like to know what can be the best way for elders (in my case, my parents) to learn how  to program. I was looking at Qimo 4 kids as a possible platform so that my parents can have a closer look at Linux environments. But it seems like Qimo mostly consists of educational games. I also don't know about which programming language would make the best choice.

If anyone can provide me with information on how to go about with this "project", that would be grateful!!!

答:
Udacity has an interesting project-based approach to learning.

Udacity's course catalog has several beginner courses. One that you may be interested in is:

Introduction to Computer Science: Building a Search Engine


答:
IMHO, you need to find a balance. That takes skill and experience.

You need to find one or two languages you specialize in, keep up to date in framework/style changes that evolve in this language, and keep your skills top-notch.

But you also have to see how this language evolves, and understand the dynamics of software development as a whole. Will Java be around in 10 years, is Phyton there to stay, is PHP going to be replaced with .NET and Mono?

These are large scale, strategic questions, answers to which will let you become highly valued professional in your field, while having some solid backup (1 or 2 languages) and knowing when to move on from your main platform.

IMHO, following all the modern languages that are being developed every day is one of the biggest problems for the whole industry. We have ton of undeveloped, dead-end languages with almost no professionals in them, and people who waste time on them are rarely real professionals in even 1 language. Mostly they write code that's mix of all languages and does nothing right. At the same time, amount of man-years that's wasted on these nonstandard languages could be spent on improving few core language frameworks and specs.


问:
What is the difference between `update` and `upgrade`
What is the difference between update and upgrade in the context of application software?

答:
When I think of update, I think of something free.

When I think of upgrade, I think of something that costs.

But of course, it just really depends on the software. I've seen the terminology used interchangeably before.


问:
front end development test - html/css/jquery/javascript
We are continually revamping our front end developer test that we do in-house after a candidate has passed an online test. The online test has questions such as:

How does a for loop start?

What is the correct way to write a JavaScript array?

Write the css selector for the 3rd list item within an ordered list
with the id "myList"

For var shoppingList = ["milk", "dumplings", "bread"]; - how would
you return dumplings into a variable named groceryItem?

FizzBuzz

So we cover the basics, and try to get an insight into their knowledge.

But, in house, we really want to test their problem solving skills, their logic approach, etc. And I don't think we've found a good way to do that for front end developers. For UI guys, it's easier - we give them a design challenge and a white board and see if they ask for more information, how they approach the problem, etc.

But we haven't found a way to replicate this approach with web developers (for the record, I am one of the web developers on the team)

Thoughts on how to approach?

答:
Some examples

Provide bugged code, and ask for explanation and solution.

General trouble shooting, for example, front end devs need to know about networking protocols, dream up a scenario.

Always space for a crazy question like " How many camels are in Egypt", and just see how they reason it out.

Take some similar code, and ask to compare, and reasons for their solution

If you are looking for insights on 'problem solving skills', you need to be a little abstract, take the candidate out of their comfort zone, and really make them think.

Good luck!


问:
Can I legally and ethically take an open-source project with community contributions to closed-source?
Let's say I start and develop some project under open-source license, and accept some community contributions. How shaky is the ground I stand on if I decide to take the project commercial and closed-source (or split license)?

This question doesn't directly address the issue of a project with community contributions, which feels like different territory, at least as far as ethics are concerned. Legally, this might be iffy as well, because I'm not sure whether contributions fall under my copyright, or whether the contributor hold the copyright to the part of the project he added.

Am I safe (ethically and legally) as long as I'm up front with the possibility that I may take the project commercial in the future?

答: Also, you may want adopt a model similar to Redhat's. Building closed source plugins but leaving the core open source. This can lead to better innovation as well since you will still get community support for a product that can benefit the open source community. Offering training, consulting, and support can also sweeten the deal for you.</p>


答:
As others have pointed out, many new technologies emerge to address new needs and therefore they make it easier to solve certain problems. Therefore you should keep up to date and at least know what is going in your field and understand which new technologies are relevant for you.

On the other hand, I think that sometimes there is also a hype factor in certain innovations: Some ideas are extremely old but only in recent years they are being pushed to become mainstream. Sometimes I have the impression that a new programming language (or a new version thereof) is pushed just because "new is better" and a new technology means new books, new programming tools, new compilers, new programming courses, or in other words, revenue.

So it can happen that you have to learn a new technology without seeing any real advantage wrt the technology you had been using before, otherwise you risk to be out of the market because your skills look old fashioned.
It is up to you to follow the development of new technologies and try to understand which ones can make you more productive, and which ones are just convenient to make your CV look better.

Bottom line: I think you should try to learn what you really find useful, regardless of whether it is new or old.


答:
Well it's probably due to the fact that you're a web developer and the technologies in that field are very volatile with languages, platforms, tools, and methodologies rising and falling in popularity. It's a field that is very VERY high level. If any of the layers beneath it are altered, that changes the position on top. And, frankly, it's new (ish). New fields have a lot of room for innovation.

Personally, I work on embedded devices, learned C, and that's worked pretty well for me.

But I'm still learning new things on a fairly regular basis. Sockets, SQL libraries, ncurses, objects in C. And methodologies are loosely coupled with technologies. Unit testing was taught horribly at my school, and I'm just now wrapping my head around it. I just heard about dependency injection the other day, and realized that's exactly how I solved my last problem with unit testing a console function.

Most programmers aren't factory workers that do the same thing every day. Those jobs can (and should) be automated away. Nobody pays for yet another bubble-sort implementation. It's been done.


问:
Best way to load application settings
A simple way to keep the settings of a Java application is represented by a text file with ".properties" extension containing the identifier of each setting associated with a specific value (this value may be a number, string, date, etc..). C# uses a similar approach, but the text file must be named "App.config". In both cases, in source code you must initialize a specific class for reading settings: this class has a method that returns the value (as string) associated with the specified setting identifier.

```<code>// Java example
Properties config = new Properties();
config.load(...);
String valueStr = config.getProperty("listening-port");
// ...

// C# example
NameValueCollection setting = ConfigurationManager.AppSettings;
string valueStr = setting["listening-port"];
// ...
</code>```

In both cases we should parse strings loaded from the configuration file and assign the converted values to the related typed objects (parsing errors could occur during this phase). After the parsing step, we must check that the setting values belong to a specific domain of validity: for example, the maximum size of a queue should be a positive value, some values may be related (example: min < max), and so on.

Suppose that the application should load the settings as soon as it starts: in other words, the first operation performed by the application is to load the settings. Any invalid values for the settings must be replaced automatically with default values: if this happens to a group of related settings, those settings are all set with default values.

The easiest way to perform these operations is to create a method that first parses all the settings, then checks the loaded values and finally sets any default values. However maintenance is difficult if you use this approach: as the number of settings increases while developing the application, it becomes increasingly difficult to update the code.

In order to solve this problem, I had thought of using the Template Method pattern, as follows.

```<code>public abstract class Setting
{
    protected abstract bool TryParseValues();

    protected abstract bool CheckValues();

    public abstract void SetDefaultValues();

    /// <summary>
    /// Template Method
    /// </summary>
    public bool TrySetValuesOrDefault()
    {
        if (!TryParseValues() || !CheckValues())
        {
            // parsing error or domain error
            SetDefaultValues();
            return false;
        }
        return true;
    }
}

public class RangeSetting : Setting
{
    private string minStr, maxStr;
    private byte min, max;

    public RangeSetting(string minStr, maxStr)
    {
        this.minStr = minStr;
        this.maxStr = maxStr;
    }

    protected override bool TryParseValues()
    {
        return (byte.TryParse(minStr, out min)
            && byte.TryParse(maxStr, out max));
    }

    protected override bool CheckValues()
    {
        return (0 < min && min < max);
    }

    public override void SetDefaultValues()
    {
        min = 5;
        max = 10;
    }
}
</code>```

The problem is that in this way we need to create a new class for each setting, even for a single value.
Are there other solutions to this kind of problem?

In summary:

Easy maintenance: for example, the addition of one or more parameters.

Extensibility: a first version of the application could read a single configuration file, but later versions may give the possibility of a multi-user setup (admin sets up a basic configuration, users can set only certain settings, etc..).

Object oriented design.

答:
Essentially the external configuration file is encoded as a YAML document. This is then parsed during application start up and mapped to a configuration object. </p>

<p>The final result is robust and above all simple to manage. </p>

Title: Best way to load application settings

Body:
Essentially the external configuration file is encoded as a YAML document. This is then parsed during application start up and mapped to a configuration object.

The final result is robust and above all simple to manage.

ContentLicense: CC BY-SA 4.0


答: In the Operating Systems section of the article, What Every Computer Science Major Should Know, Matt Might recommended Linux Kernel Development by Love. Although this is an advanced topic, the book is very well written.</p>

Title: How to understand Linux kernel source code for a beginner?

Body:
I am a student interested in working on Memory Management, particularly the page replacement component of the linux kernel.

What are the different guides that can help me to begin understanding the kernel source?

I have tried to read the book Understanding the Linux Virtual Memory Manager by Mel Gorman and Understanding the Linux Kernel by Cesati and Bovet, but they do not explain the flow of control through the code. They only end up explaining various data structures used and the work various functions perform. This makes the code more confusing.

My project deals with tweaking the page replacement algorithm in a mainstream kernel and analyse its performance for a set of workloads. Is there a flavor of the linux kernel that would be easier to understand (if not the linux-2.6.xx kernel)?


答: The best programmer I hired does not have a degree.  I have seen degree qualified candidates, supposedly experienced in embedded programming, that could not test a bit in a register or understand an interrupt function.</p>

Title: B.A Computer Science Vs B.S Inf Tech?

Body:
Would a recruiter prefer a B.A in Comp Science from a more prestigious university or a B.S in Inf Tech from just an average university? Would it matter for someone already established in the field with plenty of experience?

The only difference in the B.A and B.S is essentially the mathematics.  The B.S is geared for those going on to master's programs, although one isn't excluded from going on to a masters program with a BA, many do require more mathematics.

Just for those curious, the information tech degree is typically geared more to real-world problems then the computer science and the quality of it will vary widely. Some inf tech programs are as in-depth as an ABET C.S degree, the information tech from Drexel looks extremely strong. The Management Information Systems is generally provided via the business school and is more of a traditional business degree.

I'm not sure really how well versed the recruiters/g.p are in the actual differences in all of these programs. Some non ABET BS Comp Science may only require 1 or 2 Calculus versus the ABET certified programs.


问:
Expected behavior when an request for a collection will have zero items
Let's say you are given the following...

```<code>List<Thing> theThings = fubar.Things.All();
</code>```

If there were nothing to return, what would you expect fubar.Things.All() to return?

Edit:
Thanks for the opinions. I'll wait a bit and accept the entry with the most ups.

I agree with the responses so far, particularly those suggesting an empty collection. A vendor provided an API with several calls similar to the example above. A vendor who did $4.6 million in revenue via their API(s) last year, BTW. They do something I fundamentally disagree with -- they throw an exception.

答: I would expect an empty list. theThings would still be an object, but theThings.Count or theThings.size() would return 0.


答:
Of the two possibilities (i.e. returning a null or returning an empty collection) I would pick returning an empty collection, because it lets the caller to skip a check of the returned value. Instead of writing this

```<code>List<Thing> theThings = fubar.Things.All();
if (theThings != null) {
    for (Thing t : theThings) {
        t.doSomething();
    }
}
</code>```

they would be able to write this:

```<code>List<Thing> theThings = fubar.Things.All();
for (Thing t : theThings) {
    t.doSomething();
}
</code>```

This second code fragment is shorter and easier to read, because the nesting level is lower by one.

Title: Expected behavior when an request for a collection will have zero items

Body:
Let's say you are given the following...

```<code>List<Thing> theThings = fubar.Things.All();
</code>```

If there were nothing to return, what would you expect fubar.Things.All() to return?

Edit:
Thanks for the opinions. I'll wait a bit and accept the entry with the most ups.

I agree with the responses so far, particularly those suggesting an empty collection. A vendor provided an API with several calls similar to the example above. A vendor who did $4.6 million in revenue via their API(s) last year, BTW. They do something I fundamentally disagree with -- they throw an exception.

Body:
Of the two possibilities (i.e. returning a null or returning an empty collection) I would pick returning an empty collection, because it lets the caller to skip a check of the returned value. Instead of writing this

List<Thing> theThings = fubar.Things.All();
if (theThings != null) {
    for (Thing t : theThings) {
        t.doSomething();
    }
}

they would be able to write this:

List<Thing> theThings = fubar.Things.All();
for (Thing t : theThings) {
    t.doSomething();
}

This second code fragment is shorter and easier to read, because the nesting level is lower by one.


答: I would return an empty collection over returning a null value because that way you can avoid writing a null verification in the calling code.</p>


答:
You should, IMHO, return a EMPTY value.
I don't know about C#, but in Java we have this:

```<code>  List list = Collections.EMPTY_LIST;
  Set set = Collections.EMPTY_SET;
  Map map = Collections.EMPTY_MAP;

  // For the type-safe
  List<String> s = Collections.emptyList();
  Set<Long> l = Collections.emptySet();
  Map<Date> d = Collections.emptyMap();
</code>```

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html

Body:
You should, IMHO, return a EMPTY value.
I don't know about C#, but in Java we have this:

  List list = Collections.EMPTY_LIST;
  Set set = Collections.EMPTY_SET;
  Map map = Collections.EMPTY_MAP;

  // For the type-safe
  List<String> s = Collections.emptyList();
  Set<Long> l = Collections.emptySet();
  Map<Date> d = Collections.emptyMap();

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html


答:
Design issues like that are addressed by Null Object pattern

...Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

For example, a function may retrieve a list of files in a directory and perform some action on each. In the case of an empty directory, one response may be to throw an exception or return a null reference rather than a list. Thus, the code which expects a list must verify that it in fact has one before continuing, which can complicate the design...

Suggestion particularly applicable in your case (returning List when there are no Things) is:

...By returning a null object (i.e. an empty list) instead, there is no need to verify that the return value is in fact a list. The calling function may simply iterate the list as normal, effectively doing nothing. It is, however, still possible to check whether the return value is a null object (e.g. an empty list) and react differently if desired.


问:
Are there deprecated practices for multithread and multiprocessor programming that I should no longer use?
In the early days of FORTRAN and BASIC, essentially all programs were written with GOTO statements.  The result was spaghetti code and the solution was structured programming.

Similarly, pointers can have difficult to control characteristics in our programs.  C++ started with plenty of pointers, but use of references are recommended.  Libraries like STL can reduce some of our dependency.  There are also idioms to create smart pointers that have better characteristics, and some version of C++ permit references and managed code.

Programming practices like inheritance and polymorphism use a lot of pointers behind the scenes (just as for, while, do structured programming generates code filled with branch instructions).  Languages like Java eliminate pointers and use garbage collection to manage dynamically allocated data instead of depending on programmers to match all their new and delete statements.

In my reading, I have seen examples of multi-process and multi-thread programming that don't seem to use semaphores.  Do they use the same thing with different names or do they have new ways of structuring protection of resources from concurrent use?

For example, a specific example of a system for multithread programming with multicore processors is OpenMP.  It represents a critical region as follows, without the use of semaphores, which seem not to be included in the environment.

```<code>th_id = omp_get_thread_num();
#pragma omp critical
{
  cout << "Hello World from thread " << th_id << '\n';
}
</code>```

This example is an excerpt from: http://en.wikipedia.org/wiki/OpenMP

Alternatively, similar protection of threads from each other using semaphores with functions wait() and signal() might look like this:

```<code>wait(sem);
th_id = get_thread_num();
cout << "Hello World from thread " << th_id << '\n';
signal(sem);
</code>```

In this example, things are pretty simple, and just a simple review is enough to show the wait() and signal() calls are matched and even with a lot of concurrency, thread safety is provided.  But other algorithms are more complicated and use multiple semaphores (both binary and counting) spread across multiple functions with complex conditions that can be called by many threads.  The consequences of creating deadlock or failing to make things thread safe can be hard to manage.

Do these systems like OpenMP eliminate the problems with semaphores?

Do they move the problem somewhere else?

How do I transform my favorite semaphore using algorithm to not use semaphores anymore?

答:
I think this is mostly about levels of abstraction. Quite often in programming, it is useful to abstract away some details in a way that is safer or more readable or something like that.

This applies to control structures: ifs, fors and even try-catch blocks are just abstractions over gotos. These abstractions are almost always useful, because they make your code more readable. But there are cases when you will still need to use goto (e.g. if you're writing assembly by hand).

This also applies to memory management: C++ smart pointers and GC are abstractions over raw pointers and manual memory de-/allocation. And sometimes, these abstractions are not appropriate, e.g. when you really need maximum performance.

And the same applies to multi-threading: things like futures and actors are just abstractions over threads, semaphors, mutexes and CAS instructions. Such abstractions can help you make your code much more readable and they also help you avoid errors. But sometimes, they are simply not appropriate.

You should know what tools you have available and what are their advantages and disadvantages. Then you can choose the correct abstraction for your task (if any). Higher levels of abstraction don't deprecate lower levels, there will be always some cases where the abstraction is not appropriate and the best choice is to use the “old way”.