问:
If condition not true: default value or else clause?
I have searched Programmers and Stackoverflow and was not able to come up with a satisfying answer, even though I'm quite sure it must have been asked many times before. The only question I found has answers only dealing with readability. The code excerpts below are from actual C# code I was writing.

When dealing with a local variable that has some calculated value when a condition is true but a default value otherwise, do I:

First set the value, then change the value when the condition is true?

short version = 1;      // <-- set the value here.
if (separator != -1)
{
    version = Int16.Parse(filename.Substring(separator + 1));
    filename = filename.Substring(0, separator);
}
```

<p>Or <em>not</em> set the value, and add an else when the condition is false?</p>

<pre class="lang-cs prettyprint-override"><code>short version;
if (separator != -1)
{
    version = Int16.Parse(filename.Substring(separator + 1));
    filename = filename.Substring(0, separator);
}
else
    version = 1;        // <-- set the value here.
</code>```

Could a programmer have wrong expectations when confronted with either solution (e.g. when the if-clause is quite big and the else-clause is way down, out of view)? Do you have any experiences where the difference mattered? Is one particular style enforced at your company, and why? Are there any technical reasons why one would be preferred over the other? The first one sets a variable twice, but I'm not sure whether this would matter in modern-day optimizing compilers.

答:
You left out a third possibility:

```<code>short version;
if (separator == -1)
{
    version = 1;        // <-- set the value here.
}
 else
{
    version = Int16.Parse(filename.Substring(separator + 1));
    filename = filename.Substring(0, separator);
}
</code>```

As you note, the compiler really doesn't care which way you go.  The way I've put it here, at least you don't have the separation that you were concerned about.  The setting of version between true and false is obvious at a glance, the top one will always be nice and short, and it makes obvious the setting of version in each case--if that's what you are worried about.

I think you'll find (with the several votes to close) that it's really just a matter of preference.

Body:
You left out a third possibility:

short version;
if (separator == -1)
{
    version = 1;        // <-- set the value here.
}
 else
{
    version = Int16.Parse(filename.Substring(separator + 1));
    filename = filename.Substring(0, separator);
}

As you note, the compiler really doesn't care which way you go.  The way I've put it here, at least you don't have the separation that you were concerned about.  The setting of version between true and false is obvious at a glance, the top one will always be nice and short, and it makes obvious the setting of version in each case--if that's what you are worried about.

I think you'll find (with the several votes to close) that it's really just a matter of preference.


答:
PLEASE SHARE MORE CODE - a complete class if it fits. Otherwise, there is no way to give you a decent advice.

I do not exactly what you are doing, so I will guess. Here is one way ... what does the separator variable do? Ideally the separator would be passed in as a parameter, but then it does not make sense because if separator is -1, then it should not have been called in the first place.

```<code>// Initialize some stuff inside of the constructor.

...
private void ParseVersionAndFileName()
{
    if (this.Separator < 0)
    {
        Debug.Assert(separator == -1, "Negative value but not -1? How?");
        return;
    }

    this.Version = Int16.Parse(this.Filename.Substring(this.Separator + 1));
    this.Filename = this.Filename.Substring(0, this.Separator);
}

public string Version
{
    get;
    private set;
}

public int Version
{
    get;
    private set;
}
...
</code>```

ContentLicense: CC BY-SA 3.0

Title: If condition not true: default value or else clause?

Body:
I have searched Programmers and Stackoverflow and was not able to come up with a satisfying answer, even though I'm quite sure it must have been asked many times before. The only question I found has answers only dealing with readability. The code excerpts below are from actual C# code I was writing.

When dealing with a local variable that has some calculated value when a condition is true but a default value otherwise, do I:

First set the value, then change the value when the condition is true?

short version = 1;      // <-- set the value here.
if (separator != -1)
{
    version = Int16.Parse(filename.Substring(separator + 1));
    filename = filename.Substring(0, separator);
}
```

<p>Or <em>not</em> set the value, and add an else when the condition is false?</p>

<pre class="lang-cs prettyprint-override"><code>short version;
if (separator != -1)
{
    version = Int16.Parse(filename.Substring(separator + 1));
    filename = filename.Substring(0, separator);
}
else
    version = 1;        // <-- set the value here.
</code>```

Could a programmer have wrong expectations when confronted with either solution (e.g. when the if-clause is quite big and the else-clause is way down, out of view)? Do you have any experiences where the difference mattered? Is one particular style enforced at your company, and why? Are there any technical reasons why one would be preferred over the other? The first one sets a variable twice, but I'm not sure whether this would matter in modern-day optimizing compilers.

Body:
PLEASE SHARE MORE CODE - a complete class if it fits. Otherwise, there is no way to give you a decent advice.

I do not exactly what you are doing, so I will guess. Here is one way ... what does the separator variable do? Ideally the separator would be passed in as a parameter, but then it does not make sense because if separator is -1, then it should not have been called in the first place.

// Initialize some stuff inside of the constructor.

...
private void ParseVersionAndFileName()
{
    if (this.Separator < 0)
    {
        Debug.Assert(separator == -1, "Negative value but not -1? How?");
        return;
    }

    this.Version = Int16.Parse(this.Filename.Substring(this.Separator + 1));
    this.Filename = this.Filename.Substring(0, this.Separator);
}

public string Version
{
    get;
    private set;
}

public int Version
{
    get;
    private set;
}
...


答: It's more clear when you enclose the assignment inside an if-else block if it is relevant to the condition itself. Not only can it hint the compiler that the assignment can be ignored in case condition fails, but it also hints the programmer that the two things(assignment of a variable and the condition) are related. Similarly, if the two are not related, separating them(assignment before or after the if() block) would probably be the intuitive approach. Of course, this all depends on the context and is case-specific. But in general tie related things together and be elaborate with the logic.</p>


问:
Why do variables need a type?
So we write:

```<code>Customer c = new Customer();
</code>```

Why is the design not such that we write:

```<code>c = new Customer();
c.CreditLimit = 1000;
</code>```

The compiler can work out c points to a Customer and allow Customer's members to be invoked on c?

I know we may want to write:

```<code>IPerson c = new Customer();
IPerson e = new Employee();
</code>```

so as to be able to write:

```<code>public string GetName(IPerson object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);
</code>```

But if we wrote:

```<code>c = new Customer();
e = new Employee();
</code>```

we could still write:

```<code>public string GetName(object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);
</code>```

The compiler could complain about the code immediately above if the type of object c references does not support a Name property (as it can check which members are used on the argument/parameter within the method), or the runtime could complain.

Even with C#'s dynamic keyword, we are still using a variable 'type' (determined at runtime). But why does a variable need a type at all? I am sure there must be a good reason, but I can't think of it!

答:
Dynamically typed languages are often touted as "object-oriented". They are not. They may be encapsulation-oriented, but never object-oriented. Object orientation is all about types.

"The boy rides his brother's bike to the grocery store and buys a loaf of bread from the grocer". Using object orientation, one can immediately write a set of classes (types) to describe this real-world scenario.

In a dynamically-typed language, the scenario could only be represented thusly:

"The object rides his object's object to the object and buys an object from the object".

The power of object orientation is in its ability to model the world in natural terms, so that the software developer can use both sides of the brain to write software, and solve problems more as a human being, less as a computer programmer. This power is absent in dynamically typed languages.

Static typing permits better coding efficiency, re-usability and maintainability, because integrated development environments know the types of variables. Knowing the types of variables, an IDE can provide auto completion so that the programmer doesn't have to refer back to the class definition in order to remember whether the member property was spelled "backlightControl" or "backLightControl" or "bkLightCtrl".

Static typing permits automated refactoring, because the IDE knows every place where a variable holds an instance of the object being refactored.

Static typing permits greater re-usability and maintainability. Dynamic typing is better for disposable code. Suppose a new developer comes in off the street, and looks at an existing piece of code. If the code is statically typed, the developer can, in two mouse clicks, examine the class definition of each of the variables involved, knows what the class is for, knows what other methods and properties are available. If the code is dynamically typed, the developer has to use global searching to figure out what is going on.

OwnerDisplayName: sturdytree

Title: Why do variables need a type?


问:
How to quickly adapt to a project?
Suppose my favourite open source application has a bug. Now I want to contribute to the application by fixing its bug and submit the patch to the development team. What's the most effective way to do this? Do you actually read the whole source code of the project (or most of it) to understand the logic before start fixing it?</p>

答:
Know how to test the bug before fixing

Making sure that your bug fix does NOT introduce new defects should be the priority. Well, how to do that?

Usual pitfall in fixing bugs starts from insufficient pre-analysis of a bug/issue. Rush to fix the bug is something developer needs to avoid.

Taking your time to analyse what is the bug, how to re-produce it, its relationship to other parts of the code (also called dependencies) is very important. Once you know the test cases and all relevant dependencies to take care, it should be the right fix.

In addition try to use re-factoring tools in your development practice. They are very handy and will ease your life while maintaining the code.

Getting up to speed in a large project

Well, even though there is no silver point to follow, i have compiled a list of useful points that were helpful to me.

Ask for a senior team mate (also called buddy) as a mentor for you in the project

Read the documentation and/or requirements to understand business process of the existing implementation

For one cycle of the release work as unit tester or help other developers in doing unit testing.

Get responsibility for a independent module to start with. Work closely with your project mentor on how this will get integrated into the rest

Study and understand the architecture and design

Try to get a quick overview of the modules from developer that you will be taking care

Study and understand the build process

Title: How to quickly adapt to a project?


答:
I would encapsulate the functionality in its own method and use a guard clause to take care of the special case:

```<code>private short getVersion(String filename, int separator)
{
    if (separator == -1)
    {
        return 1;
    }

    return Int16.Parse(filename.Substring(separator + 1));
}
</code>```

I left out the filename modification because that probably deserves it's own method too:

```<code>private String removeVersion(String filename, int separator)
{
    if (separator == -1)
    {
        return filename;
    }

    return filename.Substring(0, separator);
}
</code>```

My C# is rusty but hopefully it's correct enough to make sense.

Body:
I would encapsulate the functionality in its own method and use a guard clause to take care of the special case:

private short getVersion(String filename, int separator)
{
    if (separator == -1)
    {
        return 1;
    }

    return Int16.Parse(filename.Substring(separator + 1));
}

I left out the filename modification because that probably deserves it's own method too:

private String removeVersion(String filename, int separator)
{
    if (separator == -1)
    {
        return filename;
    }

    return filename.Substring(0, separator);
}

My C# is rusty but hopefully it's correct enough to make sense.


答:
There's a school of thought that says a variable should not come into scope until you can assign it a valid value.  In other words, the variable should never contain either a wrong value or a garbage value.  This prevents the possibility of, for example, a maintainer later putting a call after the variable declaration but before the variable is properly initialized.

In your short example, it's fairly obvious those statements are a group, but over time there is nothing preventing people from putting several unrelated statements in between.

That means both of your examples are wrong.  The first way has a short period of time when it incorrectly holds the default value, and the second way has a short period of time when it incorrectly holds no value.  The best solution from a readability and maintainability point of view is something like:

```<code>short version = getVersion(filename, separator);
</code>```

This has the added bonus of conforming to the "functions should do exactly one thing" school of thought as well.

Body:
There's a school of thought that says a variable should not come into scope until you can assign it a valid value.  In other words, the variable should never contain either a wrong value or a garbage value.  This prevents the possibility of, for example, a maintainer later putting a call after the variable declaration but before the variable is properly initialized.

In your short example, it's fairly obvious those statements are a group, but over time there is nothing preventing people from putting several unrelated statements in between.

That means both of your examples are wrong.  The first way has a short period of time when it incorrectly holds the default value, and the second way has a short period of time when it incorrectly holds no value.  The best solution from a readability and maintainability point of view is something like:

short version = getVersion(filename, separator);

This has the added bonus of conforming to the "functions should do exactly one thing" school of thought as well.


问:
Should I put newlines before or after binary operators?
When you're in Python or Javascript, you should always put binary operators at the end of the previous line, in order to prevent newlines from terminating your code prematurely; it helps you catch errors.

But in C or C++, this isn't an issue, so I'm wondering:

Is there any reason for me to prefer the second version to the first?

```<code>return lots_of_text
       + 1;
</code>```

versus

```<code>return lots_of_text +
       1;
</code>```

(For example, does one of them help prevent other kinds of errors? Or is one of them considered more readable?)

答:
I'd always use the first. You want it to be clear what you are doing with that 1 there. If I saw that and there was a wall of text above that 1 I'd have no idea what was going on as far as that 1's usage.

```<code># The first
return lots_of_text
       + 1;
</code>```

The '+' being next to 1 makes it clear that at a minimum I am doing something with the 1 in question rather than it hanging out going "I'm all in your code dude..." for no apparent reason.

Body:
I'd always use the first. You want it to be clear what you are doing with that 1 there. If I saw that and there was a wall of text above that 1 I'd have no idea what was going on as far as that 1's usage.

# The first
return lots_of_text
       + 1;

The '+' being next to 1 makes it clear that at a minimum I am doing something with the 1 in question rather than it hanging out going "I'm all in your code dude..." for no apparent reason.

ContentLicense: CC BY-SA 4.0


问:
What statements and approaches should I avoid when learning functional programming?
I have 6 years of programming experience, mostly following the object oriented paradigm, and I'm interested in learning functional programming. My main goal is to become a functional paradigm programmer and not a programmer who is using a functional language but still writes in imperative style.

When I'm practising in functional programming I still follow an object oriented way of thinking, like loops, mutable variables and so on. I picked F# as a basic functional language and because it's very tightly integrated with other .Net languages, like C#. F# allows usual object oriented statements, therefore you can use F# syntax but not actually produce functional code.

What statements and approaches should I avoid when learning functional programming?

答:
Functional Programming is more than just a list of statements to avoid. It's a (often) radical shift in mindset. For example, there are no destructive state changes allowed in functional programming. If I say that A = 5, I have not set up A as a kind of box containing a 5. I've made A exactly the same as 5, forever. There's a very very good book, co-written by the one and only Jon Skeet called Real World Functional Programming.

As far as learning purely functional programming is concerned though, I'd actually recommend Haskell over F#. Granted you'll probably get more done in terms of production code with F# or Ocaml but Haskell will bend your mind into the proper shape in order to grok functional programming. The process may take some time, however.

I recommend Learn You a Haskell if you want a guide to that. The C#/F# book option is less painful though. C# and F# let you solid, workable magic as a functional programmer. Haskell is black sorcery by comparison.


问:
TDD: Mocking out tightly coupled objects
Sometimes objects just need to be tightly coupled. For example, a CsvFile class will probably need to work tightly with the CsvRecord class (or ICsvRecord interface).

However from what I learned in the past, one of test-driven development's main tenets is "Never test more than one class at a time." Meaning you should use ICsvRecord mocks or stubs rather than actual instances of CsvRecord.

However after trying this approach, I noticed that mocking out the CsvRecord class can get a little hairy. Which leads me to one of two conclusions:

It's hard to write unit tests! That's a code smell! Refactor!

Mocking out every single dependency is just unreasonable.

When I replaced my mocks with actual CsvRecord instances, things went much more smoothly. When looking around for other peoples' thoughts I stumbled across this blog post, which seems to support #2 above. For objects that are naturally tightly coupled, we should not worry so much about mocking.

Am I way off track? Are there any downsides to assumption #2 above? Should I actually be thinking about refactoring my design?

答:
There are really two questions here.  The first is if situations exist where mocking an object is inadvisable.  That's undoubtedly true, as shown by the other excellent answers.  The second question is whether your particular case is one of those situations.  On that question I am not convinced.

Probably the most common reason not to mock a class is if it's a value class.  However, you have to look at the reason behind the rule.  It's not because the mocked class will be bad somehow, it's because it will be essentially identical to the original.  If that were the case, your unit testing would not be any easier using the original class.

It very well may be that your code is one of the rare exceptions where refactoring wouldn't help, but you should only declare it such after diligent refactoring efforts haven't worked.  Even seasoned developers can have trouble seeing alternatives to their own design.  If you can't think of any possible way to improve it, ask someone experienced to give it a second look.

Most people seem to be assuming your CsvRecord is a value class.  Try making it one.  Make it immutable if you can.  If you have two objects with pointers to each other, remove one of them and figure out how to make it work.  Look for places to split classes and functions.  The best place to split a class may not always match up with the physical layout of the file.  Try reversing the parent/child relationship of the classes.  Maybe you need a separate class for reading and writing csv files.  Maybe you need separate classes for handling the file I/O and the interface to the upper layers.  There are lots of things to try before declaring it unrefactorable.


问:
EE vs Computer Science: Effect on Developers' Approaches, Styles?
Are there any systematic differences between software developers (sw engineers, architect, whatever job title) with an electronics or other engineering background, compared to those who entered the profession through computer science?

By electronics background, I mean an EE degree, or a self-taught electronics tinkerer, other types of engineers and experimental physicists.

I'm wondering if coming into the software-making professions from a strong knowledge of flip flops, tristate buffers, clock edge rise times and so forth, usually leads to a distinct approach to problems, mindsets, or superior skills at certain specialties and lack of skills at others, when compared to the computer science types who are full of concepts like abstract data types, object orientation, database normalization, who speak of "closures" in programming languages - things that make little sense to the soldering iron crowd until they learn enough programming.

The real world, I'm sure, offers a wild range of individual exceptions, but for the most part, can you say there are overall differences?   Would these have hiring implications e.g. (to make up something) "never hire an electron wrangler to do database design"?   Could knowing about any differences help job seekers find something appropriate more effectively?   Or provide enlightenment or some practical advice for those who find themselves misfits in a particular job role?

(Btw, I've never taken any computer science classes; my impression of exactly what they cover is fuzzy.   I'm an electronics/physics/art type, myself.)

答:
In my experience - EE types seem to design linear programs and not to incorporate the abstraction layers CS types seem to be comfortable with.

No comment about the quality differences or lack thereof.

ContentLicense: CC BY-SA 2.5


答:
A computer program is a graph of process nodes describing what a "machine", represented by the language runtime (extended with toolkits in most cases) should do, in what order or under what conditions. This graph is represented by a text file (or a bunch of text files) written in a specific language, and (partially or fully) created when the compiler/interpreter reads (deserializes) this file. Also, there are some environments (UML or graphical program generating tools) where you can actually build this graph, and generate the source code in a target language.

Why do I say this? Because this leads to the answer to your question.

Your program text is your directions on how the computer should solve the actual task, containing both the process steps (conditions, actions) AND the structure (what components do you use in the solution). The latter means that you get or create some instances of other components, put them into named boxes (variables) and use them: access their data and services.

Some languages gives you uniform boxes, where only the label is important, but you can put just anything into them, you can even use a variable named "target" to store a "Person" at the beginning and "Car" at the end of the same algorithm. Others requires you to create "shaped" boxes, therefore different ones for a Person or a Car - although they still let you create a "generic box" (Java Object, C/C++ void*, Objective C "id"...) and cast it as you like. Typed languages let you express your structure in finer details, creating "type contracts" for your variables (although you can hack around this limitation), while untyped languages support this "I will surely know what I have put into that box this time" approach as the default and only behavior.

Both approaches are viable, have their compiler intelligence, many programming books, practices and frameworks written using them (and other tons of books about those frameworks) on different levels. So today the answer seems to be more a matter of taste and the knowledge of the actual programmer team than a properly founded, measured and verified statement on whether to use or not use types.

I think it is needless to say that I prefer rules to tricks, especially for long term, big team (aka: "serious") projects. Reason: as far a I know, the most likely causes of a SW project failure/slip are: unclear requirements and poor design (80%! by a study I know), and only a few percent remains for actual coding. All rules and contracts enforce cleaner design, thinking forward, and requires the decisions to be made earlier and by the proper people. Types mean rules: less "freedom" and "coolness" - more preparation, thinking, coding standards, controlled teamwork. To me, this sounds like a required factor of success, and also "home, sweet home".

My 2 cents.

Title: Why do variables need a type?

Body:
So we write:

```<code>Customer c = new Customer();
</code>```

Why is the design not such that we write:

```<code>c = new Customer();
c.CreditLimit = 1000;
</code>```

The compiler can work out c points to a Customer and allow Customer's members to be invoked on c?

I know we may want to write:

```<code>IPerson c = new Customer();
IPerson e = new Employee();
</code>```

so as to be able to write:

```<code>public string GetName(IPerson object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);
</code>```

But if we wrote:

```<code>c = new Customer();
e = new Employee();
</code>```

we could still write:

```<code>public string GetName(object)
{
    return object.Name
}

string name = GetName(c); // or GetName(e);
</code>```

The compiler could complain about the code immediately above if the type of object c references does not support a Name property (as it can check which members are used on the argument/parameter within the method), or the runtime could complain.

Even with C#'s dynamic keyword, we are still using a variable 'type' (determined at runtime). But why does a variable need a type at all? I am sure there must be a good reason, but I can't think of it!


答: There is the hardware architecture perspective. By writing your code by initializing and avoiding the branch to the else clause, you avoid gratuitously polluting the branch prediction table. For your relatively trivial example, it doesn't matter because no matter what you do, you have to do the comparison and branch. </p>


问:
Scoring/analysis of Subjective testing for skills assessment
I am lucky in the sense that I have been given the opportunity to be a 'Technical Troubleshooter' for our offshore development team. While I am confident and capable of dealing with most issues, I have come across something that I am not. Based on initial discussions with various team members both on and offshore, a requirement for a 'repeatable, consistent' skills assessment has been identified.

In my opinion, the best way to achieve this would be a combination of objective and subjective tests. The former normally being an initial online skills assessment on various subjects, for example General C#, WCF and MVC. The latter being a technical test where the candidate would need to solve various problems and (hopefully) explain the thought processes involved with the  solution whilst doing so.

Obviously, the first method is consistent, repeatable and extremely accurate. The second is always going to be subjective and based on the approach, the solution (or possibly not) and other factors. The 'scoring' of this is also going to be down to the experience and skills of the assessor and this is where my problem lies;

The person that is expected to be the assessor initially (me) has no
experience.

The people that will ultimately continue this process for other
people will never remain the same due to project constraints and
internal reasons, this changes the baseline for comparison.

I am not aware of any suitable system that can be classed as
consistent and repeatable for subjective tests with the 2 factors
above, let alone if those did not exist.

So anyway, I have to present a plan that will ultimately generate a skills/gap analysis and it is unlikely that I will be able to use an objective method (budget constraints most likely reason). The only option left is the subjective methods and the issues above.

Does anyone have any suggestions for an approach that may tick all the boxes?

答:
With regard to assessing talent, let me point you at Joel Spolsky's book, "Smart and Gets Things Done".  It is a good, quick read and among other things, stresses that the range of ability between applicants may vary by a factor of 10, 20, or even more.

Having many times interviewed candidates for software development positions, I find candidates are pretty good at differentiating themselves in both subjective and objective tests.  Unless you are hiring a great many positions, you might benefit by weighing the cost of an automated test vs. a manually administered test.

I would like to suggest an approach borrowed from software testing that is called operational profile based testing (OPT).  In OPT, we identify and operational profile (OP) by observation what features are used most often.  To refer to the Spolsky book in which he describes a Yale programming class that had developers write some pretty mundane programs with names like CMDLINE99, MAKE01, or TAR00 to show they could, and measure how fast (i.e. productive) they could be, but the instructor considered his programs to be typical of what professionals had written previously and what his students would write later.

To make an operational profile for the questions or programming problems for your candidates, pair program or just spend an hour or two watching a good performer in a similar role.  Sample the activities and code that they do.  Discuss problems they are solving, and jot down vocabulary that might differentiate between novice and expert.

If the test is well designed, I suspect success on this kind of test could correlate strongly to fluency in key skills, low need for supervisory assistance, and the ability to complete most portions of the task in a timely fashion.

Hope this helps, thanks for reading this answer.


答:
When I go to the machine, which button should I press: Coffee or Tea? Well, it depends on what I want to drink: coffee or tea... :-)

When I want to express that variable "var" is by default should get value "A", but in some cases it can be "B" or "C", I set the initialization value to "A".

When the code is responsible to set "var" to a specific value without any default, I leave it uninitialized - that will even give a nice compiler warning if there is a forgotten path. Although I never used this technique, 'final' keyword can ensure that the variable is initialized only once (in Java).

But what I suggest you never ever omit is the { } around ANY block (even if it "can be a single statement" by the language definition). I have already wasted too much time on things like "I thought it will be a single line" or "I did not know there will be another if-else around/inside this", in my own and in others' codes. Indenting is not a compiler operation, but an eye candy, even if your IDE supports it. When you create a block, notify the compiler about it... typing two more characters does not hurt that much.


问:
Why does PHP have interfaces?
I noticed that as of PHP5, interfaces have been added to the language. However, since PHP is so loosely typed, it seems that most of the benefits of using interfaces is lost. Why is this included in the language?</p>

答:
Interfaces is a part of OOP paradigm. So it's very useful in many cases when you trying to make object oriented parts or your system.

So. Why not? ;-)

Examples:
You need to cache your data. How? There is a lot of different engines for caching, which one is the best? Who cares if you have abstract layer which have some ICacheDriver interface with a set of methods like key, get, put, clear, etc. Just implement to it what you need in current project and change it when you need another.
Or simple usage of toString. You have a set of different showable objects. You just implement Stringable interface (which describes toString method [there is no really interfaces like that in PHP, but for example]) and just interating over all your object with (string)$obj. There is all you need to do instead of switch (true) { case $obj isntanceof A1: "do 1"; break; ... }

Simple. So there is no question "Why?". There is "how to use that better?". ;-) Good luck.

Title: Why does PHP have interfaces?


问:
How do you organize highly customized software?
I'm working on a large software project which is highly customized for various customers arround the world. This means that we have maybe 80% code which is common between the various customers, but also a lot of code which has to change from one customer to the other. In the past we did our development in separate repositories (SVN) and when a new project started (we have few, but large customers) created another repository based on whatever past project has the best code basis for our needs. This has worked in the past, but we ran into several problems:

Bugs which are fixed in one repository are not patched in other repositories. This might be a problem of organization, but I find it difficult to fix and patch a bug in 5 different repositories, keeping in mind that the team maintaining this repository might be in another part of the world and we don't have their test environment, neither know their schedule or what requirements they have (a "bug" in one country might be a "feature" in another).

Features and improvements made for one project, which might also be useful for another project are lost or if they are used in another project often cause big headaches merging them from one code base to another (since both branches might have been developed independently for a year).

Refactorings and code improvements made in one development branch are either lost or cause more harm than good if you have to merge all these changes between the branches.

We are now discussing how to solve these problems and so far came up with the following ideas on how to solve this:

Keep development in separate branches but organizing better by having a central repository where general bug fixes are merged into and having all projects merge changes from this central repository into their own on a regular (e.g. daily) basis. This requires huge discipline and a lot of effort for merging between the branches. So I'm not convinced that it will work and we can keep this discipline, especially when time pressure puts in.

Abandon the separate development branches and have a central code repository where all our code lives and do our customization by having pluggable modules and configuration options. We are already using Dependency Injection containers to resolve dependencies in our code and we are following the MVVM pattern in most of our code to cleanly separate business logic from our UI.

The second approach seems to be more elegant, but we have many unsolved problems in this approach. For example: how do handle changes/additions in your model/database. We are using .NET with Entity Framework to have strongly typed entities. I don't see how we can handle properties which are required for one customer but useless for another customer without cluttering our data model. We are thinking of solving this in the database by using satellite tables (having a separate tables where our extra columns for a specifiy entity live with a 1:1 mapping to the original entity), but this is only the database. How do you handle this in code? Our data model lives in a central library which we would not be able to extend for each customer using this approach.

I'm sure that we are not the only team struggling with this problem and I'm shocked to find so little material on the topic.

So my questions are the following:

What experience do you have with highly customized software, what approach did you choose and how did it work for you?

What approach do you recommend and why? Is there a better approach?

Are there any good books or articles on the topic that you can recommend?

Do you have specific recommendations for our technical environment (.NET, Entity Framework, WPF, DI)?

Edit:

Thanks for all the suggestions. Most of the ideas match those that we already had in our team, but it is really helpful to see the experience you had with them and tips to better implement them.

I'm still not sure which way we will go and I'm not making the decision (alone), but I will pass this along in my team and I'm sure it will be helpful.

At the moment the tenor seems to be a single repository using various customer specific modules. I'm not sure our architecture is up to this or how much we have to invest to make it fit, so some things might live in separate repositories for a while, but I think it's the only longterm solution that will work.

So, thanks again for all responses!

答:
The second approach seems to be more elegant, but we have many
  unsolved problems in this approach.

I am sure any of those problems can be solved, one after a another. If you get stuck, ask here on or on SO about the specific problem.

As others have pointed out, having one central codebase / one repository is the option you should prefer. I try to answer your example question.

For example: how do handle changes/additions in your model/database. We are using .NET with Entity Framework to have strongly typed entities. I don't see how we
  can handle properties which are required for one customer but useless
  for another customer without cluttering our data model.

There are some possibilities, all of them I have seen in real-world systems. Which one to choose depends on your situation:

live with the cluttering to a certain degree

introduce a tables "CustomAttributes" (describing names and types) and "CustomAttributeValues" (for the values, for example stored as a string representation, even if they are numbers). That will allow to add such attributes at install time or run time, having individual values for each customer. Don't insist on having each custom attribute modeled "visibly" in your data model.

now it should be clear how to use that in code: have just general code for accessing those tables, and individual code (perhaps in a separate plug-in DLL, which is up to you) for interpreting that attributes correctly

another alternative is to give each entity table a big string field where you can add an individual XML-string.

try to generalize some concepts, so they could be more easily reused across different customers. I recommend Martin Fowler's book "Analysis patterns". Though this book is not about customizing software pre se, it may be helpful for you either.

And for specific code: you can also try to introduce a scripting language into your product, especially for adding customer-specific scripts. That way you do not only create a clear line between your code and customer-specific code, you can also allow your customers to customize the system to some degree by themselves.


答:
Probably the most important thing to avoid is using constructs that change state.

Many people who start learning functional programming try to "emulate" imperative thinking in a functional language. This results in poor programs that make them feel that functional languages are cumbersome and ineffective. So it's important to get rid of imperative thinking. Don't think about the steps the program should do, think about expressions (functions), what they mean, and how to combine them to get the desired result.

Also, don't be too concerned about the effectiveness of your program at the beginning. Imperative programmers often feel that creating new instances of data structures each time they want to "change" something must make the program slow and ineffective. Functional languages are well optimized for that.

As stated in another answer,  F#, OCaml, Scala and many other functional languages allow state-changing constructs, side effects and imperative sequences of statements. On the other hand, Haskell doesn't permit that and so you have no choice but to learn how to do it in a purely functional way. (I've seen many people describing it as "rewiring one's brain".)

Body:
I have 6 years of programming experience, mostly following the object oriented paradigm, and I'm interested in learning functional programming. My main goal is to become a functional paradigm programmer and not a programmer who is using a functional language but still writes in imperative style.

When I'm practising in functional programming I still follow an object oriented way of thinking, like loops, mutable variables and so on. I picked F# as a basic functional language and because it's very tightly integrated with other .Net languages, like C#. F# allows usual object oriented statements, therefore you can use F# syntax but not actually produce functional code.

What statements and approaches should I avoid when learning functional programming?


问:
how do I know I've split my program into too small pieces?
Ever since entering the world of programming, I've been bombed with tips like "file should be only x lines", which is fair since new programmers tend to stuff everything into one file. But, having done programming professionally for more than a year now, I've mostly found myself getting hindered by the small size of the files, rather than than the large size of them. One of the biggest hindrances I have, is having to shuffle between 10-20 different files when investigating how something works, when some of those files contain only a couple of lines.

So I guess my question is: how do I know I've split my program into too small pieces?

答:
File size doesn't seem to be your problem - in real world development you'll eventually encounter projects that would have hundreds of files, even if every one of them contained serveral thousand lines of code.

If working with many files is a problem, you need better organization and tooling. Modern IDEs have many features that help with that (e.g. when programming Java in eclipse, "Open Call Graph" will bring tears of joy to your eyes if you haven't seen it before), so learn to use one of those well. As for organization, well-designed code should have low coupling and high cohesion, which means that code that does related things is close together (high cohesion) and to understand a given piece of code you don't need to look at many others (low coupling).

All that being said, the average size of a file in well-designed code should be perhaps 300 lines of code, give or take (depends on the language too). There is no minimum: sometimes the design calls for an empty class.


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

答: Depending on your service contract, the cost.</p>


答: Instead of having to shuffle with 20 files, you'd have to shuffle with 20 locations in the same file. In my experience, editors make it easier to shuffle with 20 files and keeping some context -- such as the cursor position -- for each than to shuffle with 20 locations in the same file and trying to keep some context for each. You'll have trouble to even jump easily from one to the other.</p>

Body:
Ever since entering the world of programming, I've been bombed with tips like "file should be only x lines", which is fair since new programmers tend to stuff everything into one file. But, having done programming professionally for more than a year now, I've mostly found myself getting hindered by the small size of the files, rather than than the large size of them. One of the biggest hindrances I have, is having to shuffle between 10-20 different files when investigating how something works, when some of those files contain only a couple of lines.

So I guess my question is: how do I know I've split my program into too small pieces?


问:
What do employers look for in self-taught applicants?
I'm a self-taught programmer about to enter the job market. What I want to know is what is the best way to show my experience to employers?

What do employers want to know about my programming experience? Do employers want to look at code I wrote or could they want to see the software in action? Or do they only care how much my software is being used/how much it has created revenue? Should I write about my design and programming style?

My background: I recently graduated from a university where I studied foreign languages, and it was during this time when I found out that programming is the thing I really want to do. Currently I'm a garage programmer, developing a software for a client for commercial use while continuing to self-teach myself, but my aim is to start a "proper" employment and career. As an added twist I live in Finland at the moment, but I'm looking for employment in China or Japan (I learned both languages while studying abroad).

答:
I would say that employers look for these things in all programmer applicants (this is coming from my own experience as the head developer who is screening applicants):

Ability to be flexible and learn new technologies fast (this is especially important for self-taught programmers)

Ability to communicate problems

Ability to solve algorithmic and logistic problems (important for analyst programmers)

Ability to conform to the standards and rules by the local busines, ie. dont be too stuck in your ways, be sure to follow the naming conventions of the business you work for.

Honest and hard working.

In a lot of cases the bigger companies will ask you to provide an applicant exercise. These exercises range in difficulty but one example might be to code a reusable module which converts an amount in dollars to an English readable string of text which would be written on a cheque for that amount, ie. "$999.34" to "Nine hundred and ninety-nine dollars and thirty-four cents".

It is important to note that it's not just the code they will be looking at in these exercises, but also the documentation that comes with it, ie. doco that explains the problems, the assumptions, and the algorithm used. They will also be looking at your naming conventions (mainly checking for consistency) and checking for clear code commenting.


答:
What do employers want to know about my programming experience?

Chiefly, that you have some. Put yourself in their shoes: if you were hiring somebody, would you pick the guy who might not know what to do with a compiler, or the guy who has been around the block a few times, learned to solve problems, and can get some useful work done without a lot of hand holding?

Do employers want to look at code I wrote or could they want to see the software in action?

Yes. Having some code to show can be helpful. Having a working product to show, and being prepared to answer questions about how it works, why you did it that way, etc. can also be helpful. Different employers will value these things differently, but it's always better to have something than to have nothing.

As an added twist I live in Finland at the moment, but I'm looking for employment in China or Japan (I learned both languages while studying abroad).

There are a lot of people in China and Japan who speak Chinese and Japanese, respectively. Probably not so many who speak English and Finnish fluently too. Use that strength to your advantage -- look for companies that need those language skills.

Title: What do employers look for in self-taught applicants?

Body:
I'm a self-taught programmer about to enter the job market. What I want to know is what is the best way to show my experience to employers?

What do employers want to know about my programming experience? Do employers want to look at code I wrote or could they want to see the software in action? Or do they only care how much my software is being used/how much it has created revenue? Should I write about my design and programming style?

My background: I recently graduated from a university where I studied foreign languages, and it was during this time when I found out that programming is the thing I really want to do. Currently I'm a garage programmer, developing a software for a client for commercial use while continuing to self-teach myself, but my aim is to start a "proper" employment and career. As an added twist I live in Finland at the moment, but I'm looking for employment in China or Japan (I learned both languages while studying abroad).


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
Because the basic explanation of OOP has very, very little to do with how it's used in the field. Most programs for teaching it try to use a physical model, such as "Think of a car as an object, and wheels as objects, and the doors, and the transmission ...", but outside of some obscure cases of simulation programming, objects are much more often used to represent non-physical concepts or to introduce indirection. The effect is that it makes people understand it intuitively in the wrong way.

Teaching from design patterns is a much better way to describe OOP, as it shows programmers how some actual modeling problems can be effectively attacked with objects, rather than describing it in the abstract.

Title: Why is OOP difficult?


答:
Once you can demonstrate you have written quality code, how and where you learned to program is less important. You built the entire application, so you should be able to explain the design, the problems you faced and why you chose those solutions.

If your application isn't well-known, you'll have to give more explanation in your CV and cover letters. Having a large number of users is a benefit because it shows you can handle scale, the revenue generated is going to be difficult to add any benefit. Someone could hire a programmer to create an appliation using horoscopes to help brain surgeons. Not sure I would hold the programmer responsible for this useless product. Maybe a startup would prefer a dev with some product sense, but they can't hold it against you because you need to pay your bills.


答:
I would suggest that file size isnt really that important, to me object complexity and function / method size is a lot more important. Assuming you are using an object oriented language, just be sure to make objects that have a clear function and be sure that they only have code for those specific functions.

As a general rule dont have any method / function that is longer than 25 lines (Excluding comment lines), if it is longer than that break it up.

As for the files themselves, they become irrelevant if you follow the tips above because you can always break them up later, but try to separate the files logically, or do what a lot of languages do as a guidline and put one class to a file, if its a procedural language, try to break up functionality using the files, ie. IO in one file, UI in another file and so on.

Just my 2c.

Title: how do I know I've split my program into too small pieces?


问:
Omit terminating semicolon in a tag - a good idea?
It's possible to omit the terminating semicolon in a tag.

Example:

```<code><table>
  <th><td>Name</td><td>Email</td>
  <? foreach ($receivers as $receiver): ?>
  <tr>
    <td><?= $receiver->name ?></td>
    <td><?= $recevier->email ?></td>
  </tr>
  <? endforeach ?>
</table>
</code>```

Note the <? endforeach ?> without a semicolon after endforeach. The PHP Documentation  says:

The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block.

Why am I bringing up this subject?

Currently I and a friend of mine work in a proprietary PHP project with MVC (model-view-controller). For the view I evaluated some PHP template engines like Smarty, Moustache and even designed my own home-grown template engine. But when I read that PHP is a template engine in itself something went «click» in my head. Why not just agree in the team to use a limited subset of PHP as a template engine? And having many code reviews to keep up the rules?

And this subset could look like this:

Use only short tags <?, <?= and ?>

Use only simple expressions without side effects, especially don't assign variables

Use only if, foreach, and include for statements

Use only the alternative syntax for control structures

Have only one statement in a tag each

This is the context where we are omitting the terminating semicolon, namely for <? endforeach ?>, <? endif ?> and <? include("list-contents.php") ?>.

However I read often that omitting terminating semicolons is a bad practice. Why? Is it a bad practice at all?

I am happy that PHP allows omitting the terminating semicolon because this minimizes the visual clutter in the template files. They should look mostly like HTML files with only tiny PHP fragments here and there. The example above is what I am striving for.

What do you think about this? If you are against it: why? If you support it: Why would it be a good idea? What should I tell my partner if he is referring me some text against omitting the semicolon?

Please back up your opinion with facts, references or your own experience.

答: I'm all for omitting them in this case, and I do exactly that, specifically because in this context I only use one single-line statement per  or  block. It reduces visual clutter and in all my years of doing this, has never resulted in a single issue.</p>


答:
Learning functional programming is not about applying what you know from imperative and object-oriented programming and leveraging that to learn functional programming. In your question you are asking what to avoid, when I believe you should be thinking is: To learn functional programming I realize I should totally set aside what I know about imperative programming; where should I start.

As some starting advice see How to make the transition to functional programming?

So don't convert imperative code to functional code. If an algorithm is amiable to functional programming then use functional programming. If an algorithm is amiable to imperative programming then use imperative programming.

To answer your question more specifically

Instead of selection statements use pattern matching.

Instead of iteration statements use recursion.

Instead of objects use discriminated unions.

Instead of .NET collections, use F# types such as F# list  (which are different from .NET list), tuples, etc. Note: objects are based on classes which are typically heap based and preserve state while F# types are based on structures which are typically stack based, are optimized for use with F#, and typically immutable.

In the object-oriented world objects are king, in the functional world functions are king.

Title: What statements and approaches should I avoid when learning functional programming?


答:
I think it is a good idea to use PHP, or at least a subset of, as a template language.  It will be easier for new developers to be integrated with your system as there's no special library syntax to learn and you don't have the overhead of that library parsing your template just to turn it into PHP.

Also, you missed a context in which you would need to eliminate the terminating semi-colon in your variable echo statements as well, e.g. <?= $receiver->name ?>.  If you're going to not use semi-colons in your templates then you really need to not use them.  Clearly your code example doesn't use them but I just wanted to point out the missing context in which not to use terminating semi-colons.

The really important thing is having team buy-in and ensuring consistency across your templates.  Personally, I find it jarring to not have the semi-colon...I instinctively want to add those semi-colons into all your PHP statements.  Do you have a person on your team with the same level of OCD?  How will they react to this?  If your team doesn't have buy-in and one or two people are vehemently against it, make them defend their decision, then maybe this isn't the best way to go.

Another potential pitfall would be incorporating new team members.  They may very well not realize you can even do this, go back in your templates and insert all the terminating semi-colons where appropriate.  Obviously this is a case of a developer not knowing as much about PHP as they should but it is something that you'd want to weigh in your decision.  Educating new, junior developers that in templates we don't use terminating semi-colons but other code we do.

tl;dr

Get buy-in from your team, ensure your templates are consistent and have a reasonable plan to educate new developers on how PHP code in templates differ from "normal" PHP code (alternative syntax, no terminating semi-colon, allowed PHP structures, etc).

Title: Omit terminating semicolon in a tag - a good idea?

Body:
It's possible to omit the terminating semicolon in a tag.

Example:

```<code><table>
  <th><td>Name</td><td>Email</td>
  <? foreach ($receivers as $receiver): ?>
  <tr>
    <td><?= $receiver->name ?></td>
    <td><?= $recevier->email ?></td>
  </tr>
  <? endforeach ?>
</table>
</code>```

Note the <? endforeach ?> without a semicolon after endforeach. The PHP Documentation  says:

The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block.

Why am I bringing up this subject?

Currently I and a friend of mine work in a proprietary PHP project with MVC (model-view-controller). For the view I evaluated some PHP template engines like Smarty, Moustache and even designed my own home-grown template engine. But when I read that PHP is a template engine in itself something went «click» in my head. Why not just agree in the team to use a limited subset of PHP as a template engine? And having many code reviews to keep up the rules?

And this subset could look like this:

Use only short tags <?, <?= and ?>

Use only simple expressions without side effects, especially don't assign variables

Use only if, foreach, and include for statements

Use only the alternative syntax for control structures

Have only one statement in a tag each

This is the context where we are omitting the terminating semicolon, namely for <? endforeach ?>, <? endif ?> and <? include("list-contents.php") ?>.

However I read often that omitting terminating semicolons is a bad practice. Why? Is it a bad practice at all?

I am happy that PHP allows omitting the terminating semicolon because this minimizes the visual clutter in the template files. They should look mostly like HTML files with only tiny PHP fragments here and there. The example above is what I am striving for.

What do you think about this? If you are against it: why? If you support it: Why would it be a good idea? What should I tell my partner if he is referring me some text against omitting the semicolon?

Please back up your opinion with facts, references or your own experience.


答:
Use only short tags

No. Please god no! Relying on short open tags is a terrible idea. It only makes your code less portable. Short open tags aren't enabled by default on many many systems. And what if you want to share the code to someone who has them disabled? Besides nothing is gained from short open tags IMHO.

Use only the alternative syntax for control structures

I fail to see what you would gain from that. Besides not having a consistent code base.

Have only one statement in a tag each

That might also make things messy. When you have some "template" cluttered with open / close tags everywhere.

Why not just agree in the team to use a limited subset of PHP as a template engine?

That depends who are on that team. E.g. will only people use it who know PHP? Or do you also have people on that team who need to change the templates who don't know PHP. If it is the first I would just relax on the requirements (a.k.a rules), because when people hit a problem they can easily solve with all the power PHP provides and you are going to limit them into solving it you would either have people breaking the rules or get very messy code. However if you have people in the team who don't know PHP you might get away with that just like that.

Now to answer you question:

However I read often that omitting terminating semicolons is a bad practice. Why? Is it a bad practice at all?

When coding (no matter what language and no matter what project) you always have to reduce the number of wtf's per minute in your code. So it is bad practise because when somebody looks at that they may think at first: hey something is strange there! It's just that PHP people are used that there are semicolons to close statements. So again this may be dependent of the people in your team (but you asked fer personal experience). Besides this it is also very very annoying to switch between syntaxes when people are working both on the frontend (the templates) as the backend. And is prone to both errors and annoyance in the team.

And finally about the fact that PHP allows you to do something: PHP allows you to do all sorts of things. Just this fact doesn't mean you should use it. There was a meta post once on Stack Overflow which about Stack Overflow not being the perfect example of its own rules (or something like that :) ) which could also be used for PHP. There is all sorts of FUBAR stuff in PHP (yes I've said it), but that shouldn't mean you should say: but but but PHP allows it. Guess what PHP also allows you to run queries without input sanitation. PHP also allows you to write all code on one single line. PHP also allows you to make variable names like $S0mEvAriBLe. All these things don't mean it is the best thing to do.

My 2 cents


问:
Can we guarantee a program will never go wrong?
We have a system here. Recently there is a wrong calculation in one of the number in the report generated by the system. Through out our experience, we've never encounter any problem/error in this system for some years.

Because the writer of this system had already gone, we can hardly trace the programs. But we've verify the input data, the setting and they are right.

Now my question is, will a computer program suddenly go wrong without any logical reason? If I slam on the server machine, will one of the number which the computer is calculating, become another number and make the calculation wrong?

I agree my idea there is quite mad, but I just want to know, how can we know the problem is not caused by the program and the input, but some other factors?

P.S. This mad system has no log.

答:
Now my question is, will a computer program suddenly go wrong without any logical reason? If I slam on the server machine, will one of the number which the computer is calculating, become another number and make the calculation wrong?

The answer to that question is unknowable. It is impossible to prove that anything is always true of the universe we happen to live in. Instead we make assumptions and prove that if the assumptions hold, then some complicated property will also hold. This is what formally verified programs guarantee. Most programs are not formally verified though, they instead try to build confidence by providing tests. These tests give you assurance that provided the tests do what they were designed to do and that the assumptions that you've made hold, the program you are using will work at least some of the time.


答:
Having an EE minor and a CS major, I've worked with both groups academically. I've never held a job where I designed EE style products, but I've consumed a lot of them doing work for companies with things like PLC, and so having been able to understand (from an educational background) what as occurring was nice. So I can't say that I know 100% about workplace behavior and characteristics, but I can describe the academic differences between the two to some extent.

EE folks tend to focus on the details, and they tend to know the exact implementation. If it's not 100% mappable, they don't like it. EE folks will optimize down to remove unnecessary details if they can.

SE folks tend to like layers and compartmentalization of logic. SE folks don't mind bloated projects. SE folks tend to be very math oriented. They tend to think in terms of equations and how to solve problems from a pattern concept. Joins are more intuitive to this group, like database work. The further SE you go the more you tend to see people who are fluent with things like Functional Programming. That's just not safe ground for an EE person.

Both folks know about stuff like Karnaugh maps so there's plenty of overlap in those areas. Logic reduction, that sort of thing.

Ok, so that's my subjective answer. Hope it helps.

Title: EE vs Computer Science: Effect on Developers' Approaches, Styles?

Body:
Are there any systematic differences between software developers (sw engineers, architect, whatever job title) with an electronics or other engineering background, compared to those who entered the profession through computer science?

By electronics background, I mean an EE degree, or a self-taught electronics tinkerer, other types of engineers and experimental physicists.

I'm wondering if coming into the software-making professions from a strong knowledge of flip flops, tristate buffers, clock edge rise times and so forth, usually leads to a distinct approach to problems, mindsets, or superior skills at certain specialties and lack of skills at others, when compared to the computer science types who are full of concepts like abstract data types, object orientation, database normalization, who speak of "closures" in programming languages - things that make little sense to the soldering iron crowd until they learn enough programming.

The real world, I'm sure, offers a wild range of individual exceptions, but for the most part, can you say there are overall differences?   Would these have hiring implications e.g. (to make up something) "never hire an electron wrangler to do database design"?   Could knowing about any differences help job seekers find something appropriate more effectively?   Or provide enlightenment or some practical advice for those who find themselves misfits in a particular job role?

(Btw, I've never taken any computer science classes; my impression of exactly what they cover is fuzzy.   I'm an electronics/physics/art type, myself.)


问:
What useful expressiveness will be impossible in a language where an expression is not a statement?
I am contemplating writing a programming language. Most grammars define expressions as being a kind of a statement. But really I cannot come up with a single example of any useful expression that would pass as a statement.

See https://stackoverflow.com/questions/19132/expression-versus-statement for an easy definition of expression vs statement.

EDIT: Why are so many grammars making the distinction between expr and stmt when as noted in the answers, it makes no sense.

答:
A function/method call is, of course, an expression. At the same time (in imperative programming languages, which I assume since you seem to take statements for granted) many functions have side effects and those side effects are often enough incentive to call the function. Consider functions like printf which exist primarily for their side effect and whose return value (in this case, number of chars printed) is usually not interesting. Or basically any function/method with no interesting return value -- i.e. void or () AKA unit. (While you could, in a statically-typed setting, differentiate between the two, doing so is entirely pointless.)

In languages with operator overloading, this extends to any expressions involving operators (read: almost all expressions), because these are basically functions as above, only called differently. Sometimes a bad idea, yes, but then there's embedded DSLs.

Also, if you make assignment an expression (bad idea IMHO, but rather common), you practically need it to also be valid as statement. Ditto for pre- and post-increment and -decrement -- these are expressions, yet mostly useful as standalone statements.

EDIT: As for why the distinction exists: Statements are distinct from expression so the grammar can prevent statements from being used as expressions. An example in Python: The "expression"

```<code>f(def g():
    pass
)
</code>```

has multiple problems (primarily: does not work with the - otherwise great and simple - way indentation is handled; can be easily turned into a inner function definition) which make it utterly useless. For comparision, def g(): pass; f(g) is perfectly valid and sometimes (if f wants a callback and you want a no-op for that) useful. And not all languages accept every expression as statement -- many either rule out alternatives which never make sense (cf. Pascal, C#), or give a warning ("statement has no effect").

Body:
A function/method call is, of course, an expression. At the same time (in imperative programming languages, which I assume since you seem to take statements for granted) many functions have side effects and those side effects are often enough incentive to call the function. Consider functions like printf which exist primarily for their side effect and whose return value (in this case, number of chars printed) is usually not interesting. Or basically any function/method with no interesting return value -- i.e. void or () AKA unit. (While you could, in a statically-typed setting, differentiate between the two, doing so is entirely pointless.)

In languages with operator overloading, this extends to any expressions involving operators (read: almost all expressions), because these are basically functions as above, only called differently. Sometimes a bad idea, yes, but then there's embedded DSLs.

Also, if you make assignment an expression (bad idea IMHO, but rather common), you practically need it to also be valid as statement. Ditto for pre- and post-increment and -decrement -- these are expressions, yet mostly useful as standalone statements.

EDIT: As for why the distinction exists: Statements are distinct from expression so the grammar can prevent statements from being used as expressions. An example in Python: The "expression"

f(def g():
    pass
)

has multiple problems (primarily: does not work with the - otherwise great and simple - way indentation is handled; can be easily turned into a inner function definition) which make it utterly useless. For comparision, def g(): pass; f(g) is perfectly valid and sometimes (if f wants a callback and you want a no-op for that) useful. And not all languages accept every expression as statement -- many either rule out alternatives which never make sense (cf. Pascal, C#), or give a warning ("statement has no effect").


答:
If you refer to the definitions that are provided on those pages, its easy to see why its difficult to come up with an expression that would pass as a statement.

Expression: Something which evaluates to a value. Example: 1+2/x

Statement: A line of code which does something. Example: GOTO 100

The expression is only the subject of the statement. If you're not assigning it to something in the end, then there's not a whole lot you can do with it.

You might want to look into lisp though.

Title: What useful expressiveness will be impossible in a language where an expression is not a statement?

Body:
I am contemplating writing a programming language. Most grammars define expressions as being a kind of a statement. But really I cannot come up with a single example of any useful expression that would pass as a statement.

See https://stackoverflow.com/questions/19132/expression-versus-statement for an easy definition of expression vs statement.

EDIT: Why are so many grammars making the distinction between expr and stmt when as noted in the answers, it makes no sense.


问:
What exactly is "Web API" in ASP.Net MVC4?
I know what a Web API is.

I've written API's in multiple languages (including in MVC3).

I'm also well practiced in ASP.Net.

I just discovered that MVC4 has "Web API" and without going through the video examples I can't find a good explanation of what exactly it IS.

From my past experience, Microsoft technologies (especially ASP.Net) have a tendency to take a simple concept and wrap it in a bunch of useless overhead that is meant to make everything "easier".

Can someone please explain to me what Web API in MVC4 is exactly?  Why do I need it?  Why can't I just write my own API?

答:
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices.

ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

http://www.asp.net/web-api

EDIT:

Specifically, ASP.NET Web API includes:

A streamlined ASP.NET pipeline with reduced overhead if you choose to host your service in IIS.

HttpClient which makes it easier for a client to hook into the Web API.


答:
Others have already answered your direct question about self-taught applicants. However, there's another consideration that may be even more important than being self-taught or not. I'm talking about the cultures of countries you're planning to work and live in.

First off, never write "employment in China or Japan". It sounds like "Finland or Australia" (no offense). They are totally different, and you have to choose.

Also, employment in another country usually means higher taxes for a company, various limitations (e.g. hire one foreigner, have to hire N natives), and so on. So on order to be hired in China you have to be really good at what you're doing.

In fact, you have two best options:

Graduate in a country of your future. This will give you (a) knowledge in national standards; (b) business contacts; (c) formal diploma (which may be more important than you think). Also, likewise everywhere, big companies contact with universities to find most prominent students, and you have good chances to be the one.

Apply to a multinational company that has branches in China. You may speak with HR and agree to work on a local position for a certain time and then move within the same company (less paperwork). Having language and cultural background, it would be easier for you. And, by the moment of move, you will already have practical I.T. experience in the company.


答:
In short: ASP.NET Web API is making REST a first class citizen in .NET, which WCF was not really able to embrace. As you may know, ASP.NET Web API is a framework for building web APIs on top of the .NET Framework.

One of the biggest frustration we had as web developers was to face with the endless configurations with WCF. I mean, WCF is great but hasn’t been embraced the REST since the WCF Web API framework . There was something called REST Starter Kit but it ended up dead.

However, ASP.NET Web API is a next generation framework that makes it easy to build HTTP services that reach a broad range of clients, such as browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Framework. For more information and great blog posts, visit ASP.NET Web API bloggers page

Title: What exactly is "Web API" in ASP.Net MVC4?

Body:
I know what a Web API is.

I've written API's in multiple languages (including in MVC3).

I'm also well practiced in ASP.Net.

I just discovered that MVC4 has "Web API" and without going through the video examples I can't find a good explanation of what exactly it IS.

From my past experience, Microsoft technologies (especially ASP.Net) have a tendency to take a simple concept and wrap it in a bunch of useless overhead that is meant to make everything "easier".

Can someone please explain to me what Web API in MVC4 is exactly?  Why do I need it?  Why can't I just write my own API?


答:
Things like the traditional send call for sockets is a good example:

int send(int socket, char* buffer, int flags);

The 'bytes sent' return isn't strictly vital for the function to do its business.

You could of course say that not checking the bytes sent is an error and that your language should not allow that as input. The issue comes that parsing is done before the types are ever known. When parsing

send( socket, buffer, 0 );

your compiler has no idea if send returns a value or not. In most languages, that simple standalone expression is desirable to be allowed as a statement.


答:
I'd say the most important skills that self-taught programmers could lack without knowing it are the software engineering and software architecture related ones.

Make sure you know more than just writing code, make sure you know what is maintainability and how to achieve it; what is SOLID, why is it considered good and needed; design patterns, etc.

Also, try to fix any bad parts of your process. For example: automated testing (something everyone should do!), bug tracking, source revision control (also mandatory). This list is not meant to include everything, it's just an example.


答:
A Clue

Seriously, I look for just a few things in a candidate:

basic ability to program

interest in programming

understanding commensurate with education and experience

ability to learn

kindness

Examples: self-taught high-school graduate who has solved 50 Euler problems: easy hire.   MSCS with 4.0 GPA who can't explain the difference between TreeMap and HashMap: don't hire.


答:
I think there are a few of factors that haven't been mentioned yet.

First of all, at least in "pure OOP" (e.g., Smalltalk) where everything is an object, you have to twist your mind into a rather unnatural configuration to think of a number (for only one example) as an intelligent object instead of just a value -- since in reality, 21 (for example) really is just a value. This becomes especially problematic when on one hand you're told that a big advantage of OOP is modeling reality more closely, but you start off by taking what looks an awful lot like an LSD-inspired view of even the most basic and obvious parts of reality.

Second, inheritance in OOP doesn't follow most people's mental models very closely either. For most people, classifying things most specifically does not have anywhere close to the absolute rules necessary to create a class hierarchy that works. In particular, creating a class D that inherits from another class B means that objects of class D share absolutely, positively all the characteristics of class B. class D can add new and different characteristics of its own, but all the characteristics of class B must remain intact.

By contrast, when people classify things mentally, they typically follow a much looser model. For one example, if a person makes some rules about what constitutes a class of objects, it's pretty typical that almost any one rule can be broken as long as enough other rules are followed. Even the few rules that can't really be broken can almost always be "stretched" a little bit anyway.

Just for example, consider "car" as a class. It's pretty easy to see that the vast majority of what most people think of as "cars" have four wheels. Most people, however, have seen (at least a picture of) a car with only three wheels. A few of us of the right age also remember a race car or two from the early '80s (or so) that had six wheels -- and so on. This leaves us with basically three choices:

Don't assert anything about how many wheels a car has -- but this tends to lead to the implicit assumption that it'll always be 4, and code that's likely to break for another number.

Assert that all cars have four wheels, and just classify those others as "not cars" even though we know they really are.

Design the class to allow variation in the number of wheels, just in case, even though there's a good chance this capability will never be needed, used, or properly tested.

Teaching about OOP often focuses on building huge taxonomies -- e.g., bits and pieces of what would be a giant hierarchy of all known life on earth, or something on that order. This raises two problems: first and foremost, it tends to lead many people toward focusing on huge amounts of information that's utterly irrelevant to the question at hand. At one point I saw a rather lengthy discussion of how to model breeds of dogs, and whether (for example) "miniature poodle" should inherit from "full sized poodle", or vice versa, or whether there should be an abstract base "Poodle" class, with "full-size poodle" and "miniature poodle" both inheriting from it. What they all seemed to ignore was that the application was supposed to deal with keeping track of licenses for dogs, and for the purpose at hand it was entirely adequate to have a single field named "breed" (or something on that order) with no modeling of the relationship between breeds at all.

Second, and almost importantly, it leads to focusing on the characteristics of the items, instead of focusing on the characteristics that are important for the task at hand. It leads toward modeling things as they are, where (most of the time) what's really needed is building the simplest model that will fill our needs, and using abstraction to fit the necessary sub-classes to fit the abstraction we've built.

Finally, I'll say once again: we're slowly following the same path taken by databases over the years. Early databases followed the hierarchical model. Other than focusing exclusively on data, this is single inheritance. For a short time, a few databases followed the network model -- essentially identical to multiple inheritance (and viewed from this angle, multiple interfaces aren't enough different from multiple base classes to notice or care about).

Long ago, however, databases largely converged on the relational model (and even though they aren't SQL, at this level of abstraction the current "NoSQL" databases are relational too). The advantages of the relational model are sufficiently well known that I won't bother repeating them here. I'll just note that the closest analog of the relational model we have in programing is generic programming (and sorry, but despite the name, Java generics, for one example, don't really qualify, though they are a tiny step in the right direction).

Title: Why is OOP difficult?

Body:
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?


答:
The new Web API from Microsoft is, as its name suggests all about writing APIs that are web accessible, with a bent on REST.

Rick Strahl recently blogged about it and has a good analysis on when to use MVC vs Web API.

Things like built in content negotiation, several built in formats and more.


答:
"What useful expressiveness will be impossible in a language where an expression is not a statement?"

None.

The definitions of "expression" and "statement" are largely arbitrary. Different languages define them differently. I know of no programming language whose way of defining these terms makes any particular construct impossible to express. In some languages, some constructs may be a bit more awkward; in others, it may be easier to write code that's difficult to read because a single statement depends on multiple side effects.

Almost all programming languages are Turing-complete and are able to express the same behaviors as any other Turing-complete languages.

Two good examples are Pascal and C.

In Pascal, an assignment is a statement, not an expression. A subroutine can be either a procedure (which doesn't return a value) or a function (which does). A procedure call is a statement, and cannot be part of an expression. A function call is an expression, and cannot appear in a statement unless you explicitly do something with the result, such as assigning it to a variable. Statements can contain expressions, but expressions cannot contain statements.

In C, an assignment is an expression. All subroutines are functions; functions that return no value are declared with a return type of void. A function call is an expression; it can be made into a statement by adding a semicolon. The result of a function call, or of any expression, can be silently discarded. Any expression can be turned into a statement by adding a semicolon. As in Pascal, statements can contain expressions, but expressions cannot contain statements (but gcc provides statement expressions as a language extension).

Here's a typical C construct that depends on the ability to treat assignments as expressions (item is some arbitrary type, and last_item is a constant of that type):

```<code>item x;
while ((x = get_next_item()) != last_item) {
    do_something_with(x);
}
</code>```

In Pascal, you can implement exactly the same behavior like this (if I remember the syntax correctly):

```<code>var
    x: item;
    done: boolean = false;
begin
    while not done do
    begin
        x := Next_Item;
        if x = last_item then
            done := true
        else
            do_something_with(x);
    end;
end;
</code>```

Body:
"What useful expressiveness will be impossible in a language where an expression is not a statement?"

None.

The definitions of "expression" and "statement" are largely arbitrary. Different languages define them differently. I know of no programming language whose way of defining these terms makes any particular construct impossible to express. In some languages, some constructs may be a bit more awkward; in others, it may be easier to write code that's difficult to read because a single statement depends on multiple side effects.

Almost all programming languages are Turing-complete and are able to express the same behaviors as any other Turing-complete languages.

Two good examples are Pascal and C.

In Pascal, an assignment is a statement, not an expression. A subroutine can be either a procedure (which doesn't return a value) or a function (which does). A procedure call is a statement, and cannot be part of an expression. A function call is an expression, and cannot appear in a statement unless you explicitly do something with the result, such as assigning it to a variable. Statements can contain expressions, but expressions cannot contain statements.

In C, an assignment is an expression. All subroutines are functions; functions that return no value are declared with a return type of void. A function call is an expression; it can be made into a statement by adding a semicolon. The result of a function call, or of any expression, can be silently discarded. Any expression can be turned into a statement by adding a semicolon. As in Pascal, statements can contain expressions, but expressions cannot contain statements (but gcc provides statement expressions as a language extension).

Here's a typical C construct that depends on the ability to treat assignments as expressions (item is some arbitrary type, and last_item is a constant of that type):

item x;
while ((x = get_next_item()) != last_item) {
    do_something_with(x);
}

In Pascal, you can implement exactly the same behavior like this (if I remember the syntax correctly):

var
    x: item;
    done: boolean = false;
begin
    while not done do
    begin
        x := Next_Item;
        if x = last_item then
            done := true
        else
            do_something_with(x);
    end;
end;


答:
What do employers want to know about my programming experience? Do employers want to look at code I wrote or could they want to see the software in action?

Yes, these are the best options.  Qualifications aren't a particularly good indicator for ability to write code.  The same applies to previous employers - lots of people can scrape by in a job they are unsuited for.  I want to see what kind of code you write and a track history of being able to build stuff that has been put into production.

Or do they only care how much my software is being used/how much it has created revenue?

That's outside of your area of responsibilities, I don't care about that stuff unless you're going for a project manager role or higher.

Should I write about my design and programming style?

Not too much, but perhaps bullet points showing areas of interest with your code samples would be useful.


问:
Arrow => in Perl
What does the => mean in Perl?

```<code>my $CreateArray = [
objectClass => [ "top", "person", "organizationalPerson", "inetOrgPerson" ],
cn => "Jane User",
uid => "0000001",
sn => "User",
mail => "JaneUser@mycompany.com"
];
</code>```

produces

```<code>CreateArray:
0  'objectClass'
1  ARRAY(0x104ef40)
  0  'top'
  1  'person'
  2  'organizationalPerson'
  3  'inetOrgPerson'
2  'cn'
3  'Jane User'
4  'uid'
5  0000001
6  'sn'
7  'User'
8  'mail'
9  'JaneUser@mycompany.com'
</code>```

It seems that even numbers are keys and odd numbers are values. Why don't they use hashes? Because they aren't ordered? Is there a name for this strange structure?

Thank you.

答:
Generally, the "big arrow" (=>) in Perl is basically a comma, with one difference: everything on its left is treated as if it is quoted. So this:

```<code>Foo => Bar
</code>```

Is the same as:

```<code>'Foo', Bar
</code>```

For more info, see perlop.

Title: Arrow => in Perl

Body:
Generally, the "big arrow" (=>) in Perl is basically a comma, with one difference: everything on its left is treated as if it is quoted. So this:

Foo => Bar

Is the same as:

'Foo', Bar

For more info, see perlop.


问:
Android, OpenGL and extending GLSurfaceView?
This question is part-technical, part-meta, part-subjective and very specific:

I'm an indie game dev working on android, and for the past 6 months I've struggled and finally succeeded in making my own 3D game app for android. So I thought I'd hop on SO and help out others struggling with android and openGL-ES

However, the vast majority of questions relate to extending GLSurfaceView. I made my whole app without extending GLSurfaceView (and it runs fine). I can't see any reason at all to extend GLSurfaceView for the majority of questions I come across.

Worse, the android documentation implies that you ought to, but gives no detailed explaination of why or what the pros/cons are vs not extending and doing everything through implementing your own GLSurfaceView.Renderer as I did

Still, the sheer volume of questions where the problem is purely to do with extending GLSurfaceView is making me wonder whether actually there is some really good reason for doing it that way vs the way I've been doing it (and suggesting in my answers to others to do).

So, is there something I'm missing? Should I stop answering questions in the meantime?

Android openGL documentation

答:
At least one good reason to extend GLSurfaceView is to be able to instantiate it directly from a layout xml file, just as any other widget:</p>

```<code>    <RelativeLayout ... >
      <com.example.MyGlSurfaceView
        android:id="@+id/my_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
      />
     </RelativeLayout>
</code>```

Body:
At least one good reason to extend GLSurfaceView is to be able to instantiate it directly from a layout xml file, just as any other widget:

    <RelativeLayout ... >
      <com.example.MyGlSurfaceView
        android:id="@+id/my_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
      />
     </RelativeLayout>


问:
Order of subject and modifiers in variable names
I'm looking for experiences regarding the ordering of the subject and modifiers in variable names.

A simple object Shape would have just a subject for the variable name, such as Area.

A slightly more complex case Sphere which has a wall will have an inner volume and an outer volume, which is where my question comes into play.

What's preferred between Modifier-Subject or Subject-Modifier?

As an example set:

```
class Containers_Modifier_Subject
{
  AreaAdjustmentFactor
  WallThickness
  Height
  Length
  Width
  AdjustedArea
  SurfaceAreaInner
  SurfaceAreaOuter
  LongWallArea
  ShortWallArea
  TopArea
  InnerVolume
  OuterVolume
}

class Containers_Subject_Modifier
{
  AreaAdjustmentFactor
  WallThickness
  Height
  Length
  Width
  AreaAdjusted
  AreaInnerSurface
  AreaOuterSurface
  AreaLongWall
  AreaShortWall
  AreaTop
  VolumeInner
  VolumeOuter
}
```

The trigger for my question comes from an object that is similar to the examples.  There were enough variables in the object that only a portion displays in the code ahead / lookup window from the IDE.  I want to make sure that any future developer is quickly led to the correct variable that they'll be looking for without having to scroll up and down through the lookup window.

In my case, I was looking for the total area, but the area factor and adjusted area values had popped up first.

Consistency in naming as a code standard is a given.

Which naming approach has been:

most maintainable?

more easily understood?

semantically correct?

i.e. how well does the variable name match the business object and how well does the variable name flow into conversations about the problem being solved?

conducive to being used with code lookup functionality like Intellisense or the various Eclipse based constructs?

答:
In my API's I always use names that describe what I expect the user to type: TotalArea instead of AreaTotal, but WallCount instead of CountWall, as the latter examples are improper English.

Using subject-modifier is something designers do only to satisfy IntelliSense, as typing Area would then result in a list of only those things dealing with area - which is nice - but this does not warrant using strange names. A much better option would be to separate the properties of an area into a separate Area object. This makes the API cleaner, the class shorter, and improves reusability and testability. Your example class would then become:

```
WallThickness
Height
Length
Width
Area
Volume
```

To conclude: use the word order you'd use when writing it in normal English. If you have multiple such prefixed properties, fields (and methods), consider putting those members together in a related class. This improves maintainability (testability and reusability), allows IntelliSense to suggest only relevant area members after typing Area., and makes the objects match their business objects more closely (in most cases).

And never ever use a particular coding convention only to satisfy your programming envionment (e.g. code completion in Visual Studio or Eclipse).

Body:
In my API's I always use names that describe what I expect the user to type: TotalArea instead of AreaTotal, but WallCount instead of CountWall, as the latter examples are improper English.

Using subject-modifier is something designers do only to satisfy IntelliSense, as typing Area would then result in a list of only those things dealing with area - which is nice - but this does not warrant using strange names. A much better option would be to separate the properties of an area into a separate Area object. This makes the API cleaner, the class shorter, and improves reusability and testability. Your example class would then become:

WallThickness
Height
Length
Width
Area
Volume

To conclude: use the word order you'd use when writing it in normal English. If you have multiple such prefixed properties, fields (and methods), consider putting those members together in a related class. This improves maintainability (testability and reusability), allows IntelliSense to suggest only relevant area members after typing Area., and makes the objects match their business objects more closely (in most cases).

And never ever use a particular coding convention only to satisfy your programming envionment (e.g. code completion in Visual Studio or Eclipse).


问:
How can uTorrent be multi-platform while keeping such a small binary size?
Nowdays it turned into a bloated client that works in Mac, Linux, and Windows, while still keeping the whole program in a single binary file that weighs only 876 kb, while competitors that use gui libraries weigh around 6 mb.

Do they create a separate native gui for each platform instead of using a multiplatform gui library? What's the best approach to achieve such a thing?

Thanks.

答:
From looking at screenshots it's fairly obvious that the Windows and OSX GUIs of μTorrent are not identical, so it's fairly unlikely that they used a multi-platform GUI library. μTorrent for Linux doesn't even have a conventional GUI, it offers a web-based interface, which would be programmed separately to a Windows GUI in any case.

That's the way to go: If you want to keep binary size down, you can't depend on libraries that aren't included in the operating system, because you'll have to bundle them.

Programming separate GUIs for separate platforms is, in my opinion, usually the correct approach: user interfaces on OSX and Windows follow significantly different paradigms, and if you port an app designed for Windows to OSX without changing the user interface, it will look quite alien to the user. Cross-platform GUI libraries can be very helpful tools, but they make it very easy to build software that looks out-of-place everywhere.