问:
Why Use !boolean_variable Over boolean_variable == false
A comment on this question: Checking if a method returns false: assign result to temporary variable, or put method invocation directly in conditional? says that you should use !boolean instead of boolean == false when testing conditions. Why? To me boolean == false is much more natural in English and is more explicit. I apologise if this is just a matter of style, but I was wondering if there was some other reason for this preference of !boolean?

答:
if (!boolean_variable) translates to if the condition is not true.

if (boolean == false) translates to if the condition not false is true. Because that is inversed logic, it is harder to understand.


答: because sometimes you might write boolean = false (with the obvious errors) and false == boolean doesn't seem natural (no matter how good of a practice it is)

ContentLicense: CC BY-SA 3.0

Title: Why Use !boolean_variable Over boolean_variable == false

Body: A comment on this question: Checking if a method returns false: assign result to temporary variable, or put method invocation directly in conditional? says that you should use !boolean instead of boolean == false when testing conditions. Why? To me boolean == false is much more natural in English and is more explicit. I apologise if this is just a matter of style, but I was wondering if there was some other reason for this preference of !boolean?


答:
At work I often am dealing with Booleans which can be null so I'll often code this case as

if (value != null && value == true) {
        //do something
}
```

because I personally feel the symmetry makes it easier to read. Especially if there are other Booleans being tested as well.

I don't really care one way or the other.

Body:
At work I often am dealing with Booleans which can be null so I'll often code this case as

if (value != null && value == true) {
        //do something
}

because I personally feel the symmetry makes it easier to read. Especially if there are other Booleans being tested as well.

I don't really care one way or the other.

ContentLicense: CC BY-SA 4.0


答:
When I see a line like  if (!lateForMeeting()), I read that as "If not late for meeting", which is quite straight-forward to understand, as opposed to if (lateForMeeting() == false) which I'd read as "If the fact that I'm late for meeting is false".

They're identical in meaning, but the former is closer to how the equivalent English sentence would be constructed.


答:
Writing == false and == true is redundant. It can be taken to arbitrary extremes, too. If you start writing

if (condition == false) { ... }
```

<p>Then why not</p>

<pre class="lang-c prettyprint-override"><code>if ((condition == false) == true) { ... }
</code>```

Or why not

if ((someExp == anotherExp) == true) { ... }
```

The moral of this story is that if condition is a boolean expression, then you don't need to add == false; that's what operator ! is for ;)

Body:
Writing == false and == true is redundant. It can be taken to arbitrary extremes, too. If you start writing

if (condition == false) { ... }

Then why not

if ((condition == false) == true) { ... }

Or why not

if ((someExp == anotherExp) == true) { ... }

The moral of this story is that if condition is a boolean expression, then you don't need to add == false; that's what operator ! is for ;)


答: When I see var == false I always wonder whether var is boolean or of a logic type with more than two values (with, for example, a maybe and an undefined as well as true and false, or something like the nine values of IEEE 1164).


答:
The two are functionally identical, so which one to use is a matter of taste.

The major reason that I use == false is that I have found that !is too easy to overlook, when looking at code.

Having been bitten severely by this, I've made a habit of making it very clear when testing for false.

Had the operator been named not as in Pascal, I do not think this would have become an issue.


答:
Size matters ;)

In mixed expressions it is easier to read:

```<code>boolean1 = false
boolean2 = true

p ! boolean1 and ! boolean2
p boolean1 == false and boolean2 == false
</code>```

And especial for ruby an example where it is a big difference:

```<code>boolean = nil
p ! boolean         #-> true
p boolean == false  #-> false
</code>```

nil is not false, but it is also not true.

Body:
Size matters ;)

In mixed expressions it is easier to read:

boolean1 = false
boolean2 = true

p ! boolean1 and ! boolean2
p boolean1 == false and boolean2 == false

And especial for ruby an example where it is a big difference:

boolean = nil
p ! boolean         #-> true
p boolean == false  #-> false

nil is not false, but it is also not true.


答:
When you're testing the true condition, it makes sense to do just if (condition), especially when you apply the convention of naming boolean variables beginning with 'is': if (isOpen) is perfectly clear and using != false would be redundant.

For a C/C++/Java/etc. programmer, the meaning of the '!' operator is completely assimilated, to the point that we automatically have 'not' in our minds when we see it. So having if (!isOpen) is as clear as if (_NOT_ isOpen) for me. But you're not familiar enough, in C/C++ you could create a macro with #define _NOT_ !. But trust me, after a few years this is completely unnecessary.

Aside that, it's always preferable to test boolean values without comparing them with literals. For instance, it's dangerous to test if (x == true) because a boolean value is considered true if it's not zero, and the literal true has just one specific value, so x could be 'true' (i.e. nonzero) and still the comparision evaluate to false (because it contains 2 and the literal true is, say, 1.) Of course that doesn't apply to a comparision with false, but if you don't use it when testing for true, why use it when testing for false?


问:
Checking if a method returns false: assign result to temporary variable, or put method invocation directly in conditional?
Is it a good practice to call a method that returns true or false values in an if statement?

Something like this:

private void VerifyAccount()
{
    if (!ValidateCredentials(txtUser.Text, txtPassword.Text))
    {
        MessageBox.Show("Invalid user name or password");
    }
}

private bool ValidateCredentials(string userName, string password)
{
    string existingPassword = GetUserPassword(userName);
    if (existingPassword == null)
        return false;

    var hasher = new Hasher { SaltSize = 16 };
    bool passwordsMatch = hasher.CompareStringToHash(password, existingPassword);

    return passwordsMatch;
}
```

<p>or is it better to store them in a variable then compare them using if else values like this</p>

<pre class="lang-.NET prettyprint-override"><code>bool validate = ValidateCredentials(txtUser.Text, txtPassword.Text);
if(validate == false){
    //Do something
}
</code>```

I am not only referring to .NET, I am referring to the question in all programming languages it just so happens that I used .NET as an example

答:
Let see...

Because it's all about KISS, there's no need to create an additional variable when you can do without it. Also, there's no need to type more... when there's no need.

But then because you DRY, if you were later calling ValidateCredentials and find yourself typing ValidateCredentials(txtUser.Text, txtPassword.Text) you know you should have created an additional variable.


问:
If competition is using 'lingua obscura' for development (why) should I be worried?
I was reading Paul Graham's essay - Beating The Averages (2003) and here's what he had to say:

The more of an IT flavor the job descriptions had, the less dangerous
  the company was. The safest kind were the ones that wanted Oracle
  experience. You never had to worry about those. You were also safe if
  they said they wanted C++ or Java developers. If they wanted Perl or
  Python programmers, that would be a bit frightening-- that's starting
  to sound like a company where the technical side, at least, is run by
  real hackers

Now, this is a dated essay. However, I fail to see how using a non-commonplace language (C/C++/Java, C#) would be 'less dangerous'. If the programmers of an organization are very fluent with the development language they should be equally adept at cranking out code at a decent pace. In fact if you do use a non-commonplace language won't maintenance/enhancement problems hit you in the face since not too many programmers would be available, in the long run?

For making quick-n-dirty systems I agree, that some languages allow you to take off relatively sooner than others. But does Paul Graham's essay/comment make sense in 2012 and beyond? If a startup were to use typical IT languages for development, why should it's competition be less worried?

I fail to see how the language itself makes a difference. IMHO it's the developers experience with the language that matters and the availability of frameworks so that you DRY (do not repeat yourself) not just coding in a particular language.

What is it that I'm missing? Does it imply that startups better choose non IT-flavored languages (even if the developers may be extremely adept at them)? What are the (programming) economic/market-forces behind this claim?

PS: 'lingua obscura' is not meant to hurt anyone's feelings :)

答:
If your customers are not locked in, then yes.  You should be worried about competitors using powerful languages.

Java, C#, C++, are comparatively verbose, and have relatively slow edit/test cycles.  This limits the speed that even the fastest developers can deliver features.  More expressive languages, with powerful meta-programming built-in, and zero compile time, allow expert developers to build features as fast as possible.  If you are in a race for market share, with a huge reward to the winner, it makes sense to hire the very best developers you can find, and use whatever language will let them go fastest.  You can worry about scalability later.


答:
I view PG's comments more about attitude than specifics of the language.  People with an internal IT mindset play it safe.  They use low risk technologies,have processes to minimize risk and take the low risk strategy.  They are too busy worrying about their own lunch to eat yours.

People on the bleeding edge (python 2003) are ones to be worried about.  They are hungry.  They take risks.  They are intellectually curious.  The same type of person staying up late learning an exciting new language is the type who might upend your industry before you do.

Title: If competition is using 'lingua obscura' for development (why) should I be worried?

Body:
I was reading Paul Graham's essay - Beating The Averages (2003) and here's what he had to say:

The more of an IT flavor the job descriptions had, the less dangerous
  the company was. The safest kind were the ones that wanted Oracle
  experience. You never had to worry about those. You were also safe if
  they said they wanted C++ or Java developers. If they wanted Perl or
  Python programmers, that would be a bit frightening-- that's starting
  to sound like a company where the technical side, at least, is run by
  real hackers

Now, this is a dated essay. However, I fail to see how using a non-commonplace language (C/C++/Java, C#) would be 'less dangerous'. If the programmers of an organization are very fluent with the development language they should be equally adept at cranking out code at a decent pace. In fact if you do use a non-commonplace language won't maintenance/enhancement problems hit you in the face since not too many programmers would be available, in the long run?

For making quick-n-dirty systems I agree, that some languages allow you to take off relatively sooner than others. But does Paul Graham's essay/comment make sense in 2012 and beyond? If a startup were to use typical IT languages for development, why should it's competition be less worried?

I fail to see how the language itself makes a difference. IMHO it's the developers experience with the language that matters and the availability of frameworks so that you DRY (do not repeat yourself) not just coding in a particular language.

What is it that I'm missing? Does it imply that startups better choose non IT-flavored languages (even if the developers may be extremely adept at them)? What are the (programming) economic/market-forces behind this claim?

PS: 'lingua obscura' is not meant to hurt anyone's feelings :)


答:
Graham means less dangerous to him as a competitor, not merely less dangerous.  His point is not that Java (or C++ in 2003, or COBOL in 1980) is less dangerous, but rather that it is normal, and that there is a good probability that companies searching for such skills are merely-average competitors.  But companies that are looking for strong talent in obscure (or, more correctly, higher-powered-and-less-well-known) languages are companies to watch.

And yes, it makes perfect sense today.  It made perfect sense long before Graham wrote it, we just didn't talk about Java in those days.


答:
The choice of language is hard for a startup. Plenty of very good startups choose "common" languages for speed of getting to market, familiarity of the founder and ease of future hiring.

Choosing the a lesser used language does sent out good signs. It says you are prepared to take development seriously and try hard to hire specialized programmers. Those are just signals though, a startup is more than just it's choose in language.

Bottom line is your choice in language should be evaluated properly in your context. Facebook for example did ok using php which is not generally considered a very scalable language


答: The choice of an obscure language would indicate uncommon technical self-confidence in a startup. A company willing to abandon common wisdom might know something about software development that most companies do not. Then again, they might just be wankers.</p>


答:
An average developer uses average tools, because he doesn’t see the value of more powerful ones:

“As long as our hypothetical Blub programmer is looking down the power continuum, he knows he's looking down. Languages less powerful than Blub are obviously less powerful, because they're missing some feature he's used to. But when our hypothetical Blub programmer looks in the other direction, up the power continuum, he doesn't realize he's looking up. What he sees are merely weird languages. He probably considers them about equivalent in power to Blub, but with all this other hairy stuff thrown in as well. Blub is good enough for him, because he thinks in Blub.”—Paul Graham, Beating the Averages.

(Emphasis mine.)

The more powerful the language, the fewer developers are going to use it, and the less common it will be. Popularity is thus a good metric of how far the power of a language is from the average. The more obscure the language, the better the chance that the developer using it knows what he’s doing, and has chosen it for a good reason over its run-of-the-mill peers—and a savvy competitor is a dangerous one.


答:
In C and some similar languages, comparing boolean expressions for equality to false or true is a dangerous habit.

In C any scalar expression (numeric or pointer) can be used in a boolean context, for example as the condition of an if statement.  The C rule is that if (cond) is equivalent to if (cond != 0) -- i.e., zero is false, and any non-zero value is true.  If cond is of pointer type, 0 is treated as a null pointer constant; if (ptr) means if (ptr != NULL).

This means that

if (cond)
```
<p>and</p>
<pre class="lang-c prettyprint-override"><code>if (cond == true)
</code>```

do not mean the same thing.  The first is true if cond is non-zero; the second is true only if it's equal to true, which in C (if you have #include <stdbool.h>) is simply 1.

For example, the isdigit() function declared in <ctype.h> returns an int value: non-zero if the argument is a digit, 0 if it isn't a digit.  It can return 42 to indicate that the condition is true.  Comparing 42 == true will fail.

It happens that 0 is the only value considered to be false, so comparison for equality to false will work; if (!cond) and if (cond == false) do the same thing.  But if you're going to take advantage of that, you have to remember that comparing to false is ok, and comparing to true is not.  Worse yet, comparing to true will work most of the time (for example, the equality and relational operators always yield either 0 or 1).  This means that any bugs you introduce by using this still could be difficult to track down.  (Don't worry, they'll show up as soon as you demo the code to an important client.)

C++ has slightly different rules; for example, its bool type is a bit more tightly integrated into the language, and if (cond) converts cond to type bool.  But the effect is (mostly) the same.

Some other languages have what one might call better behaved booleans, such that cond == true and cond == false (or whatever the syntax happens to be) is safe.  Even so, every language I've seen has a not or ! operator; it's there, so you might as well use it.  Using cond == false rather than !cond or not cond does not, in my opinion, improve readability.  (It's true that the ! character can be difficult to see at a glance; I sometimes add a space after the ! to avoid this.)

And often you can avoid the issue and improve clarity by rearranging the code slightly.  For example, rather than:

if (!cond) {
    do_this();
}
else {
    do_that();
}
```
<p>you might write:</p>
<pre class="lang-c prettyprint-override"><code>if (cond) {
    do_that();
}
else {
    do_this();
}
</code>```

That's not always better, but it doesn't hurt to look for opportunities where it is.

Summary: In C and C++, equality comparisons to true and false are dangerous, overly verbose, and poor style.  In many other languages, such comparisons might not be dangerous, but they're still overly verbose and poor style.

Body:
In C and some similar languages, comparing boolean expressions for equality to false or true is a dangerous habit.

In C any scalar expression (numeric or pointer) can be used in a boolean context, for example as the condition of an if statement.  The C rule is that if (cond) is equivalent to if (cond != 0) -- i.e., zero is false, and any non-zero value is true.  If cond is of pointer type, 0 is treated as a null pointer constant; if (ptr) means if (ptr != NULL).

This means that

if (cond)

and

if (cond == true)

do not mean the same thing.  The first is true if cond is non-zero; the second is true only if it's equal to true, which in C (if you have #include <stdbool.h>) is simply 1.

For example, the isdigit() function declared in <ctype.h> returns an int value: non-zero if the argument is a digit, 0 if it isn't a digit.  It can return 42 to indicate that the condition is true.  Comparing 42 == true will fail.

It happens that 0 is the only value considered to be false, so comparison for equality to false will work; if (!cond) and if (cond == false) do the same thing.  But if you're going to take advantage of that, you have to remember that comparing to false is ok, and comparing to true is not.  Worse yet, comparing to true will work most of the time (for example, the equality and relational operators always yield either 0 or 1).  This means that any bugs you introduce by using this still could be difficult to track down.  (Don't worry, they'll show up as soon as you demo the code to an important client.)

C++ has slightly different rules; for example, its bool type is a bit more tightly integrated into the language, and if (cond) converts cond to type bool.  But the effect is (mostly) the same.

Some other languages have what one might call better behaved booleans, such that cond == true and cond == false (or whatever the syntax happens to be) is safe.  Even so, every language I've seen has a not or ! operator; it's there, so you might as well use it.  Using cond == false rather than !cond or not cond does not, in my opinion, improve readability.  (It's true that the ! character can be difficult to see at a glance; I sometimes add a space after the ! to avoid this.)

And often you can avoid the issue and improve clarity by rearranging the code slightly.  For example, rather than:

if (!cond) {
    do_this();
}
else {
    do_that();
}

you might write:

if (cond) {
    do_that();
}
else {
    do_this();
}

That's not always better, but it doesn't hurt to look for opportunities where it is.

Summary: In C and C++, equality comparisons to true and false are dangerous, overly verbose, and poor style.  In many other languages, such comparisons might not be dangerous, but they're still overly verbose and poor style.


答: Go ask the best and worst programmers you know, by whatever criteria you like, what other languages they know.  Now write a job ad to attract the former, and you have your answer.  Even if your app is in C++, you're going to get a better class of programmers if you hire ones who know languages that aren't taught in school. </p>


答:
Expanding a bit on the readability issue ...

I can think of two good reasons to store the result in a variable:

If you're going to be using the condition more than once, saving it in a variable means you only have to call the function once.  (This assumes that the stored value is still valid; if you need to re-test it, of course this doesn't apply.)

If storing it in a variable improves readability by giving the condition a name that's more meaningful than what you see in the function call.

For example, this:

```<code>bool foo_is_ok = is_ok(foo);
if (foo_is_ok) ...
</code>```

doesn't help readability, but this:

```<code>bool done_processing = feof(file1) && feof(file2);
if (done_processing) ...
</code>```

probably does, since it's not immediately obvious that feof(file1) && feof(file2) means that we're done processing.

The passwordsMatch variable in the question is probably a better example than mine.

Single-use variables are useful if they give a meaningful name to some value.  (This is of course for the benefit of the human reader.)

Title: Checking if a method returns false: assign result to temporary variable, or put method invocation directly in conditional?

Body:
Is it a good practice to call a method that returns true or false values in an if statement?

Something like this:

private void VerifyAccount()
{
    if (!ValidateCredentials(txtUser.Text, txtPassword.Text))
    {
        MessageBox.Show("Invalid user name or password");
    }
}

private bool ValidateCredentials(string userName, string password)
{
    string existingPassword = GetUserPassword(userName);
    if (existingPassword == null)
        return false;

    var hasher = new Hasher { SaltSize = 16 };
    bool passwordsMatch = hasher.CompareStringToHash(password, existingPassword);

    return passwordsMatch;
}
```

<p>or is it better to store them in a variable then compare them using if else values like this</p>

<pre class="lang-.NET prettyprint-override"><code>bool validate = ValidateCredentials(txtUser.Text, txtPassword.Text);
if(validate == false){
    //Do something
}
</code>```

I am not only referring to .NET, I am referring to the question in all programming languages it just so happens that I used .NET as an example

Body:
Expanding a bit on the readability issue ...

I can think of two good reasons to store the result in a variable:

If you're going to be using the condition more than once, saving it in a variable means you only have to call the function once.  (This assumes that the stored value is still valid; if you need to re-test it, of course this doesn't apply.)

If storing it in a variable improves readability by giving the condition a name that's more meaningful than what you see in the function call.

For example, this:

bool foo_is_ok = is_ok(foo);
if (foo_is_ok) ...

doesn't help readability, but this:

bool done_processing = feof(file1) && feof(file2);
if (done_processing) ...

probably does, since it's not immediately obvious that feof(file1) && feof(file2) means that we're done processing.

The passwordsMatch variable in the question is probably a better example than mine.

Single-use variables are useful if they give a meaningful name to some value.  (This is of course for the benefit of the human reader.)


问:
Shouldn't MVC be MCV?
The model is defined first, then the controllers are fired based on the user request, and they will generate the views (the output).

So it should be M->C->V, right?

答: Maybe it comes down to dependancies and usage?  Each item on the right knows about or uses  the item on the left.  Controller knows about views and models.  Views know about Models.  Models just know about themselves.  So hence the naming convention MVC.  Just my thoughts.</p>

Title: Shouldn't MVC be MCV?


问:
Why doesn't Python need a compiler?
Just wondering (now that I've started with C++ which needs a compiler) why Python doesn't need a compiler?

I just enter the code, save it as an exec, and run it. In C++ I have to make builds and all of that other fun stuff.

答:
Python is an interpreted language. This means that there is software on your computer that reads the Python code, and sends the "instructions" to the machine. The Wikipedia article on interpreted languages might be of interest.

When a language like C++ (a compiled language) is compiled, it means that it is converted into machine code to be read directly by the hardware when executed. The Wikipedia article on compiled languages might provide an interesting contrast.

Title: Why doesn't Python need a compiler?


答:
Python has a compiler! You just don't notice it because it runs automatically. You can tell it's there, though: look at the .pyc (or .pyo if you have the optimizer turned on) files that are generated for modules that you import.

Also, it does not compile to the native machine's code. Instead, it compiles to a byte code that is used by a virtual machine. The virtual machine is itself a compiled program. This is very similar to how Java works; so similar, in fact, that there is a Python variant (Jython) that compiles to the Java Virtual Machine's byte code instead! There's also IronPython, which compiles to Microsoft's CLR (used by .NET). (The normal Python byte code compiler is sometimes called CPython to disambiguate it from these alternatives.)

C++ needs to expose its compilation process because the language itself is incomplete; it does not specify everything the linker needs to know to build your program, nor can it specify compile options portably (some compilers let you use #pragma, but that's not standard). So you have to do the rest of the work with makefiles and possibly auto hell (autoconf/automake/libtool). This is really just a holdover from how C did it. And C did it that way because it made the compiler simple, which is one main reason it is so popular (anyone could crank out a simple C compiler in the 80's).

Some things that can affect the compiler's or linker's operation but are not specified within C or C++'s syntax:

dependency resolution

external library requirements (including dependency order)

optimizer level

warning settings

language specification version

linker mappings (which section goes where in the final program)

target architecture

Some of these can be detected, but they can't be specified; e.g. I can detect which C++ is in use with __cplusplus, but I can't specify that C++98 is the one used for my code within the code itself; I have to pass it as a flag to the compiler in the Makefile, or make a setting in a dialog.

While you might think that a "dependency resolution" system exists in the compiler, automatically generating dependency records, these records only say which header files a given source file uses. They cannot indicate what additional source code modules are required to link into an executable program, because there is no standard way in C or C++ to indicate that a given header file is the interface definition for another source code module as opposed to just a bunch of lines you want to show up in multiple places so you don't repeat yourself. There are traditions in file naming conventions, but these are not known or enforced by the compiler and linker.

Several of these can be set using #pragma, but this is non-standard, and I was speaking of the standard. All of these things could be specified by a standard, but have not been in the interest of backward compatibility. The prevailing wisdom is that makefiles and IDEs aren't broke, so don't fix them.

Python handles all this in the language. For example, import specifies an explicit module dependency, implies the dependency tree, and modules are not split into header and source files (i.e. interface and implementation).

Title: Why doesn't Python need a compiler?

Body:
Just wondering (now that I've started with C++ which needs a compiler) why Python doesn't need a compiler?

I just enter the code, save it as an exec, and run it. In C++ I have to make builds and all of that other fun stuff.


答:
Yes this should be MCV but many acronyms are made in wrong order just because they sound better that way.</p>

```<code>AmVeeSee  (more fluent)
AmSeeVee  (less fluent)
</code>```

Title: Shouldn't MVC be MCV?

Body:
The model is defined first, then the controllers are fired based on the user request, and they will generate the views (the output).

So it should be M->C->V, right?

Body:
Yes this should be MCV but many acronyms are made in wrong order just because they sound better that way.

AmVeeSee  (more fluent)
AmSeeVee  (less fluent)


答:
Because that's how the originator of the term ordered it.

"MVC was first described in 1979[3] by Trygve Reenskaug, then working on Smalltalk at Xerox PARC."

http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Title: Shouldn't MVC be MCV?


问:
Is this a proper implementation of an iOS MVC pattern?
After browsing the apple docs, I came across this sample of their MVC pattern:

Using NSNotificationCenter and without using KVO, would this diagram below represent a correct implementation of the MVC pattern?  If not, what’s wrong and how can it be corrected or improved?

App starts with the left light set to on, and the right one off.  Only one light may be on at a time.

Users presses the right switch, which sends a target action to the view controller.

The view controller receives the message, and send a message to the right light data model.

The right light uses NSNotificationCenter to notify the controller the right light has changed.

The controller receives the message, and performs the following method

BOOL rightLightOn = [rightLightData on];
    if( rightLightOn )
    {
      [rightLightImage setImage:onImage];
      [leftLightSwitch setOn:NO];
    }
    else
    {
      [rightLightImage setImage:offImage];
    }

The switch change causes the UISwitch to call the method “leftSwitchChanged” in the controller.

The controller receives the message, and send a message to the left light data model.

The left light uses NSNotificationCenter to notify the controller the left light has changed.

The controller receives the message, and again performs the same method shown above, but modified for the right light.

In addition, what if the system wasn’t using a switch, and instead was using a UIButton that displayed the text, “Turn On” or “Turn Off.”  Would the switch update it’s own text, then call “rightSwitchChanged” or would it call rightSwitchChanged immediately and wait for the view controller to change the text?

答:
Yes it fits the pattern. But...

I'm not a fan of notifications in iOS. In fact in many cases they are used as glorified gotos.

If you call [model setLightOn] why would the model need to send you a notification back that the light is on?  It's on!

One other nit-picky comment: setLightOn is a poor name.  setLightOn:NO - does this turn the light off or just ignore the message?


答:
In (much) older compilers, I believe they would break (boolean == false) into 2 register assignments and a compare code in machine language. The first example would be broken into one assignment and a NOT operator. In terms of performance, the compare operation would take a number of clock cycles, depending on the size of the register being compared, compared to a bitwise invert (1 clock) and would be slower to execute.

That being said, I believe newer compilers do away with this, so it should be OK to go with either.


问:
Places to store basic data
I am using PHP.

I'm building a fully modular CMS, which is destined for the public. Some people might view this as a framework, but I intend to write a set of extensions for it, extensions that will make it a CMS :P

Because it's completely modular I have a problem figuring out how to load extensions.

Practically I need to get the list of active extensions, so I can load them inside my base class. I load them by reading some file headers, which contain a "dependency" field. That field decides the order in which I have to instantiate the objects.

The problem is that when the CMS starts I have no database interface, because that's an extension too, so I can't store the active extensions list in the database :)

You might ask how are extensions activated in the first place. Well - in the administration interface, which is an extension as well (obviously on first install of the CMS there will be some extensions active by default).

Could writing that list inside a text file be a solution? The problem is that a lot of hosts are not very nice with scripts when they write files. And since this CMS is public I might have a problem here?

答:
"(obviously on first install of the CMS there will be some extensions active by default)."

Isn't this the answer?  Your app has to have some core functionality before it's extended.  A mechanism to retain the configured extensions and to discover or add additional extensions is essential.  If you want to maintain the ability to replace both the data store and the process which loads extensions with other extensions, you will still need that bootstrap extension loader as part of your base functionality.

Title: Places to store basic data


答:
Based from my experience and the answers from my quesion that you have linked to.

Some people prefer to use if(condition), for the reason is that one it is shorter to write. and for me it actually makes sense, for example (! isValidated()) I read this as Not Validated. but for me it's all based on personal preferences, and it depends on the logical structure of isValidated() method, if it either returns true or false


问:
Should I learn a programming language before I attend college for Computer Engineering?
I've dipped my toes in C++ programming but I haven't actually delved into it.  I want to know if I actually need to learn it or any other languages before I go to college for Computer Engineering or am I just going to learn it at school anyway?</p>

答:
I'll share my own experience.

I started programming about 10-11 months ago. My first real exposure to it was with PHP, but afterwards, I found myself learning C# in an introductory course (CS 140) at my local community college. After I learned the basics, I pretty much flew with it and haven't stopped since. After C#, I decided to start learning the lower level mechanics of how computers worked. I'm working on an application which is supposed to be multi-platform, and is supposed to help video game engines to interact with each other (similar to SDL, but possibly more lower level than that, with a strict focus on GUI, mathematics, and other helper functions).

Basically, if it wasn't for that class, I wouldn't have found what I loved until much, much later. You don't really know that you enjoy programming until you really understand the concepts behind it. If you want to find out, I'd recommend picking up an intro to programming book and start with C/C++ since you need to understand what you're doing, rather than using a language which will hold your hand like Java or C# or just some scripting language - mind you, these have their place and are good tools to use, but it's also very imperative that you understand the lower-level concepts in the beginning. This was a mistake I made in the beginning.

After that, keep programming if you enjoy it. If not, learn something else. Whatever it is you decide to do, you should be spending as much time as you can on it before you attend some 2-4 year university to learn it, as it will REALLY keep you ahead of the game. It will also show motivation to any employer who potentially could hire you.

I can tell you that computer science/electrical engineering disciplines are by far the fastest in terms of their evolution rates (which keep increasing year-by-year), and you're going to have to keep learning new technologies to keep up with what's the latest and greatest (which you should find at least somewhat interesting, though it really depends on what area of expertise you're specializing in. For example, I hate web programming, and I'm not interested at all in the technologies that exist for it, but some people really enjoy it and ARE interested in it). Despite this, C/C++ are great languages to learn as, while many other languages (e.g. C#, Java), have their own prebuilt APIs to "make life easier", you're not going to learn a damn thing about what's really happening under the hood until you "roll with the hard knocks" (this may or may not include learning assembly at some point - it really depends on what you're going to be doing). In other words, the more you learn about operating systems and lower level architecture on your own ,the more valuable you are as a programmer. This includes learning concepts such as Linked Lists, or Binary Search Trees and various other algorithms.

Basically, I've been programming for 10-11 months and I haven't attended any university one bit. I've taken a C# class at a community college (my first programming class, which taught me the fundamentals), and at least 95% of the rest I've learned on my own. This is because, after taking that class, I knew I wanted to be a programmer. You'll know it once you come to understand it. Either path you choose, you should be studying it independently if you really want to be successful at it, because it increases your aptitude for motivation and commitment. A programmer has to be motivated to succeed. They deal with a lot, more than just simply "writing code". An application constantly has to be tested, debugged, and understood from the ground up. Typically, whether small or large, you're almost going to be learning something new for every project you undertake. This is a good thing, because you need to keep that brain active.


问:
What are good reasons to use explicit interface implementation for the sole purpose of hiding members?
During one of my studies into the intricacies of C#, I came across an interesting passage concerning explicit interface implementation.

While this syntax is quite helpful when you need to resolve name clashes,
    you can use explicit interface implementation simply to hide more "advanced"
    members from the object level.

The difference between allowing the use of object.method() or requiring the casting of ((Interface)object).method() seems like mean-spirited obfuscation to my inexperienced eyes. The text noted that this will hide the method from Intellisense at the object level, but why would you want to do that if it was not necessary to avoid name conflicts?

答:
The most useful application I found is with implementing factories. In many cases, it is useful to create classes that are mutable inside the factory but immutable to external classes. This can be easily implemented in Java using inner classes, by making the fields and their setters private and only exposing the getters as public members. However in C#, I had to use explicit interfaces to achieve the same thing. I'll explain further:

In Java, the inner class AND the outer class can access private members of each other, which makes total sense as the classes are very closely related. They are in the same code file and are probably developed by the same developer. This means that private fields and methods in the inner class can still be accessed by the factory to modify their values. But external classes will not be able to access these fields except through their public getters.

However, in C#, outer classes cannot access private members of inner classes so that concept is not directly applicable. I used an explicit interface as a workaround by defining a private interface in the outer class and explicitly implementing it in the inner class. This way, only the outer class can access the methods in this interface the same way it is done in Java (but they have to be methods, not fields).

Example:

public class Factory
{
    // factory method to create a hard-coded Mazda Tribute car.
    public static Car CreateCar()
    {
        Car car = new Car();

        // the Factory class can modify the model because it has access to
        // the private ICarSetters interface
        ((ICarSetters)car).model = "Mazda Tribute";

        return car;
    }

    // define a private interface containing the setters.
    private interface ICarSetters
    {
        // define the setter in the private interface
        string model { set; }
    }

    // This is the inner class. It has a member "model" that should not be modified
    // but clients, but should be modified by the factory.
    public class Car: ICarSetters
    {
        // explicitly implement the setter
        string ICarSetters.model { set; }

        // create a public getter
        public string model { get; }
    }
}

class Client
{
    public Client()
    {
        Factory.Car car = Factory.CreateCar();

        // can only read model because only the getter is public
        // and ICarSetters is private to Factory
        string model = car.model;
    }
}
```

That is what I would use explicit interfaces for.

Body:
The most useful application I found is with implementing factories. In many cases, it is useful to create classes that are mutable inside the factory but immutable to external classes. This can be easily implemented in Java using inner classes, by making the fields and their setters private and only exposing the getters as public members. However in C#, I had to use explicit interfaces to achieve the same thing. I'll explain further:

In Java, the inner class AND the outer class can access private members of each other, which makes total sense as the classes are very closely related. They are in the same code file and are probably developed by the same developer. This means that private fields and methods in the inner class can still be accessed by the factory to modify their values. But external classes will not be able to access these fields except through their public getters.

However, in C#, outer classes cannot access private members of inner classes so that concept is not directly applicable. I used an explicit interface as a workaround by defining a private interface in the outer class and explicitly implementing it in the inner class. This way, only the outer class can access the methods in this interface the same way it is done in Java (but they have to be methods, not fields).

Example:

public class Factory
{
    // factory method to create a hard-coded Mazda Tribute car.
    public static Car CreateCar()
    {
        Car car = new Car();

        // the Factory class can modify the model because it has access to
        // the private ICarSetters interface
        ((ICarSetters)car).model = "Mazda Tribute";

        return car;
    }

    // define a private interface containing the setters.
    private interface ICarSetters
    {
        // define the setter in the private interface
        string model { set; }
    }

    // This is the inner class. It has a member "model" that should not be modified
    // but clients, but should be modified by the factory.
    public class Car: ICarSetters
    {
        // explicitly implement the setter
        string ICarSetters.model { set; }

        // create a public getter
        public string model { get; }
    }
}

class Client
{
    public Client()
    {
        Factory.Car car = Factory.CreateCar();

        // can only read model because only the getter is public
        // and ICarSetters is private to Factory
        string model = car.model;
    }
}

That is what I would use explicit interfaces for.


问:
Grouping conceptual algorithms into one class or associate with their object models
If I have a number of classes, lets say a variety of buildings of some sort.  Each of these buildings have various properties and do some stuff etc

Now there is a set of operations I need to do on these buildings that are all conceptually the same.  Lets call this conceptual group of operations Move building effluent.  This functionality is essentially responsible for performing methods based on the information of each Building and then setting properties in other areas of the code as well as setting information on the building itself (can't help the need to set properties in other areas at the moment due to current system design limitations).

It's important to note that although these methods are conceptually the same and they set many of the same properties in various classes the way they calculate and get to these values are different (they do share some code however).

My question is should I put the code to do this into one class called say EffluentBuildingDistribution or should I put it into each buildings own class with appropriate methods to perform essentially the same code.

So either something like:

```<code>public class EffluentBuildingDistribution
{
    public void DistributeEffluent()
    {
       // parameters example only
       DistributeBuildingHouse(var param1, var param2);
       DistributeBuildingDogHouse(var param1, var param2);
       DistributeBuildingSecondHouse(var param1, var param2);
    }

    // and various private methods to help work with the 3 methods some shared
    // others not
}
</code>```

or

```<code>public class HouseBuilding    {
   public void DistributeEffluent(var param1, var param2)
   {
      // do stuff
   }
}

public class DogHouseBuilding    {
   public void DistributeEffluent(var param1, var param2)
   {
      // do stuff
   }
}
</code>```

Or perhaps neither of these options!.

I'm not sure if putting the code on the objects they are working on is the way to go, or putting it in a class that represents conceptually what we are trying to do.  This is an example of my current dilemma however it's also a general responsibility question on where to proportion methods and actions etc

If it's not specific enough or needs more explanation etc let me know and I'll try to explain more of my issue.

EDIT:  Due to some understandable confusion with my usage of the term Structure in my example, I since changed it to Building.  Some of the answers below refer to Structure but they are still valid as I have not changed the core of the question.

答:
What about trying to make a generic version of it?

```<code>public class DistributeEffluent<T>
{
      public void DistributeEffluent()
      {
          // a generic algo working on T=HouseStructure as well as on T=DogHouseStructure...
      }
}
</code>```

How this has to look exactly depends on the programming language you are using (which you forgot to mention, I guess C# or Java?). You can realize this also by using template method pattern, which is essentially the same approach without generics. The thing you have to add here is a common interface or a common base class for your structure classes, so DistributeEffluent can work with this interface. In this in interface, there should be elementary methods implementing the individual behaviour of each structure, but nothing more.

Body:
What about trying to make a generic version of it?

public class DistributeEffluent<T>
{
      public void DistributeEffluent()
      {
          // a generic algo working on T=HouseStructure as well as on T=DogHouseStructure...
      }
}

How this has to look exactly depends on the programming language you are using (which you forgot to mention, I guess C# or Java?). You can realize this also by using template method pattern, which is essentially the same approach without generics. The thing you have to add here is a common interface or a common base class for your structure classes, so DistributeEffluent can work with this interface. In this in interface, there should be elementary methods implementing the individual behaviour of each structure, but nothing more.


答:
I would probably create a DistributeEffluent interface and one or more implementations of it. Then, I would create a member of the interface in the structure classes to be able to use the operations.

Take a look at the Wikipedia article on Strategy Patterns.

Title: Grouping conceptual algorithms into one class or associate with their object models

Body:
If I have a number of classes, lets say a variety of buildings of some sort.  Each of these buildings have various properties and do some stuff etc

Now there is a set of operations I need to do on these buildings that are all conceptually the same.  Lets call this conceptual group of operations Move building effluent.  This functionality is essentially responsible for performing methods based on the information of each Building and then setting properties in other areas of the code as well as setting information on the building itself (can't help the need to set properties in other areas at the moment due to current system design limitations).

It's important to note that although these methods are conceptually the same and they set many of the same properties in various classes the way they calculate and get to these values are different (they do share some code however).

My question is should I put the code to do this into one class called say EffluentBuildingDistribution or should I put it into each buildings own class with appropriate methods to perform essentially the same code.

So either something like:

```<code>public class EffluentBuildingDistribution
{
    public void DistributeEffluent()
    {
       // parameters example only
       DistributeBuildingHouse(var param1, var param2);
       DistributeBuildingDogHouse(var param1, var param2);
       DistributeBuildingSecondHouse(var param1, var param2);
    }

    // and various private methods to help work with the 3 methods some shared
    // others not
}
</code>```

or

```<code>public class HouseBuilding    {
   public void DistributeEffluent(var param1, var param2)
   {
      // do stuff
   }
}

public class DogHouseBuilding    {
   public void DistributeEffluent(var param1, var param2)
   {
      // do stuff
   }
}
</code>```

Or perhaps neither of these options!.

I'm not sure if putting the code on the objects they are working on is the way to go, or putting it in a class that represents conceptually what we are trying to do.  This is an example of my current dilemma however it's also a general responsibility question on where to proportion methods and actions etc

If it's not specific enough or needs more explanation etc let me know and I'll try to explain more of my issue.

EDIT:  Due to some understandable confusion with my usage of the term Structure in my example, I since changed it to Building.  Some of the answers below refer to Structure but they are still valid as I have not changed the core of the question.


答:
The toolchain is a symptom.

When a company picks Oracle, this is an indication of:

Lots of money to throw around

Large corporation

Deeply nested organisational structure with many layers of management

Company is run by 'suits': either executive types, or marketing and sales

Makes large monolithic software products with gigantic codebases

Formal processes for everything

When a company picks Python, this is a sign of:

Small young company

No money to spare

Flat hierarchy

Company is run by programmers

Makes small single-purpose products with small codebases

Mostly informal processes

When these two meet, the large corporation's strategy is to avoid risks, use their momentum and out-marketeer the competitor. The small competition's strategy is to first beat the competition to the market, and then keep being the superior product. If the small company picks the right battles, they can easily out-perform the large company simply by being faster and more reactive, and taking advantage of the large company's tendency to avoid risks.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答:
Absolutely

It's also true that managers should conduct all meetings in Pig-Latin.  It improves their communication skills overall to have them disadvantaged when speaking simple sentences.  They'll have to rely more on facial expressions and body language to get their point across and we all know that is at least 70% of all communication anyways.

CFOs should use only an abacus and chalk.  Otherwise they end up relying too much on 'raw data' and not enough on their 'gut feel'.

And Vice Presidents and higher should be required to hold all important business meetings in distracting settings like golf courses while semi-intoxicated.   Oh snap...

ContentLicense: CC BY-SA 2.5


问:
Easy To Use Collaborative Editing Software?
My friend and I usually don't have time to meet up in person to do some real pair programming. Since we want to program together anyway, we turned to the world of collaborative software editing.

Sadly, most of the solutions we have tried are either lackluster or don't work at all. Cloud9 (fusion of Mozilla Skywriter, ACE) is tossing errors like there's no tomorrow and makes developing a project impossible.

Notepad++'s plugin seems to be broken.

CollabEdit allows only for one file at the time. Granted, you can open multiple windows, but that makes editing a bunch of files really, really awkward and clumsy.

Is there any online or offline software to enable sane collaborative editing? We tried Skyping with a shared screen, and while it's truer to pair-programming than two people coding at once, we don't want to be limited that way.

答:
It looks like you misunderstood the concept of pair programming. It is not about two people editing one file. I guess you could get two monitors, but there is only one keyboard and one mouse.

The pair programming is about two heads thinking in two different tracks. While one write code, the other looks and see if there are major errors (like a code review on steroids), plus he thinks on what to do next.

Having said that, you can take a look into this list and see if you find something that suits your need. The one that I use is gobby.


答: Saros for Eclipse is good. You and your friend can see each other's cursor and you can choose to follow what they are doing (for Observer role) or be followed (for Driver role). It also takes minimal setup (Get eclipse, get saros, get some form of communication, e.g. pigin). </p>

Title: Easy To Use Collaborative Editing Software?

Body:
My friend and I usually don't have time to meet up in person to do some real pair programming. Since we want to program together anyway, we turned to the world of collaborative software editing.

Sadly, most of the solutions we have tried are either lackluster or don't work at all. Cloud9 (fusion of Mozilla Skywriter, ACE) is tossing errors like there's no tomorrow and makes developing a project impossible.

Notepad++'s plugin seems to be broken.

CollabEdit allows only for one file at the time. Granted, you can open multiple windows, but that makes editing a bunch of files really, really awkward and clumsy.

Is there any online or offline software to enable sane collaborative editing? We tried Skyping with a shared screen, and while it's truer to pair-programming than two people coding at once, we don't want to be limited that way.


问:
How would you architect an application which is largely a collection of flowcharts?
I am working with a history teacher on a history app. He has like 200 flowcharts that he wants to put into the app (among other things). The two likeliest-looking ways to do it:

HTML/CSS. The big minus here is that neither one of us is a big HTML/CSS person. Though I do know a bit about them.

Adobe Illustrator. The interface makes it easy to draw stuff, and we can make vector graphics files and work from those. The drawback is that the text of a box, the graphical box, and the corresponding hyperlink would be different entities, where as if the HTML/CSS is done right, they might all be a single thing.

There are some flowchart-drawing websites out there. But the ones I have looked at have some problems:

In the ones I have looked at, the HTML is big and messy. We need ours to be short and simple.

Often a large amount of JavaScript is involved. We could do that, but it adds to the complexity of our mobile app, as well as the risk of failures.

We are starting on iOS but may add other platforms later.

答: You could save each flowchart as an image. You can draw it on the desktop and load it to your sever, your web page can load it at run-time like any other image. It may be a bit slow if you have large charts but probably much easier to build and manage. Even if you want to present large charts, they can be cut into pieces with each piece loaded separately.</p>


答:
Make it a PDF and leave it at that?

PDF's can have internal hyperlinks if you need to go elsewhere in your document, and you can add additional scripting in form of JavaScript.

Title: How would you architect an application which is largely a collection of flowcharts?

Body:
I am working with a history teacher on a history app. He has like 200 flowcharts that he wants to put into the app (among other things). The two likeliest-looking ways to do it:

HTML/CSS. The big minus here is that neither one of us is a big HTML/CSS person. Though I do know a bit about them.

Adobe Illustrator. The interface makes it easy to draw stuff, and we can make vector graphics files and work from those. The drawback is that the text of a box, the graphical box, and the corresponding hyperlink would be different entities, where as if the HTML/CSS is done right, they might all be a single thing.

There are some flowchart-drawing websites out there. But the ones I have looked at have some problems:

In the ones I have looked at, the HTML is big and messy. We need ours to be short and simple.

Often a large amount of JavaScript is involved. We could do that, but it adds to the complexity of our mobile app, as well as the risk of failures.

We are starting on iOS but may add other platforms later.


问:
Do job postings exaggerate their requirements?
I feel like a reasonably qualified programmer, but a lot of job postings I run into make me feel otherwise. Almost all of them separate qualifications into requirements and desirables, but even the requirements part can be daunting.

I've seen a lot of postings that say they require several years (2 or more) experience in a relatively small technology or library, something specific to their company. Other times I see 5 or even 7+ years experience required for a language. On their own some of these would be ok, but it gets ridiculous when a small town company says you need 3 years in 2 languages, proficiency in network programming, scripting, databases, and stuff like "experience with large highly redundant business critical systems" all at the same time.

Do they really expect to find someone who has extensive experience working with exactly the same technology set they use? I have a hard time finding a single posting where I don't have at least 1 or 2 holes in my skill set. I've heard over and over that most places value your ability to learn quickly and will teach you on the job, but then why say it's required? Are they just trying to discourage the bottom of the barrel (FizzBuzz failures) from applying?

答:
I'll add yet another answer here even though there are many answers already, because this answer is sort of opposite.  While job description inflation is very common in the industry, my own employer very often soft-pedals the requirements of roles, because

There are enough staff on the team that a specific skills gap for the applicant isn't a problem, if they broadly have the right kind of skills

The job is pretty technically demanding and possible applicants know this, so the requirements are to some degree understated to make sure that we don't reject excellent applicants just because (for example) they don't know Python.

We hire engineers at a variety of levels, so people responding to the same advert will get hired at different grades depending on their abilities.


答: If you named your variable properly, then !boolean is more natural. It reads as not boolean to anyone who's enough of a programmer to read code mentally.


答:
I don't think I've ever said this before, but this looks like a prime candidate for the Visitor pattern.

the visitor design pattern is a way of separating an algorithm from an object structure on which it operates

In essence, the visitor pattern allows you to define the structure of the objects within the objects themselves (in an accept method), while allowing you to put all of your algorithms in the Visitor class (in a set of visit methods, which can then share code through private methods).

```<code>public class StructureVisitor
{
    public void visit (StructureHouse structure)
    {
        // do stuff to house here
    }

    public void visit (StructureDogHouse structure)
    {
        // do stuff to dog house here
    }

    public void visit (StructureSecondHouse structure)
    {
         // do stuff to second house here
    }
}
</code>```

And then you have some parent class that has an accept method a bit like this:

```<code>public void accept (StructureVisitor visitor)
{
    this.House.accept(visitor);
    this.DogHouse.accept(visitor);
    this.SecondHouse.accept(visitor);
}
</code>```

Each of the above accept methods would simply pass themselves on to the visitor class (unless there was more depth to the structure, obviously).

```<code>public void accept (StructureVisitor visitor)
{
    visitor.visit(this);
}
</code>```

Body:
I don't think I've ever said this before, but this looks like a prime candidate for the Visitor pattern.

the visitor design pattern is a way of separating an algorithm from an object structure on which it operates

In essence, the visitor pattern allows you to define the structure of the objects within the objects themselves (in an accept method), while allowing you to put all of your algorithms in the Visitor class (in a set of visit methods, which can then share code through private methods).

public class StructureVisitor
{
    public void visit (StructureHouse structure)
    {
        // do stuff to house here
    }

    public void visit (StructureDogHouse structure)
    {
        // do stuff to dog house here
    }

    public void visit (StructureSecondHouse structure)
    {
         // do stuff to second house here
    }
}

And then you have some parent class that has an accept method a bit like this:

public void accept (StructureVisitor visitor)
{
    this.House.accept(visitor);
    this.DogHouse.accept(visitor);
    this.SecondHouse.accept(visitor);
}

Each of the above accept methods would simply pass themselves on to the visitor class (unless there was more depth to the structure, obviously).

public void accept (StructureVisitor visitor)
{
    visitor.visit(this);
}


答:
There are two different things that you should be worried about if a competitor is using an unusual language:

Productivity advantage - There are pros and cons of unusual languages, but assuming the competition has chosen well for their given problem domain then they might well have a genuine productivity advantage. Meta-programming capabilities in Lisps, for example, will probably give you a real and substantial advantage anywhere that you need to do significant amount of automatic code generation on-the-fly.

Cultural advantage - if a company uses an unusual language of interest to great hackers, then they are probably in a position to attract and retain great hackers. Companies live and die by the quality of their people, so if this translates into a long term talent advantage then it can be really significaant.

Both of these advantages may not apply in any given situation. For example, a startup could easily adopt a language "because it is cool" without really thinking through whether it is the right choice. They can easily make hiring mistakes. They can easily shoot themselves in the foot by abusing a "powerful" language.

But if a competitor picks an unusual language and uses it well then yes, you may well have a significant threat on your hands.

I think this principle is fairly timeless and is as true now as it was in 2003 - specific languages and paradigms may come and go but the idea of choosing a powerful, expressive language that suits your problem domain over a generic, safe, general purpose language will probably always merit some serious consideration.


答: For pair programming, you will need no special editing software. Any solution for virtual desktop sharing will do the trick. My personal favorite is TeamViewer, (only free for personal use). If you want a fully free solution, you can try UltraVNC.</p>


答:
If condition == false is indeed “much more natural in English” for you then I must assume that you are not a native speaker. Otherwise I cannot explain this, because nobody speaks like that:

If the sun is shining is false I stay at home.

Compare that to

If the sun is not shining I stay at home.

That said, I agree that the single, slender ! character is easily overlooked in code. For that reason, I prefer the keyword not when supported by the language. C++ for instance does allow this although many programmers are not aware of it.

For languages that require !, I put a space between operator and operand. This makes the negation much harder to overlook:

if (! condition) { … }
```

Notice that every programmer should translate this automatically, without second thought, to “not condition” in their head. Acquiring this kind of fluency in reading code idioms is among the first steps in becoming a good programmer.

Body: A comment on this question: Checking if a method returns false: assign result to temporary variable, or put method invocation directly in conditional? says that you should use !boolean instead of boolean == false when testing conditions. Why? To me boolean == false is much more natural in English and is more explicit. I apologise if this is just a matter of style, but I was wondering if there was some other reason for this preference of !boolean?

Body:
If condition == false is indeed “much more natural in English” for you then I must assume that you are not a native speaker. Otherwise I cannot explain this, because nobody speaks like that:

If the sun is shining is false I stay at home.

Compare that to

If the sun is not shining I stay at home.

That said, I agree that the single, slender ! character is easily overlooked in code. For that reason, I prefer the keyword not when supported by the language. C++ for instance does allow this although many programmers are not aware of it.

For languages that require !, I put a space between operator and operand. This makes the negation much harder to overlook:

if (! condition) { … }

Notice that every programmer should translate this automatically, without second thought, to “not condition” in their head. Acquiring this kind of fluency in reading code idioms is among the first steps in becoming a good programmer.


答:
Can you tell us about your scenario how you want to use it?

For collaborative software Development: SVN, Git

For collaborative Software Editor : Use Remote Desktop to connect and work in one editor together, walk each other though stuff. TeamViewer is a great option here to and is free

Simple non Software Editor : Good Docs (every one can work in the same file at the same time. You can past code here for a file or two but you can't compile :) )

I think if it does not fit in any of the three requirements. You needs are too peculiar.

Also check the answers here SVN vs GIT


问:
What does mathematics have to do with programming?
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...

答:
Programming crosses a lot of traditional academic disciplines.

Mathematics, especially applied mathematics, is important to programming because a lot of what we ask computers to do is crunch numbers.  Understanding numerical methods and how to apply computation efficiently and appropriately is one of the things many programmers do on a daily basis.


答:
They're not that closely related. For programming, it is important to know about mathematics- especially those branches pertaining to, for example, algorithm performance, but the simple fact is that there is no branch of mathematics that will tell you that Singletons are a horrifically bad idea, for example, or when to favour inheritance over composition, or whether or not you're really going to need that flexibility, and not to repeat yourself, and dozens of other core programming necessities.

Mathematics might be able to express what your program does, but it most certainly cannot tell you the most maintainable, human-readable, feasible way to go about it.

Title: What does mathematics have to do with programming?

Body:
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...


答:
Programming is usually based upon a Model which usually is mathematical model.

Lets take an example of creating a Mortgage Calculator. For this you need to know what interest are, what a compound interst is and so on. If you do not have the understanding of the underlying math then someone else has to provide that information to you. Usually it is the programmer job to do everything. You can always seek help though, if needed.

There are simple concept in mathematics that are used widely in programming. For example expressions, equation, variable, they are profoundly used in programming. If you dont get it in Math, you might not be the best programmer.

Having strong mathematics, give you more stuff to model you your work on. That ultimately makes you a better programmer. For example you may want to draw a quadratic equation in one of your project, this way you learn more stuff just because you are strong in math. Or you write a program to find the area of a circle, give you more experience.

In my short teaching career, I found that if students did not have a math background, they are almost lost when doing a financial problem. If they are lost about the model, learning the language itself become more difficult and honestly very frustrating.


答:
Two specific examples where a math education is important to computer science are:

1) Relational databases where relational calculus is used.

Relational calculus consists of two calculi, the tuple relational
  calculus and the domain relational calculus, that are part of the
  relational model for databases and provide a declarative way to
  specify database queries. This in contrast to the relational algebra
  which is also part of the relational model but provides a more
  procedural way for specifying queries.

The relational algebra might suggest these steps to retrieve the phone
  numbers and names of book stores that supply Some Sample Book:

```<code>Join book stores and titles over the BookstoreID.
Restrict the result of that join to tuples for the book Some Sample Book.
Project the result of that restriction over StoreName and StorePhone.
</code>```

The relational calculus would formulate a descriptive, declarative
  way:

```<code>Get StoreName and StorePhone for supplies such that there exists a title BK with the same BookstoreID value and with a BookTitle value of
</code>```

Some Sample Book.

The relational algebra and the relational calculus are essentially
  logically equivalent: for any algebraic expression, there is an
  equivalent expression in the calculus, and vice versa. This result is
  known as Codd's theorem.

The next area is artificial intelligence (AI) and machine learning.

For an example on how these are used take a look at udacity's class CS 373: PROGRAMMING A ROBOTIC CAR.

Description: This class, taught by one of the foremost experts in AI, will teach you basic methods in Artificial Intelligence, including: probabilistic inference, computer vision, machine learning, and planning, all with a focus on robotics. Extensive programming examples and assignments will apply these methods in the context of building self-driving cars. You will get a chance to visit, via video, the leading research labs in the field, and meet the scientists and engineers who are building self-driving cars at Stanford and Google.

Prerequisites: The instructor will assume solid knowledge of programming, all programming will be in Python. Knowledge of probability and linear algebra will be helpful.

WEEK 1:

Basics of probability Car localization with particle filters

WEEK 2:

Gaussians and continuous probability Tracking other cars with Kalman
  filters

WEEK 3:

Image Processing and Machine Learning Finding objects in sensor data

WEEK 4:

Planning and search Determining where to drive with A* search Finding
  optimal routes with dynamic programming

WEEK 5:

Controls Controlling steering and speeds with PID

WEEK 6:

Putting it all together Programming a self-driving car

WEEK 7:

Final Exam Exam testing your knowledge

Body:
Two specific examples where a math education is important to computer science are:

1) Relational databases where relational calculus is used.

Relational calculus consists of two calculi, the tuple relational
  calculus and the domain relational calculus, that are part of the
  relational model for databases and provide a declarative way to
  specify database queries. This in contrast to the relational algebra
  which is also part of the relational model but provides a more
  procedural way for specifying queries.

The relational algebra might suggest these steps to retrieve the phone
  numbers and names of book stores that supply Some Sample Book:

Join book stores and titles over the BookstoreID.
Restrict the result of that join to tuples for the book Some Sample Book.
Project the result of that restriction over StoreName and StorePhone.

The relational calculus would formulate a descriptive, declarative
  way:

Get StoreName and StorePhone for supplies such that there exists a title BK with the same BookstoreID value and with a BookTitle value of

Some Sample Book.

The relational algebra and the relational calculus are essentially
  logically equivalent: for any algebraic expression, there is an
  equivalent expression in the calculus, and vice versa. This result is
  known as Codd's theorem.

The next area is artificial intelligence (AI) and machine learning.

For an example on how these are used take a look at udacity's class CS 373: PROGRAMMING A ROBOTIC CAR.

Description: This class, taught by one of the foremost experts in AI, will teach you basic methods in Artificial Intelligence, including: probabilistic inference, computer vision, machine learning, and planning, all with a focus on robotics. Extensive programming examples and assignments will apply these methods in the context of building self-driving cars. You will get a chance to visit, via video, the leading research labs in the field, and meet the scientists and engineers who are building self-driving cars at Stanford and Google.

Prerequisites: The instructor will assume solid knowledge of programming, all programming will be in Python. Knowledge of probability and linear algebra will be helpful.

WEEK 1:

Basics of probability Car localization with particle filters

WEEK 2:

Gaussians and continuous probability Tracking other cars with Kalman
  filters

WEEK 3:

Image Processing and Machine Learning Finding objects in sensor data

WEEK 4:

Planning and search Determining where to drive with A* search Finding
  optimal routes with dynamic programming

WEEK 5:

Controls Controlling steering and speeds with PID

WEEK 6:

Putting it all together Programming a self-driving car

WEEK 7:

Final Exam Exam testing your knowledge


问:
Interpreted vs Compiled: A useful distinction?
A lot of questions get asked here about interpreted vs compiled language implements. I'm wondering whether the distinction actually makes any sense. (Actually the questions are usually about languages, but they are really thinking about the most popular implementations of those languages).

Today almost no implementation is strictly interpreted. i.e. pretty much nobody parses and runs the code one line at a time. Additionally, implementation which compile to machine code are also becoming less common. Increasingly, compilers target some sort of virtual machine.

In fact, most implementation are converging on the same basic strategy. The compiler produces bytecode which is interpreted or compiled to native code via a JIT. It is really a mix of the traditional ideas of compilation and interpretation.

Thus I ask: Is there a useful distinction between interpreted implementations and compiled implementation these days?

答: Actually lots of implementations of languages are still strictly interpreted, you just may not be aware of them. To name a few: the UNIX shell languages, The Windows cmd and PowerScript shells, Perl, awk, sed, MATLAB, Mathematica and so on. </p>


答: Useful distinction: interpreted programs can modify themselves by adding or changing functions at runtime. </p>

Title: Interpreted vs Compiled: A useful distinction?

Body:
A lot of questions get asked here about interpreted vs compiled language implements. I'm wondering whether the distinction actually makes any sense. (Actually the questions are usually about languages, but they are really thinking about the most popular implementations of those languages).

Today almost no implementation is strictly interpreted. i.e. pretty much nobody parses and runs the code one line at a time. Additionally, implementation which compile to machine code are also becoming less common. Increasingly, compilers target some sort of virtual machine.

In fact, most implementation are converging on the same basic strategy. The compiler produces bytecode which is interpreted or compiled to native code via a JIT. It is really a mix of the traditional ideas of compilation and interpretation.

Thus I ask: Is there a useful distinction between interpreted implementations and compiled implementation these days?


答:
It's important to remember that interpreting and compiling are not just alternatives to each other. In the end, any program that you write (including one compiled to machine code) gets interpreted. Interpreting code simply means taking a set of instructions and returning an answer.

Compiling, on the other hand, means converting a program in one language to another language. Usually it is assumed that when compilation takes place, the code is compiled to a "lower-level" language (eg. machine code, some kind of VM bytecode, etc.). This compiled code is still interpreted later on.

With regards to your question of whether there is a useful distinction between interpreted and compiled languages, my personal opinion is that everyone should have a basic understanding of what is happening to the code they write during interpretation. So, if their code is being JIT compiled, or bytecode-cached, etc., the programmer should at least have a basic understanding of what that means.


答:
Math and programming are related in two ways.

One is that math can be used to reason about computer programs. It can help answer questions like "How will the running time of my program change as the input data changes?", "Is my program guaranteed to find an answer to my problem?", "Is my program as efficient as it could be?", "How should I re-arrange my program to make it faster or use less memory?". You typically cover topics like these in upper division courses on the theory of computation, the design of algorithms, and computer language design.

The second way math and program are related is that programming is used to solve mathematical problems. This is important because many problems of "ordinary life" can actually be recast as mathematical problems and then solved (maybe approximately) on a computer. These sorts of topics will show up to some extent in almost all of your courses, but particularly in courses on discrete math and mathematical modeling.


问:
Where is the best place to store code on a Mac?
I've started toying with some Mac development and wonder where the best place to store the code is?

Generally on my windows box, I'd store all my code in c:\Code\

On the Mac it's in /Users/Liam/Code/

Will this cause me any issue with permissions when running web code?

答:
Your home directory is a great place to store your code on a Mac/Ubuntu (Linux based system).

I would still create sub directories under it as appropriate.  I usually organize by project, with a few extra directories for whatever, e.g.

```<code>/home/myname/project_pear
/home/myname/project_pear/upgrade/
/home/myname/random_java_code
/home/myname/Dropbox/my_open_source_awesome_project
</code>```

The other thing I do which is really "big" for me is to create aliases in .bash_rc (Ubuntu) or .bash_profile (Mac).  I have so many now I put them in a separate file called .bash_aliases. (which I keep on Dropbox of course...) and include it with:

```<code>if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi
</code>```

For instance, for the above, I might create a 'mup' alias that does a cd /home/myname/project_pear/upgrade, then I can just type mup at the command line to do that long cd!

Another hint - when you copy working code into a unix based system, you will often find that executable say 'insufficent permission'.  However you can frequently fix that with chmod +x filename (modify the file so that is has eXecute permission.

Body:
Your home directory is a great place to store your code on a Mac/Ubuntu (Linux based system).

I would still create sub directories under it as appropriate.  I usually organize by project, with a few extra directories for whatever, e.g.

/home/myname/project_pear
/home/myname/project_pear/upgrade/
/home/myname/random_java_code
/home/myname/Dropbox/my_open_source_awesome_project

The other thing I do which is really "big" for me is to create aliases in .bash_rc (Ubuntu) or .bash_profile (Mac).  I have so many now I put them in a separate file called .bash_aliases. (which I keep on Dropbox of course...) and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

For instance, for the above, I might create a 'mup' alias that does a cd /home/myname/project_pear/upgrade, then I can just type mup at the command line to do that long cd!

Another hint - when you copy working code into a unix based system, you will often find that executable say 'insufficent permission'.  However you can frequently fix that with chmod +x filename (modify the file so that is has eXecute permission.


答:
For scientific application development, Game programming, real-time systems, simulation systems, and such applications, Mathematics is required indeed. After all, programming uses mathematics and science to solve problems. On the other hand, to program an application that captures users information for registering them in your database, does not require any high level of mathematics. Nevertheless, all programmers would benefit from Basic Number Theory, Algebra, Basic Set Theory and Elementary Numerical Analysis.

From the mathematics practitioner side, different topics in Mathematics (as well as many other science branches) could benefit significantly from programming.


答:
I think: Absolutely Yes.

In fact, most implementation are converging on the same basic strategy

Really, C++ aims to port to compiler domain some high level concept that's usually handed to interpreters, but it stays on the minority side...


问:
Should developers enter bugs into the bug tracking system?
While developing (either features or bug fixes) I sometimes happen to discover bugs that are not directly related to what I'm working on.  What should I do in that situation.  Just fix it?  Try to remember to fix it later?  Write it down somewhere?  Or enter it into the bug tracking system?

I generally enter it into the bug tracking system and let the process play itself out (i.e. triaging, assigning, etc.).  However I have hardly ever seen another developer enter a bug.  (Why is that?)

答:
Assuming its already-tested (and particularly if released) code absolutely.

There are a number of reasons for this:

Memory - The system is really unlikely to forget the bug, any given developer may.

Metrics - The number of bugs found, closed and the time taken can be good easy-to-capture metrics to tell you how the quality of your code is progressing

Urgency - It might seem like the most important thing in the world to the developer, however the time spent fixing this issue may be better spent on something that the end users want first (see also memory).

Duplication - Maybe it's already been spotted and is under examination / fix by someone else. Alternatively maybe it has fallen foul of the urgency rule and been put off. Of course the fact that you've found it again doesn't just mean that it shouldn't be done, it might mean that (as it keeps coming up) that is is now more urgent to fix.

Root cause analysis - The easiest bug to fix is the one that was never there. It may be that the team should be looking at this bug to find out how it came to be. This is definativley not to punish the one responsible (that never helps) but to find out how the situation can be avoided in the future.

Wider impact analysis - The cheapest bug to find is the one you knew about before you found it. By looking at this bug (particularly after doing root cause analysis) it may quickly become clear that this problem could exist in other places in the code. As a result the team can choose to go find it before it raises its ugly head at a more embarrassing moment.

The amount of time that is spent on these (if any) is largely dependent on the maturity and quality level of the code. Root cause analysis is likely to be overkill for a tiny team working on demonstration code, but a large team on business critical development probably need to learn the lessons effectively and efficiently.

From experience there are two broad reasons that developers avoid using the tool:

The bug handling tool and/or process is perceived as too heavyweight for the development

The developers find the mental challenge of fixing the bug more interesting than the stuff they are currently working on.

Item 1 implies that a better/simpler system may be required; or alternatively a more compelling justification of the existing system might be in order.

Item 2 should be a useful warning sign to the development lead about current task allocations.


问:
Where to use C++ today?

Possible Duplicate:

  Is there any reason to use C++ instead of C, Perl, Python, etc.?

  When to use C over C++, and C++ over C?

I am going to enter university next fall in computer sciences, but have been programming already for a few years.  I am currently doing web application development.  I use Python and Java mainly.

I also know C++, but never really pacticed it because everytime I think of a project, there seems to be a language that is better suited for the job than C++.  For example, Java seems to give the same result as C++, but in a more productive way (even performance-wise, Java is not far behind C++).  Not to mention that the Java library is much greater than the C++ one.  This makes me wonder where, in the world of web development, could I use C++ and get an advantage that other languages won't give me?  I currently believe that it would be as an add-on to a language like Java or Python.

答:
Actually the main Java VM implementation (HotSpot) is written in C++. This language is still very used mainly for performance and memory issue I think, and because there are still a lot of C and C++ developers. You can find here some application made in C++.

C++ can use C method that are low level, it can be usefull for some application. I don't know if you can write easily a driver in Java for example.

It is also used for creating GUI or games with Qt and SDL.

So C++ is still a good language that can't be totally replaced with Python or Java.

Title: Where to use C++ today?


答: In embedded system development, C and C++ are widely used. We can say that C is industry standart for embedded development. You can easily find a compiler for nearly all micro-controllers. There are also lots of computer program/tool written in C/C++. Games and 3D designing softwares (CAD,CAM) also prefer C++.</p>

Title: Where to use C++ today?

Body:
Possible Duplicate:

  Is there any reason to use C++ instead of C, Perl, Python, etc.?

  When to use C over C++, and C++ over C?

I am going to enter university next fall in computer sciences, but have been programming already for a few years.  I am currently doing web application development.  I use Python and Java mainly.

I also know C++, but never really pacticed it because everytime I think of a project, there seems to be a language that is better suited for the job than C++.  For example, Java seems to give the same result as C++, but in a more productive way (even performance-wise, Java is not far behind C++).  Not to mention that the Java library is much greater than the C++ one.  This makes me wonder where, in the world of web development, could I use C++ and get an advantage that other languages won't give me?  I currently believe that it would be as an add-on to a language like Java or Python.


答:
I mostly agree with FrustratedWithFormsDesign but I think it is even clearer if the whole issue is broken down into two areas:

Bug Reporting.

Bug Fixing.

These are often treated as being the same and separating them will almost certainly help a lot.

These can be handled with:
Bug Reporting:- put it in the system, as everyone says.

Bug fixing:- Every week or two (adjust to your development schedule, etc.) everyone gets together on the project and decides what should be fixed, by whom, etc.  This was everyone is on the same page and can see what needs to be done.  In Agile Development this is the Sprint Planning meeting.

A good tool that people want to use also makes a big difference.  I like Pivotal Tracker and it passed my 'really useful tool' test when I started using it just to keep track of things I want to do or fix in my own private projects!

Title: Should developers enter bugs into the bug tracking system?

Body:
While developing (either features or bug fixes) I sometimes happen to discover bugs that are not directly related to what I'm working on.  What should I do in that situation.  Just fix it?  Try to remember to fix it later?  Write it down somewhere?  Or enter it into the bug tracking system?

I generally enter it into the bug tracking system and let the process play itself out (i.e. triaging, assigning, etc.).  However I have hardly ever seen another developer enter a bug.  (Why is that?)


答: There are whole industries (games, high-perf garphics, etc) where C++ is the dominant language today and likely to stay dominant for a while.</p>

Title: Where to use C++ today?


答:
Google does lots of work in C++.

https://stackoverflow.com/questions/754301/what-programming-language-is-google-written-in

Anywhere you go, where you need performance, C and C++ are the way to go.

Title: Where to use C++ today?


问:
Raise a ticket to issue tracking from external web application
I don't know if it's the right place to post this question but, to improve my productivity I need to install an open source issue-tracking system to keep tracks of all bugs and information about the completion.

There are a lot of open source systems to do that but I'm looking for one which could be hosted on PHP / MySql / Linux server and, in particular allows to raise a ticket via rest or soap from my Spring webapp (I thought to create a simple form in my webApp to submit a ticket).

I took a look to The Bug Genie, Mantis and WebIssues and the first two are very hard to be used by non IT user. WebIssues seems to be very easy also for my customers that just need to take a look to the ticket resolution status.

Any tips?

Note I prefer to install my own system in order to pay only one hosting service.

答: Do you need to install your own?  There are several hosted solutions out there.</p>


问:
Do you need to meet personally to collaborate effectively?
If you are starting up a web, mobile, or standalone application, how well must you know the rest of your collaboration team? Would it be a bad idea to ever work with someone unless I've met him personally? Is it okay to sometimes accept small public contributions such as code snippets and artwork without meeting the contributor? Should I ever actively collaborate with people online that I have not met, as long as the person has a detailed profile and a good reputation.

If you do collaborate online, what tools do you to build teams and find contributors? If not, would you consider the idea if there was a safe medium? Any other input on the subject would be appreciated.

答:
I've worked for the last 18 months on a mission critical iOS line of business app.  We have a manager, a Project Manager, and two developers.  The two managers are at the east coast corporate headquarters, one developer is remote from the Midwest, and I'm remote from the west coast.  When the project launched we spent a week together, and we've had follow up meetings of approximately a week three other times.  I do 95% of the iOS development and the other developer does 95% of the server side.

We use telephone, email, and join.me to collaborate. I pretty much need to work east coast hours.

Despite the fact that we have 50% management overhead we are extremely productive.  In fact I think we rock.  If we developers were at the corporate office I'm convinced our productivity would be just a fraction of what it is.  When we are at the office frankly I'm shocked at the signal to noise ratio.

Obviously this requires professionalism, skill, and a strong ability to self-manage.


答:
Someone almost hit the nail on the head above. Programming is mathematics.  More specifically, programming is a branch of mathematical logic called computability theory or recursion theory.

Other branches of math are involved directly, specifically formal language and automata theory. These help describe regular expressions, used in pattern matching, and formal grammars, used to describe and parse programming languages.

Anybody who says that programming is not mathematics either doesn't know what they're talking about, or has an ulterior motive, like a "Intellectual Property" maximalist, who hopes to profit by getting a patent on an algorithm or some other basic mathematical fact or discovery.

Some references for programming as math, and the corollary not knowing what you're talking about:

Program are Proofs: 19th Century Logic and 21st Century Computing

Programs are Proofs: Models and Types in Lambda Calculus

Wikipedia's Curry-Howard Correspondence article

On the Unusual Effectiveness of Logic in Computer Science

The Unreasonable Effectiveness of Logic

Yes, those are heavy on the "logic" part of mathematical logic, but mathematics is generally acknowledged to be a few axioms, and their logic consequences as developed via first order logic.

As far as saying otherwise and being an "IP" maximalist out for money:

How to patent an algorithm in the US.  Algorithms aren't patentable, but patents are granted on algorithms by not referring to them as algorithms. It's not hard to find a lot of material on the web that either points out, or attempts to explain, that contradiction.