问:
Is switch-case over enumeration bad practice?
I have an enumeration with the commands Play, Stop and Pause for a media player. In two classes I do a switch-case over the received commands. The player runs in a different thread and I deliver the commands in a command queue to the thread.

If I generate class diagrams the enumeration has dependencies all over the place. Is there a nicer way to deal with the commands? If I would change/extend the enumeration, I would have to change several classes. (Its not super important to keep the player extensible, but I try to write nice software.)

答:
A "nicer" way is to have three methods, one per command.

There is no need to collapse all those commands into one method and to use a switch later. Since those commands do different things, they deserve their own methods in the interface.

Instead of:

```<code>public void ChangeState(PlayerState newState)
{
    switch (newState)
    {
        case PlayerState.Play:
            // Start playing.

        case PlayerState.Stop:
            // Stop playing.

        case PlayerState.Pause:
            // Pause or resume.
    }
}
</code>```

you would have:

```<code>public void Play()
{
    // Start playing.
}

public void Stop()
{
    // Stop playing.
}

public void Pause()
{
    // Pause or resume.
}
</code>```

Why?

Your current implementation using a switch will:

either do multiple things,

or will just serve to call Play, Stop and Pause methods.

In the first case, you break the rule which says that a method should do one and one only thing.

In the second case, KISS: don't write a method you really don't need and which doesn't bring anything useful to the API.

Body:
A "nicer" way is to have three methods, one per command.

There is no need to collapse all those commands into one method and to use a switch later. Since those commands do different things, they deserve their own methods in the interface.

Instead of:

public void ChangeState(PlayerState newState)
{
    switch (newState)
    {
        case PlayerState.Play:
            // Start playing.

        case PlayerState.Stop:
            // Stop playing.

        case PlayerState.Pause:
            // Pause or resume.
    }
}

you would have:

public void Play()
{
    // Start playing.
}

public void Stop()
{
    // Stop playing.
}

public void Pause()
{
    // Pause or resume.
}

Why?

Your current implementation using a switch will:

either do multiple things,

or will just serve to call Play, Stop and Pause methods.

In the first case, you break the rule which says that a method should do one and one only thing.

In the second case, KISS: don't write a method you really don't need and which doesn't bring anything useful to the API.


问:
If-Else V.S. Switch end of flow
I was wondering the if if-else statements, is like a switch statement that does have a break statement.

```<code>if( boolean_expression_1 )
  statement_1
else if( boolean_expression_2 )
  statement_2
else
  default_statement
</code>```

Is the same as:

```<code>switch( controlling_expression )
{
case: ( boolean_expression_1 )
{
     statement_1
     break;
}
case: ( boolean_expression_2 )
{
     statement_2
     break;
}
default:
{
     default_statement
}
</code>```

答:
The answer is no - the if-statement is not like a switch-statement without a break. Let us begin with this part of your question:

if boolean_expression_1 was true, would it check if boolean_expression_2 is true?

We can find the answer with this program. The trick is, that we call a method as our boolean_expression and use System.out.println() to see, if the method gets executed. This way we know if the expression was evaluated. Here is the program:

```<code>public class IfElseExample {

    private static boolean booleanExpression1() {
        System.out.println("Expression 1 is being evaluated.");
        return true;
    }

    private static boolean booleanExpression2() {
        System.out.println("Expression 2 is being evaluated.");
        return true;
    }

    public static void main(String[] args) {
        if (booleanExpression1())
            System.out.println("Statement 1 is executed");
        else if (booleanExpression2())
            System.out.println("Statement 2 is executed");
        else
            System.out.println("Default statement is executed");
    }

}
</code>```

You will see, that the second boolean expression is not evaluated. This behavior probably becomes more understandable if you put in some brackets (which is a good habit in most cases):

```<code>    if (booleanExpression1()) {
        System.out.println("Statement 1 is executed");
    } else {
        if (booleanExpression2()) {
            System.out.println("Statement 2 is executed");
        } else {
            System.out.println("Default statement is executed");
        }
    }
</code>```

This is the way, the compiler views your original if-chain. As you can see now, the second "if" is a single statement of its own and as such it is not on the same level as the first if-statement. If you chain more if-statements those get nested even deeper.

You also asked, why the switch-statement needs a break statement. This is because the switch-statement is not implemented internally with a chain of if-statement (neither is the if-statement based upon switch-statements). You might expect that

```<code>        switch(controllingExpression()) {
            case 42: System.out.println("A");
                        case 43: System.out.println("B");
            default : System.out.println("z");
        }
</code>```

gets translated by the compiler into something like:

```<code>if (controllingExpression() == 42) {
    System.out.println("A");
} else if (controllingExpression() == 43) {
    System.out.println("B");
} else {
    System.out.println("z");
}
</code>```

This is not the case. Instead it uses a hidden skip-statement:

```<code>int x = numberOfStatementsToSkipFor(controllingExpression());
skip x // hidden skip the next x statements byte code instruction
System.out.println("A");
System.out.println("B");
System.out.println("z");
</code>```

The method numberOfStatementsToSkipFor() returns 0 for 42, 1 for 43 and 2 for everything else. Now it becomes clear why this program might produce

```<code>A
B
z
</code>```

or

```<code>B
z
</code>```

or just

```<code>z
</code>```

but never

```<code>A
B
</code>```

without the 'z'. But clearly it would be nice if we could do this. And we can by using break which gets translated into another skip statement. So if you put break into all case-branches

```<code>switch(controllingExpression()) {
    case 42: {
        System.out.println("A");
        break;
    }
    case 43: {
        System.out.println("B");
        break;
    }
    default : System.out.println("z");
}
</code>```

the compiler will produce this:

```<code>int x = numberOfStatementsToSkip(controllingExpression());
skip x; // hidden skip the next x statements byte code instruction
System.out.println("A");
skip 3; //"B" + skip + "z"
System.out.println("B");
skip 1;
System.out.println("z");
</code>```

ContentLicense: CC BY-SA 3.0

Title: If-Else V.S. Switch end of flow

Body:
The answer is no - the if-statement is not like a switch-statement without a break. Let us begin with this part of your question:

if boolean_expression_1 was true, would it check if boolean_expression_2 is true?

We can find the answer with this program. The trick is, that we call a method as our boolean_expression and use System.out.println() to see, if the method gets executed. This way we know if the expression was evaluated. Here is the program:

public class IfElseExample {

    private static boolean booleanExpression1() {
        System.out.println("Expression 1 is being evaluated.");
        return true;
    }

    private static boolean booleanExpression2() {
        System.out.println("Expression 2 is being evaluated.");
        return true;
    }

    public static void main(String[] args) {
        if (booleanExpression1())
            System.out.println("Statement 1 is executed");
        else if (booleanExpression2())
            System.out.println("Statement 2 is executed");
        else
            System.out.println("Default statement is executed");
    }

}

You will see, that the second boolean expression is not evaluated. This behavior probably becomes more understandable if you put in some brackets (which is a good habit in most cases):

    if (booleanExpression1()) {
        System.out.println("Statement 1 is executed");
    } else {
        if (booleanExpression2()) {
            System.out.println("Statement 2 is executed");
        } else {
            System.out.println("Default statement is executed");
        }
    }

This is the way, the compiler views your original if-chain. As you can see now, the second "if" is a single statement of its own and as such it is not on the same level as the first if-statement. If you chain more if-statements those get nested even deeper.

You also asked, why the switch-statement needs a break statement. This is because the switch-statement is not implemented internally with a chain of if-statement (neither is the if-statement based upon switch-statements). You might expect that

        switch(controllingExpression()) {
            case 42: System.out.println("A");
                        case 43: System.out.println("B");
            default : System.out.println("z");
        }

gets translated by the compiler into something like:

if (controllingExpression() == 42) {
    System.out.println("A");
} else if (controllingExpression() == 43) {
    System.out.println("B");
} else {
    System.out.println("z");
}

This is not the case. Instead it uses a hidden skip-statement:

int x = numberOfStatementsToSkipFor(controllingExpression());
skip x // hidden skip the next x statements byte code instruction
System.out.println("A");
System.out.println("B");
System.out.println("z");

The method numberOfStatementsToSkipFor() returns 0 for 42, 1 for 43 and 2 for everything else. Now it becomes clear why this program might produce

A
B
z

or

B
z

or just

z

but never

A
B

without the 'z'. But clearly it would be nice if we could do this. And we can by using break which gets translated into another skip statement. So if you put break into all case-branches

switch(controllingExpression()) {
    case 42: {
        System.out.println("A");
        break;
    }
    case 43: {
        System.out.println("B");
        break;
    }
    default : System.out.println("z");
}

the compiler will produce this:

int x = numberOfStatementsToSkip(controllingExpression());
skip x; // hidden skip the next x statements byte code instruction
System.out.println("A");
skip 3; //"B" + skip + "z"
System.out.println("B");
skip 1;
System.out.println("z");


答:
What you seem to be doing is taking 3 separate inputs, merging them into a single variable, and passing that along to be processed.  Your processing code then does a switch / if statements on this variable.

As MainMa mentioned, the obvious and cleaner approach would be to simply have 3 methods, and have your interface call those.  If, for some reason, you wish to have a slightly more disconnected model (say, if you need to execute the command at a later stage then when it's triggered), the typical way is the Command Pattern where you effectively encapsulate a method call in an object (which can be serialised / stored / sent over the network / run multiple times, etc).  The advantage over your enum is that it caters for input parameters (e.g. if you have a volume control command).  That said, this is an unneccessary over-complication, and I'd stick to plain old methods.

Title: Is switch-case over enumeration bad practice?

Body:
I have an enumeration with the commands Play, Stop and Pause for a media player. In two classes I do a switch-case over the received commands. The player runs in a different thread and I deliver the commands in a command queue to the thread.

If I generate class diagrams the enumeration has dependencies all over the place. Is there a nicer way to deal with the commands? If I would change/extend the enumeration, I would have to change several classes. (Its not super important to keep the player extensible, but I try to write nice software.)


问:
Why do .Net books talk about stack vs heap memory allocation?
It seems like every .net book talks about value types vs reference types and makes it a point to (often incorrectly) state where each type is stored - the heap or the stack.  Usually it's in the first few chapters and presented as some all-important fact.  I think it's even covered on certification exams. Why does stack vs heap even matter to (beginner) .Net developers?  You allocate stuff and it just works, right?</p>

答:
I'm becoming convinced that the primary reason this bit of information is considered important is tradition.  In unmanaged environments, the disctinction between stack and heap is important and we have to manually allocate and delete the memory we use.  Now, garbage collection takes care of the management, so they ignore that bit.  I don't think the message has really gotten through that we don't have to care which type of memory is used either.

As Fede pointed out, Eric Lippert has some very interesting things to say about this: https://docs.microsoft.com/en-us/archive/blogs/ericlippert/the-truth-about-value-types.

In light of that information, you could adjust my first paragraph to basically read: "The reason people include this information and assume it is important is because of incorrect or incomplete information combined with needing this knowledge in the past."

For those who think it is still important for performance reasons:  What actions would you take to move something from the heap to the stack if you did measure things and find out that it mattered?  More likely, you'd find a completely different way of improving performance for the problem area.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Improving without mentor
Although I consider myself not much experienced, I keep landing in jobs as the leader somehow (in the current one I am tech director of the company, in a previous one I was the R&D head).

I understand why this happen (I have a certain specific set of skills, and I use some uncommon programming languages), my issue is: I cannot find a mentor...

I know there must be stuff to me learn, and I notice as I work over the years that I am slowly learning more and more, but I believe that there are some way to get better much faster than just coding...

So, how I improve when there are no other person in the company to teach me, or to me read their code? (or fix their code even...)

I think I am beyond books, but way below a "master" level, so I don't know where to learn more.

答:
my issue is: I cannot find a mentor... I think I am beyond books, but way below a "master" level, so I don't know where to learn more.

In what area? Do you want to improve your programming skills, your software engineering skills, your project management skills, something else? You didn't specify in your question.

You are not beyond books if you've learned to program / engineer software projects / manage a project on your own. You also are not beyond going back to school. Going back to school for an advanced degree, or at least taking some graduate level classes is one option you should not rule out. What area? That depends on what you want to improve, where you see your career. There's a lot to be said for getting an MBA, for example. People who are savvy in both a technical and business sense are worth a lot. A whole lot. A few of my former coworkers went for an MBA. I don't see them often because when they aren't working they're off to some tropical paradise. Or a safari. Or a weekend trip to the Alps. Or a summer ski trip to South America.

Another option is to join a technical society in a field where you have expertise but still want to improve. Yet another is to get your employer to send you to some boondoggle conference where you can learn and network.

Title: Improving without mentor


问:
How do tight timelines and scheduling pressure affect TCO and delivery time?
A friend's father, who is a software engineering manager, said, emphatically, "The number one cause of scheduling overruns is scheduling pressure."

Where does the research stand? Is a moderate amount of scheduling pressure invigorating, or is the manager I mentioned right or wrong, or is it a matter of "the more scheduling pressure you have, the longer the delivery time and the more TCO?" Is it one of those things where ideally software engineering would work without scheduling pressure but practically we have to work with constraints of real-world situations?

Any links to software engineering literature would be appreciated.

答:
Right to left scheduling.

Someone in management always thinks they are Steve Jobs with his famous reality distortion zone.  Until someone in product development educates them, non-technical managers may often have a view about scheduling that is as sophisticated as the early French film "Le voyage dans la lune" ("A Trip to the Moon") was for rocket science.

The problem has been around for a while.  Fred Brooks talks about gut-less estimation in Mythical Man-Month.  Barry Boehm talks about it in his proposals for a Theory-W approach to management.  More recently, Steve McConnell (author of Code Complete) brings the concept of principled negotiation issue into focus in "How to Defend an Unpopular Schedule".

Agile pushes the scope of projects to a place where it is highly visible.  The Agile Manifesto calls for "Customer collaboration over contract negotiation".  It also, I hope, empowers the people who are held accountable.  The planning game avoids non-technical stakeholders coercing developers to promises they made long ago that have been overrun by changes in requirements or new discoveries.

If your organization rejects agile, there are great methods related to calibration of estimates to rebaseline a schedule based on earned value.  I don't think earned value does a great job with some of the real problems with prediction, but it can help disspell delusions about the velocity of projects and the harping on the estimates we have as somehow being facts.

There is a saying that the sooner you start to code, the longer it takes.  Schedule pressure can have the effect of forcing methodology change.  Sometimes it is from waterfall to "code like hell".  This can have negative impact on quality, not to mention morale when workers can't do their best and their peers and future maintainers see them at their worst, not their best.  In an environment like this, some degree of the chaos can be controlled with source control, daily build and test (or continuous integration and unit test), code reviews, using an experienced and highly skilled team, resisting the temptation to add staff late in the project, and the old standby, overtime.

Other times the methodology change might be from waterfall to iterative incremental.  My experience has been that management was slow to embrace Agile.  But then after a while there was new management that was more supportive toward Agile.  Time boxing can be like budgeting - it can force us to think about the best use of a limited resource.  Scrum has two time boxes - one is daily for feedback between team members, the other is monthly for the sprint through the burn down list.

Creative Commons License - see http://en.wikipedia.org/wiki/File:Scrum_process.svg


问:
How to get multiple open-source projects to use a standard way of doing something
- Problem

In the last couple weeks, I've used 3 different "repository" tools (listed in alphabetical order):

gradle

ivy

maven

I'm calling them "repository" tools because I've also used sbt -- which fortunately uses ivy to manage it's cache or local repository.

Each of these tools will create it's own repository. The defaults are:

~/.m2/repository for maven

~/.gradle/cache

~/.ivy2/cache

Why can't they all use the same cache?

- Goal

I'd like to change the world so that all three build tools could use the same cache. I'm looking for advice about issues I'm likely to run into and smart ways to get around them.

By "use the same cache", I do not mean "retrieve from another build tool's cache".

I mean "retrieve from and store in another build tool's cache".

While I could go ahead and submit issues to the three projects, I know from experience (as a developer on an open source project), that if you want something done, you're best off getting it done yourself.

Also, it seems like I need to get all 3 communities on board to some degree.

- Question

What is the recommended approach for getting this kind of thing done? How do I approach the different communities? Do I work on patches for the 3 different projects, or would it be better off to create my own "interface" project that deals with these issues and have the 3 tools interface with that? Is this a standards question that I need to address on that front?

Lastly, if I'm missing something and this is possible (in an globally configurable fashion), then please let me know.

答:
I'd go for creating a separate project & interface and then provide patches for each tool.

Having a separate project makes it easier to centralize design decisions for the common format. Providing patches is necessary to show viability and iron out bugs in spec and implementation.

Additionaly, having your cache implementation separate allows even other projects to use the same cache.


问:
Is a coding standard even needed any more?
I know that it's been proven that a coding standard helps enormously.  However, there are many different tools and IDEs that will format to whatever standard the programmer prefers.  So long as the code's neat/commented (and not a spaghetti mess), I don't see the need for a coding standard.

Are there any arguments for the development of a coding standard (we don't have one, but I was looking into creating one)?

答:
Now that commercial aircraft are fly-by-wire you would hope the programs flying the plane based on the pilots input works. When the programmers write such code you hope they follow a strict set of rules to avoid commonly avoidable programming errors. One way to do this is with a coding standard.

See: Proposed Federal Aviation Administration C and C++ Coding Standards

Need I say more.

Note: I could not find the actual standard from the FAA online, but I have seen it.


答:
Coding standards could NOT be any more important!  I'm an avid CakePHP user and I like to review the changesets from version-to-version and the developers are not following standards there.

In fact, I was so upset by the differences in style that I had to write A Short Rant About Coding Conventions.  It costs a lot of time and money bringing new developers into an existing team already - just imagine bringing a new developer on with no standards...learning the code would be next too impossible.

Title: Is a coding standard even needed any more?

Body:
I know that it's been proven that a coding standard helps enormously.  However, there are many different tools and IDEs that will format to whatever standard the programmer prefers.  So long as the code's neat/commented (and not a spaghetti mess), I don't see the need for a coding standard.

Are there any arguments for the development of a coding standard (we don't have one, but I was looking into creating one)?


问:
Why are invariants important in Computer Science
I understand 'invariant' in its literal sense. I also recognize them when I type code. But I don't think I understand the importance of this term in the context of computer science.

Whenever I read conversations\white papers about language design from famous programmers\computer scientists, the term 'invariant' keeps popping up as a jargon; and that is the part I don't understand. What is so special about it?

答:
The notion of invariant is strongly linked with 'side effects'. I believe it was promoted by Bertrand Meyer's 'Design by Contract (DbC)' approach for software design.

DbC enriches Abstract Data Types (backbone of classes) with 3 important notions, preconditions, postconditions, invariants. It is easily explained when referring to procedures, so I'll try to explain in reference with it:

A precondition represents the condition input data for a procedure must respect in order to call that procedure. This precondition must be respected and enforced by the client of that particular procedure. The procedure designer might however defend from clients that do not respect the precondition by asserting that condition as first lines in the procedure. For example having a method double divide(double dividend, double divisor) a precondition might be divisor != 0.

A postcondition represents the a condition on the output data after the procedure returns; it is entirely the job of the procedure designer to respect this postcondition provided the precondition was respected; in a defense programming style before returning, the postcondition can be asserted.

An invariant can be regarded as a both a precondition and a postcondition, but with different understanding for precondition and postcondition from above concepts. An invariant basically says that the if the input has a particular condition met before the procedure was called, then that particular condition is valid after the procedure is called. For example a valid invariant for a procedure boolean search(int term, int array[]) might say that the state of array before the call is the same as it is after the call.

Enforcing invariants on procedures (and not only procedures) is a great thing since it reduces side effects; this is useful since side effects are a great evil in programming. A particular procedure might change the state of the input arguments, or change the state of some global variables, or depend on some global variables; this might lead to nasty situations where two identical calls on the same procedure (with the same input) might yield different outputs. This leads to knowing the history of the calls and is very hard to debug especially in a multithreading context.


答:
An invariant is a logical property that is preserved by some operation(s).

You need invariants to reason about loops. Since you don't know beforehand how many iterations there will be (or you wouldn't need a loop), each iteration must preserve the invariant, so that at the end you can prove some useful property about the loop.

You need invariants to reason about properties of encapsulated data.  Often the various data inside a module or object need to satisfy certain properties for correct operation (for example, a list representing a set must always be sorted).  You want that each function or method operating on the data preserves these properties, so they are invariants, too.

Title: Why are invariants important in Computer Science

Body:
I understand 'invariant' in its literal sense. I also recognize them when I type code. But I don't think I understand the importance of this term in the context of computer science.

Whenever I read conversations\white papers about language design from famous programmers\computer scientists, the term 'invariant' keeps popping up as a jargon; and that is the part I don't understand. What is so special about it?


答:
An algorithm is a repeatable process.  If it is repeatable, it has to have attributes that do not change with repetition.  These are your invariants.  The invariants are combined with and/or operate on the (potentially) varying data that will be fed into your algorithm.

Thus the whole point of programming is to identify what does not vary--that is essentially your program.

In object-oriented program, there is a notion that each object should do a single thing well.  This essentially means that (for class-based OOP) a class defines the invariants for a single algorithm, along with place-holders (variables) for any variant data that its objects might need. Ideally in OO, you would isolate what varies as much as possible, so that each object is mostly invariant.


答:
I think that a certain amount of pressure in a project is OK because it helps to maintain focus.

However, if the pressure is not realistic, or if the communication between management and technical people does not work properly, yes, there is a the risk that scheduling pressure results in bad quality and / or late delivery.

An experienced developer will know that he / she is not expected to produce the perfect solution but rather a solution that is good enough. So the estimate given by such a developer will already reflect their understanding of what is good enough for a particular project.

There many factors that influence the definition of good enough.

For example, how many months does the project last? If the project lasts one year, you can write a prototype of that particularly difficult module rather quickly at the beginning of the project and then you have several months to test and debug it as a side activity to the development of other, more routine modules. (You can let that module ripe over several months until it is good enough so you do not need to try and get it right from the very beginning.)
I find this strategy very effective but you need a manager that trusts you and will let you keep a project open for months. Another (distrustful) manager might push you to finish that module as soon as possible (no matter if you'll have to fix it later and if this approach will eventually cost much more time in total).

Another example: the project is for a product that will have only one release. Then you can try to get it done quickly and rely on extensive tests to ensure that the product works as expected (quick and dirty is good enough). On the other hand, if the product is going to have two or three releases, better spend some time on designing it, to avoid extensive rewriting of the code for later releases. (In this case, quick and dirty is not good enough because the total development time over the three releases is bigger.)

Bottom line, I think that bad communication between management and technical people and a lack of a common understanding of what is good enough for the project at hand can lead to excessive scheduling pressure, resulting in bad quality / late delivery.

There is never enough time to do it properly the first time, but there is always enough time to fix it later.

Title: How do tight timelines and scheduling pressure affect TCO and delivery time?

Body:
A friend's father, who is a software engineering manager, said, emphatically, "The number one cause of scheduling overruns is scheduling pressure."

Where does the research stand? Is a moderate amount of scheduling pressure invigorating, or is the manager I mentioned right or wrong, or is it a matter of "the more scheduling pressure you have, the longer the delivery time and the more TCO?" Is it one of those things where ideally software engineering would work without scheduling pressure but practically we have to work with constraints of real-world situations?

Any links to software engineering literature would be appreciated.


问:
I need a decent alternative to c++
I've learned php and c++, i will list the things i liked and didn't liked on each of them, how i decided to learn them in the first place and why i feel the need to learn a decent alternative to c++, i'm not a professional programmer and only do projects for myself.

PHP - Decided to learn because i wanted to build a dynamic website, that i did and turned out very good, i even coded a 'not so basic' search engine for it that would display the results 'google style' and really fast, pretty cool stuff.

PROS - Pretty consistent syntax for all stuff (minor caveats), great functionality, a joy for me to code in it (it seems to 'know' what i want it to do and just does it)

CONS - Painfully slow for number crunching (which takes me to c++ that i only learned because i wanted to do some number crunching and it had to be screaming fast)

C++ - Learned because number crunching was so slow in php and manipulating large amounts of data was very difficult, i thought, it's popular programming language and all, and tests show that it's fast, the basic stuff resemble php so it shouldn't be hard to pick up

PROS - It can be used to virtually anything, very very fast

CONS - Although fun to code at the start, if i need to do something out of the ordinary, memory allocation routines, pointer stuff, stack sizes etc... will get me tired really quick, syntax is a bit inconsistent some times (more caveats)

I guess that from what i wrote you guys will understand what i'm looking for, there are thousands of languages out there, it's likely that one of them will suit my needs, i've been seeing stuff today and a friend of mine that is a professional programmer tried OCaml and Fortran and said that both are fast for numerical stuff, i've been inclined to test Fortran, but i need some more input because i want to have some other good 'candidates' to choose from, for example the python syntax seemed great to me, but then i found out from some tests that it was a lot slower than c++ and i simply don't want to twiddle my thumbs all day.

答:
If PHP is too slow for you, you can always write the performance sensitive parts in C++ and then call those C++ functions from PHP (see this stackoverflow question).

For relatively fast servers, Java and C# are also good options. They may not always be as fast as C++, but for most purposes they are "fast enough".

For some workloads, you may also hear that node.js is the fastest, but not in your case. Node.js specializes in I/O-bound operations, and you seem to be stuck in CPU-bound operations, so node.js would be "pretty fast, but not mind-blowingly so".

For C++, there are a number of things you could do to improve the situation. I suspect you might be doing something wrong if stack sizes are such a huge problem for you.

Pointers might be easier to handle if you try smart pointers.

Avoid manually allocating stuff if you can. If you want to allocate memory for a bunch of stuff, just use a vector and let C++'s STL do the complex stuff for you.

Finally, you might try a PHP compiler to accelerate PHP without needing to switch languages. See Phalanger, phc and HipHop.

Try many different technologies and see what works for you.

If performance is really a major issue, and your calculations can be split into many smaller independent steps, then languages like OpenCL might help.

Title: I need a decent alternative to c++


答:
Sounds like PHP was too high of a level for you and C++ was too low. I'm a C++ programmer myself and I do agree that sometimes signal-to-noise ratio, especially for a new person, can be quite low. It still has its place in many areas, but I would not use it for general programming.

The languages I would recommend would be C#, Python or Java.  Of those Java is at the end of the list because it seems like it's no longer the hot item in the industry and if you are going to learn something, might as well pick up a skill other people are looking for.

Both C# and Java are similar to syntax of C++, but they are less flexible which is a good and a bad thing. For you, its mostly a good thing since the flexibility is what introduces complexity.  Both languages will not allow you to pave over memory and will worry about allocations for you so you can focus on the actual logic.

Python is quite different and I'm not entirely sure how it compares in speed since I believe it is still interpreted whereas C# just-in-time compiles to machine code. But it is still a fun language.

Title: I need a decent alternative to c++

Body:
I've learned php and c++, i will list the things i liked and didn't liked on each of them, how i decided to learn them in the first place and why i feel the need to learn a decent alternative to c++, i'm not a professional programmer and only do projects for myself.

PHP - Decided to learn because i wanted to build a dynamic website, that i did and turned out very good, i even coded a 'not so basic' search engine for it that would display the results 'google style' and really fast, pretty cool stuff.

PROS - Pretty consistent syntax for all stuff (minor caveats), great functionality, a joy for me to code in it (it seems to 'know' what i want it to do and just does it)

CONS - Painfully slow for number crunching (which takes me to c++ that i only learned because i wanted to do some number crunching and it had to be screaming fast)

C++ - Learned because number crunching was so slow in php and manipulating large amounts of data was very difficult, i thought, it's popular programming language and all, and tests show that it's fast, the basic stuff resemble php so it shouldn't be hard to pick up

PROS - It can be used to virtually anything, very very fast

CONS - Although fun to code at the start, if i need to do something out of the ordinary, memory allocation routines, pointer stuff, stack sizes etc... will get me tired really quick, syntax is a bit inconsistent some times (more caveats)

I guess that from what i wrote you guys will understand what i'm looking for, there are thousands of languages out there, it's likely that one of them will suit my needs, i've been seeing stuff today and a friend of mine that is a professional programmer tried OCaml and Fortran and said that both are fast for numerical stuff, i've been inclined to test Fortran, but i need some more input because i want to have some other good 'candidates' to choose from, for example the python syntax seemed great to me, but then i found out from some tests that it was a lot slower than c++ and i simply don't want to twiddle my thumbs all day.


答:
For me its a matter of discipline and being disciplined always helps, its a reflection of the quality of the work you produce.

Having said that, I would make the coding standard keeping in view the IDE and/or tools in use. Further, the IDE should be configured identically (e.g. each developer's IDE should either be using all tabs or all white-spaces for indentation and everyone's IDE should have the same tab length) for each developer so everyone can follow the standard easily...

Also, check-in scripts could be developed and used which may help in adhering to the coding standards to certain extent, e.g. they can fix the indentation before actually committing the checked in file into the version control system.


问:
Review before or after code commit, which is better?
Traditionally we performed code review before commit, I had an argument with my colleague today, who preferred code review after commit.

First, here's some background,

We have some experienced developers and we also have new hires with almost zero programming experience.

We'd like to perform fast and short iterations to release our product.

All team members are located at the same site.

The advantages of code review before commit I've learned:

Mentor new hires

Try to prevent errors, failures, bad designs early in the development cycle

Learn from others

Knowledge backup if someone quits

But I've also had some bad experiences:

Low efficiency, some changes may be reviewed over days

Hard to balance speed and quality, especially for newbies

One team member felt distrust

As to post-commit review, I know little about this, but the thing I'm most worried about is the risk of losing control due to lack of review.
Any opinions?

UPDATE:

We're using Perforce for VCS

We code and commit in the same branches (trunk or bug fixing branches)

To improve efficiency, we've tried to split code into small changes. We've also tried some live dialog review, but not everyone followed the rule. This is another problem though.

答:
Both. (Kind of.)

You should be reviewing your own code summarily before committing it. In Git, I think the staging area is great. After I've staged my changes, I run git diff --cached to see everything that is staged. I use this as an opportunity to make sure I'm not checking in any files that don't belong (build artifacts, logs, etc.) and making sure that I don't have any debug code in there or any important code commented out. (If I'm doing something that I know I don't want to check in, I usually leave a comment in all caps so that I'll recognize it during staging.)

Having said that, your peer code review should be generally be conducted after you commit, assuming that you are working on a topic branch. This is the easiest way to make sure that everybody else is reviewing the correct thing, and if there are major problems, then it's no big deal to fix them on your branch or delete them and start over. If you conduct code reviews asynchronously (i.e. using Google Code or Atlassian Crucible), then you can easily switch branches and work on something else without have to separately keep track of all your different patches/diffs that are currently under review for a few days.

If you're not working on a topic branch, you should. It reduces stress and hassle and makes release planning much less stressful and complicated.

Edit: I should also add that you should be doing code review after testing, which is another argument in favor of committing code first. You don't want your test group fiddling around with dozens of patches/diffs from all the programmers, then filing bugs just because they applied the wrong patch at the wrong place.


答: 100% paired programming (no matter how senior you think you are) with lots of small commits and a CI system that builds on EVERY commit (with automated testing including units, integration and functional wherever possible).  Post-commit reviews for large or risky changes.   If you must have some kind of gated/pre-commit review, Gerrit works.</p>

Title: Review before or after code commit, which is better?

Body:
Traditionally we performed code review before commit, I had an argument with my colleague today, who preferred code review after commit.

First, here's some background,

We have some experienced developers and we also have new hires with almost zero programming experience.

We'd like to perform fast and short iterations to release our product.

All team members are located at the same site.

The advantages of code review before commit I've learned:

Mentor new hires

Try to prevent errors, failures, bad designs early in the development cycle

Learn from others

Knowledge backup if someone quits

But I've also had some bad experiences:

Low efficiency, some changes may be reviewed over days

Hard to balance speed and quality, especially for newbies

One team member felt distrust

As to post-commit review, I know little about this, but the thing I'm most worried about is the risk of losing control due to lack of review.
Any opinions?

UPDATE:

We're using Perforce for VCS

We code and commit in the same branches (trunk or bug fixing branches)

To improve efficiency, we've tried to split code into small changes. We've also tried some live dialog review, but not everyone followed the rule. This is another problem though.


问:
What is the advantage of assigning a function to a var?
Given this Javascript example I found

```<code>var sum = function() {
  var i, sum = 0;
  for(i = 0; i < arguments.length; i += 1) {
    sum += arguments[i];
  }
  return sum;
};
</code>```

What advantage is there in assigning a function to a var?

答:
The short answer I believe is simply that you are creating an anonymous function assigned to a variable, as opposed to creating a named function with...

```<code>    function sum() {}
</code>```

A good way to check the differences is to call .ToString() on them and see the difference or you could do console.log(sum.name).  One will give an actual name and the other nothing, namely the anonymous function (the one assigned to the var).  There are specifics too, like the var sum = function(){} gets defined at run time and the function sum(){} gets defined at parse time.

Body:
The short answer I believe is simply that you are creating an anonymous function assigned to a variable, as opposed to creating a named function with...

    function sum() {}

A good way to check the differences is to call .ToString() on them and see the difference or you could do console.log(sum.name).  One will give an actual name and the other nothing, namely the anonymous function (the one assigned to the var).  There are specifics too, like the var sum = function(){} gets defined at run time and the function sum(){} gets defined at parse time.


问:
What is the best way to diagrammatically represent a system threading architecture?
I am yet to find the perfect way to diagrammatically represent the overall threading architecture for a system (using UML or otherwise).

I am after a diagramming technique that would show all the threads in a given system and how they interact with each other. There are a few similar questions - Drawing Thread Interaction, UML Diagrams of Multithreaded Applications and Intuitive UML Approach to Depict Threads but they don't fully answer my question.

What are some of the techniques that you've found useful to depict the overall threading architecture for a system?

答:
What are some of the techniques that you've found useful to depict the overall threading architecture for a system?

By not treating it special. Elements in the architecture send messages to one another; if that's across a thread boundary (or even a system boundary) doesn't really matter from an architectural perspective.

As far as implementation goes, it doesn't matter. Implementation is done at the module level. Black Box A presents some interface and consumes some other Black Box. Make a note that the interface it consumes or provides is required to be (non)blocking and/or threadsafe and be on your way.

Otherwise, consider it a design smell if those threading details are leaking through your abstractions.


问:
Proper Use Of HTML Data Attributes
I'm writing several JavaScript plugins that are run automatically when the proper HTML markup is detected on the page. For example, when a tabs class is detected, the tabs plugin is loaded dynamically and it automatically applies the tab functionality. Any customization options for the JavaScript plugin are set via HTML5 data attributes, very similar to what Twitter's Bootstrap Framework does.

The appeal to the above system is that, once you have it working, you don't have worry about manually instantiating plugins, you just write your HTML markup. This is especially nice if people who don't know JavaScript well (or at all) want to make use of your plugins, which is one of my goals.

This setup has been working very well, but for some plugins, I'm finding that I need a more robust set of options. My choices seem to be having an element with many data-attributes or allowing for a single data-options attribute with a JSON options object as a value. Having a lot of attributes seems clunky and repetitive, but going the JSON route makes it slightly more complicated for novices and I'd like to avoid full-blown JavaScript in the attributes if I can. I'm not entirely sure which way is best.

Is there a third option that I'm not considering?

Are there any recommended best practices for this particular use case?

答:
I've been working with a similar pattern over the past several months.  My personal opinion is that it is ok to mix these two conventions depending on the needs of the plugin.  If you have a small number (i.e. < 5) of well defined parameters or if you want to select elements based on a particular attribute then data attributes for each parameter is ok.  If you have a large number of parameters, or if the parameters are highly dynamic (i.e. request parameters to an ajax call) then json within a data attribute may be more beneficial.

In any case, IMO it is very important to clearly document what the parameters are and how they should be used.

Title: Proper Use Of HTML Data Attributes


答:
Its mostly a matter of style, since the only situations where the difference shows up (calling some of the functions before ending all declarations; using the toString method) are kind of corner cases, in my oppinion.

One of the arguments I have heard supporting this var = style is that it is consistent with how you declare normal variables. This limits the number of language features you use and makes it simpler to indroduce your program to someone new to Javascript.

Title: What is the advantage of assigning a function to a var?

Body:
Given this Javascript example I found

```<code>var sum = function() {
  var i, sum = 0;
  for(i = 0; i < arguments.length; i += 1) {
    sum += arguments[i];
  }
  return sum;
};
</code>```

What advantage is there in assigning a function to a var?


答:
One advantage is that you can't use a function declaration in a block. They can only be at the top level of a file or directly within another function.

```<code>if (true) {
  function foo() {}
}
try {
  function foo(){}
}
switch (true) {
  default:
    function foo(){}
}
</code>```

These are all unspecified by the standard and browsers do different things, see https://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements. So if you have to use the other style sometimes, for consistency you might want to do so always

Also, I'm not sure of this one but if I remember correctly some old minifiers weren't smart enough to to handle function declarations and don't rename them.

Body:
One advantage is that you can't use a function declaration in a block. They can only be at the top level of a file or directly within another function.

if (true) {
  function foo() {}
}
try {
  function foo(){}
}
switch (true) {
  default:
    function foo(){}
}

These are all unspecified by the standard and browsers do different things, see https://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements. So if you have to use the other style sometimes, for consistency you might want to do so always

Also, I'm not sure of this one but if I remember correctly some old minifiers weren't smart enough to to handle function declarations and don't rename them.


问:
Pointers in C vs No pointers in PHP
Both languages have the same syntax.

Why does C have the weird * character that denotes pointers (which is some kind of memory address of the variable contents?), when PHP doesn't have it and you can do pretty much the same things in PHP that you can do in C, without pointers? I guess the PHP compiler handles this internally, why doesn't C do the same?

Doesn't this add unneeded complexity in C? For example I don't understand them :)

答:
Yes to all of the above. But there are other things to consider.

```<code>(type *T) list ~ (type T) list[]  // pointer can be used as an alias for an array
</code>```

The only difference is that an array is a constant pointer, meaning it cannot be reassigned to point to something else. And,

```<code>*(list + n) = list[n].
</code>```

To sort a list, especially a multidimensional one, it is more efficient to just move the pointers around. There is no need to copy and drag data around.

What (* = deference) means depends on context. Pointers are always declared using it,
e.g. char *p, int *n, struct record *rec.

In a statement (*) returns the value pointed to.
Thus.

```<code>char ch = *p;   // ch = value p is currently pointing at.
</code>```

In C++ you can use pointers to get base class data or methods from a derived class, provided that the classes are properly defined.

Certainly, the understanding of pointers takes time, but necessity often facilitates
imaginative uses.

Contrast this with PHP which is an primarily designed to be a back end
language. Although it can be sophisticated in implementation, it was not designed for
robust computing.

Title: Pointers in C vs No pointers in PHP

Body:
Yes to all of the above. But there are other things to consider.

(type *T) list ~ (type T) list[]  // pointer can be used as an alias for an array

The only difference is that an array is a constant pointer, meaning it cannot be reassigned to point to something else. And,

*(list + n) = list[n].

To sort a list, especially a multidimensional one, it is more efficient to just move the pointers around. There is no need to copy and drag data around.

What (* = deference) means depends on context. Pointers are always declared using it,
e.g. char *p, int *n, struct record *rec.

In a statement (*) returns the value pointed to.
Thus.

char ch = *p;   // ch = value p is currently pointing at.

In C++ you can use pointers to get base class data or methods from a derived class, provided that the classes are properly defined.

Certainly, the understanding of pointers takes time, but necessity often facilitates
imaginative uses.

Contrast this with PHP which is an primarily designed to be a back end
language. Although it can be sophisticated in implementation, it was not designed for
robust computing.


答:
I'm not a Javascript expert, so take this with a grain of salt. I think in some cases people might do it for style and same thing could be achieved by simply writing "function sum() {...}"

However, assigning a function to a variable is a very powerful technique in functional programming. If you are familiar with OOP, it is somewhat similar to polymorphism. Think of the classic example of Animal base class and Cat/Dog deriving classes. You can write code that works with Animal but when it calls a function, that function could do different work depending on the type of an instance.

In functional programming, you could have an algorithm which works with "a function" but if you are using a variable to call that function, you have the flexibility of assigning a different function at runtime.

For example, let's say you write an algorithm to present 10,000 data points in a window which is only 500 pixels across.  Each pixel will then represent 20 data points and in order to present them you need to aggregate those 20 data points into a single value.

So let's say you define an algorithm to present the 10,000 points and this algorithm uses a function variable called aggregate like so:

```<code>...
displayValue = aggregate( numbersInOnePixel );
...
</code>```

Now at runtime your user can select how the data is to be aggregated. Your actual function variable can be any one of the following:

```<code>aggregate = function sum() {...}
aggregate = function min() {...}
aggregate = function max() {...}
aggregate = function average() {...}
</code>```

Body:
I'm not a Javascript expert, so take this with a grain of salt. I think in some cases people might do it for style and same thing could be achieved by simply writing "function sum() {...}"

However, assigning a function to a variable is a very powerful technique in functional programming. If you are familiar with OOP, it is somewhat similar to polymorphism. Think of the classic example of Animal base class and Cat/Dog deriving classes. You can write code that works with Animal but when it calls a function, that function could do different work depending on the type of an instance.

In functional programming, you could have an algorithm which works with "a function" but if you are using a variable to call that function, you have the flexibility of assigning a different function at runtime.

For example, let's say you write an algorithm to present 10,000 data points in a window which is only 500 pixels across.  Each pixel will then represent 20 data points and in order to present them you need to aggregate those 20 data points into a single value.

So let's say you define an algorithm to present the 10,000 points and this algorithm uses a function variable called aggregate like so:

...
displayValue = aggregate( numbersInOnePixel );
...

Now at runtime your user can select how the data is to be aggregated. Your actual function variable can be any one of the following:

aggregate = function sum() {...}
aggregate = function min() {...}
aggregate = function max() {...}
aggregate = function average() {...}


问:
Compiler design in Lisp
With some googling, I could easily find some documents in compiler design in C, Java, and C# and even in Haskell, but not in Lisp except implementing Scheme/Lisp in Lisp.

Is Lisp not so popular in implementing other (not functional) programming languages?
Do you know of some good documentation about implementing a compiler in LISP?

答:
Lisp programmers use the language to solve tasks other than writing a Lisp compiler in itself.

Most Common Lisp implementations (I cannot think of an exception at the moment) are compiled, and their compilers are written in Lisp. The code is there, just maybe not the papers and tutorials.

OwnerDisplayName: prosseek

Title: Compiler design in Lisp


问:
Why is iOS "jailbreaking" CPU specific?
Recently, iOS 6 was "jailbroken" but only on the Apple A4 CPU.

Why is the "jailbreaking" process specific to a CPU?

From Wikipedia:

... "iOS jailbreaking is the process of removing the limitations imposed by
  Apple on devices running the iOS operating system through the use of
  hardware/software exploits – such devices include the iPhone, iPod
  touch, iPad, and second generation Apple TV. Jailbreaking allows iOS
  users to gain root access to the operating system""" ...

答:
Odds are that the older A4 chips have an instruction which may or may not be undocumented that allows for an exploit that enables a rooting to be performed. It is possible that that exploit became known during the design process for the next generation of ARM chips for Apple devices and was either removed or otherwise disabled.

Also the longer a given device has been on the public market, the more time that the various cracking groups have had to take a look at and dissect the hardware for that device. Once you map the circuitry for a chip fully, understanding what it does is substantially easier. This process can take a long time in many cases given the size (smallness) and complexity (staggering) of modern integrated circuits.

Much of the analysis involved (and the design of the devices) are machine driven at this point to deal with the complexities inherent. Thus a new chip may have a totally different architecture requiring an entirely different approach to rooting or otherwise exploiting it.

Title: Why is iOS "jailbreaking" CPU specific?


答:
From what i know the importance of invariant comes from the fact that it is the building block for proving that an algorithm does compute a certain function.
For example you have developed a new sorting algorithm but how can you be so sure that it really sorts with every input or with every correct output. The next step is to construct invariants that correspond to do flow of the algorithm and prove that it sorts using the invariants.  </p>


问:
Torvalds' quote about good programmer
Accidentally I've stumbled upon the following quote by Linus Torvalds:

"Bad programmers worry about the code. Good programmers worry about
  data structures and their relationships."

I've thought about it for the last few days and I'm still confused (which is probably not a good sign), hence I wanted to discuss the following:

What interpretation of this possible/makes sense?

What can be applied/learned from it?

答: Can't agree more with Linus. Focusing on the data helps greatly distill a simple and flexible solution to a given problem. Git itself is a proving example -- giving so many features supported in the years of development, the core data structure largely remain unchanged. That's magic!  --2c</p>

Title: Torvalds' quote about good programmer


问:
Do other developers feel that as they get better, it becomes harder to get jobs?
When I was starting out, it seemed I had a much better time getting interviews and passing them. But now that I'm more experienced, I'm finding that its harder and harder to find a job. Do other developers out there feel the same way?

I'll give you an example. I did an interview last Wednesday. It was a small start-up with only one other engineer and the CEO. They flew me in from Ohio (they are SF based). When I got there, they had me write them a link shortener, which took me about 10 minutes to write. I was supposed to be there all day working on this. When I finished it early, the interviewer seemed kind of shocked. After that, we were talking, and I asked him what they use to store data. He told me Mongo. I ask why he decided to use mongo. He then stammered and mumbled his answer, which basically boiled down to "We're using it because Mongo is a the trendy database technology and we don't want to be left out", which I've found is pretty much most common reason people use NoSQL these days. The interviewer quickly ended the interview and pretty much shoved me out the door. I was supposed to have lunch with the CEO, but I he kicked me out before I had a chance. The intervier wasn't mean or rude, (and neither was I).

After I got back to Ohio, I got an email from them saying "I wasn't a fit". This sot of thing happens to me all the time. I'm starting to think "not a fit" can sometimes mean "are too high of a skill level that we are". Is this all in my head, or do other experienced developers notice the same thing happening? Back when I used to struggle with coding problems, I would work with the interviewer and it would be a positive thing and I'd get hired. But now I usually blow through the coding part, and the interviewer being left speechless is working against me. Should I feign struggling with coding problems?

答:
It's understandable that some companies won't want to hire someone that far exceed their skill level. You're going to show them up, they'll feel inadequate, they don't have the opportunity to groom you to work according to their model, and you'll probably get bored and move on.

I'm been to interviews like that but they are normally excited about me and I'm the one who bails out. But at the end of the day it's the same thing - you don't want to work somewhere where you won't fit in.

You should apply for some more exclusive roles.


问:
Single statement if block - braces or no?
Which is better/more generally accepted?

This:

```<code>if(condition)
{
  statement;
}
</code>```

Or:

```<code>if(condition)
  statement;
</code>```

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without.  The second one, however, is still syntactically correct and definitely more compact.  I'm curious to see which is more generally preferred by others though.

答:
I use the two-line version without braces (the 2nd form), but not to save space.

I use that form because I find it more readable, more visually appealing, and easier to type.  I only use that form if those conditions are met; i.e. the if condition has to fit nicely on a single line, and the corresponding statement has to fit nicely on the following line.  If that is not the case, then I will use braces to improve readability.

If I use this form, I make sure that there is an empty line (or a line containing only a brace) before and after the if statement (or above the comment, if present).  While this is not a rule that I consciously follow, I notice it now after reading this question.

Conserving screen space is not a priority for me.  If I needed more space I would use a larger monitor.  My screen is already large enough for me to read anything that I might need to focus my attention on.  It's unlikely that I would need to focus on so many lines of code at one time that they take up my entire screen.  If there is so much nesting going on with a chunk of code that I can't understand it without viewing more of it at one time, then I would have to consider whether the logic could be better represented by refactoring.

Below are some examples that demonstrate how I use this form of the if statement.

```<code>    string GuardConditions(Plan planForWorldDomination)
    {
        if (planForWorldDomination == null)
            throw new ArgumentNullException("planForWorldDomination");

        if (!planForWorldDomination.IsComplete())
            return "Doh!";

        planForWorldDomination.Execute();
    }

    void ProcessingLogic()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
        OneBlankLineAbove();

        // optional comment on the line above an if statement
        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
    }

    void Assignment(string drive)
    {
        OneBlankLineAbove();

        string prompt;
        if (simpleCondition)
            prompt = "simple assignment";
        else
            prompt = null;

        OneBlankLineBelow();
    }

    string Return()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            return "simple return";
        else
            return null;

        OneBlankLineBelow();
    }
</code>```

Body:
I use the two-line version without braces (the 2nd form), but not to save space.

I use that form because I find it more readable, more visually appealing, and easier to type.  I only use that form if those conditions are met; i.e. the if condition has to fit nicely on a single line, and the corresponding statement has to fit nicely on the following line.  If that is not the case, then I will use braces to improve readability.

If I use this form, I make sure that there is an empty line (or a line containing only a brace) before and after the if statement (or above the comment, if present).  While this is not a rule that I consciously follow, I notice it now after reading this question.

Conserving screen space is not a priority for me.  If I needed more space I would use a larger monitor.  My screen is already large enough for me to read anything that I might need to focus my attention on.  It's unlikely that I would need to focus on so many lines of code at one time that they take up my entire screen.  If there is so much nesting going on with a chunk of code that I can't understand it without viewing more of it at one time, then I would have to consider whether the logic could be better represented by refactoring.

Below are some examples that demonstrate how I use this form of the if statement.

    string GuardConditions(Plan planForWorldDomination)
    {
        if (planForWorldDomination == null)
            throw new ArgumentNullException("planForWorldDomination");

        if (!planForWorldDomination.IsComplete())
            return "Doh!";

        planForWorldDomination.Execute();
    }

    void ProcessingLogic()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
        OneBlankLineAbove();

        // optional comment on the line above an if statement
        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
    }

    void Assignment(string drive)
    {
        OneBlankLineAbove();

        string prompt;
        if (simpleCondition)
            prompt = "simple assignment";
        else
            prompt = null;

        OneBlankLineBelow();
    }

    string Return()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            return "simple return";
        else
            return null;

        OneBlankLineBelow();
    }


问:
Cross-platform desktop programming: C++ vs. Python
Alright, to start off, I have experience as an amateur Obj-C/Cocoa and Ruby w/Rails programmer. These are great, but they aren't really helpful for writing cross-platform applications (hopefully GNUStep will one day be complete enough for the first to be multi platform, but that day is not today).

C++, from what I can gather, is extremely powerful but also a huge, ugly behemoth that can take half a decade or more to master. I've also read that you can very easily not only shoot yourself in the foot, but blow your entire leg off with it since memory management is all manual. Obviously, this is all quite intimidating. Is it correct?

Python seems to provide most of the power of C++ and is much easier to pick up at the cost of speed. How big is this sacrifice? Is it meaningful or can it be ignored?

Which will have me writing fast, stable, highly reliable applications in a reasonable amount of time?

Also, is it better to use Qt for your UI or instead maintain separate, native front ends for each platform?

EDIT: For extra clarity, there are two types applications I want to write: one is an extremely friendly and convenient database frontend and the other, which no doubt will come much later on, is a 3D world editor.

答:
C/C++ is fast. The reality is, most apps wont need that performance with the state of the current hardwares. The usual way is to develop the application in a high level language, like python, than optimize when needed with lower level languages, like C/C++.

Python will give you a big productivity boost, it's easy to learn and reasonably fast. There is Cython, which you can use to write C extensions to use in your python app with python-like syntax to speed up bottlenecks.

For standart GUI apps, python can give you enough performance. And python has something very cool called Kivy, a GUI framework that runs on Mac, Windows, Linux, Android and iOS, and supports multi touch. The bonus part is, the performance critical parts are optimized with C, using Cython.


问:
bug: deviation from requirements vs deviation from expectations
I am not clear on this one. No matter the terminology, in the end the software fault/bug causes (according to a lot of sources):

Deviation from requirements

   Devation from expectations

But if the expectations are not in requirements, then stakeholder could see a bug everywhere as he expected it to be like this or that..So how can I really know? I did read that specification can miss things and then of course its expected but not specified (by mistake).

答: Generally, a deviation from expectations would only be considered a bug if the expectations were obvious and reasonable. For example, if the application is for scheduling medical appointments, clearly taking 10 minutes to pull up an appointment would be unreasonable. But if the requirements didn't specify a time frame, it wouldn't be a deviation from requirements.</p>


答:
But if the expectations are not in requirements, then stakeholder could see a bug everywhere as he expected it to be like this or that..So how can I really know?

You know what is in the requirements by reading the requirements.  (There may also be unstated requirements; i.e. things that were so obvious that nobody bothered to write them down.  But these can be problematic: see below.)

You know what the user's expectations were / are by asking the user.

Whether an unmet user expectation is a "bug" is really a matter for discussion between the stake holders.

Unfortunately, a lot of less than scrupulous software suppliers / contractors will play hard-ball over reasonable user expectations that are not written requirements.  But the flip-side is that some less than scrupulous customers are prepared to play cost / blame shifting games by pretending that expectations are unstated requirements.

Title: bug: deviation from requirements vs deviation from expectations

Body:
I am not clear on this one. No matter the terminology, in the end the software fault/bug causes (according to a lot of sources):

Deviation from requirements

   Devation from expectations

But if the expectations are not in requirements, then stakeholder could see a bug everywhere as he expected it to be like this or that..So how can I really know? I did read that specification can miss things and then of course its expected but not specified (by mistake).


答:
I would go with Python, as it gives you big productivity boost. You can still write portions of your app that need speed in C++, there is a Cython project that allows to use C++ libraries directly in Python. If you're concerned about security of your sources, Cython can also help with that, you can use it to compile your normal python code to C++ code.

I would recommend to embed Chrome engine and use technologies like: HTML5 + CSS3 + Javascript + JQuery + Canvas for the UI.

There is a framework that makes it easy to embed Chrome engine in your C++ app, it's called CEF - Chromium Embedded Framework. It supports Windows, Linux, Mac OS.

If you like Python, have a look at CEF Python, it's a project that provides python bindings for the CEF framework (by using Cython). CEF python currently supports only Windows, but there are plans for other OS'es.

Here is a list of applications that have been successfull using CEF (taken from here):

Adobe Brackets - code editor for the web

Adobe Edge - multimedia authoring tool

AppJS - build desktop applications using Node.js

AOL Instant Messenger - windows client uses CEF

Cubiez - integrates your favorite content into the desktop

Desura - online game platform

Dish World IPTV - streaming video platform

Evernote - notetaking software

ExeOutput - allows you to deploy html5/php applications as desktop applications

GitHub for Windows - GitHub client software for Windows

Janetter - twitter client software

mChef - mIRC browser plugin

MediaMan - organizer software

MetaVR - geographic simulation software

MTG Studio - game organizer software

OpenSpace3D - 3D development platform

Rdio - streaming music platform

Spotify - streaming music platform

Steam Client - online game platform

Tencent QQ - instant messaging program and web browser

Trend Micro - internet security software

WBEA Desktop - allows you to deploy html5 applications as desktop applications

Also have a look at this blog entry: Building a Desktop-Quality App on Web Technologies - Brackets editor team explaining how they built it using CEF framework and web technologies like: jQuery, Bootstrap, LESS CSS, requireJS, Jasmine for Unit testing, JSlint.

Disclaimer: I'm the author of CEF Python project.

Title: Cross-platform desktop programming: C++ vs. Python

Body:
Alright, to start off, I have experience as an amateur Obj-C/Cocoa and Ruby w/Rails programmer. These are great, but they aren't really helpful for writing cross-platform applications (hopefully GNUStep will one day be complete enough for the first to be multi platform, but that day is not today).

C++, from what I can gather, is extremely powerful but also a huge, ugly behemoth that can take half a decade or more to master. I've also read that you can very easily not only shoot yourself in the foot, but blow your entire leg off with it since memory management is all manual. Obviously, this is all quite intimidating. Is it correct?

Python seems to provide most of the power of C++ and is much easier to pick up at the cost of speed. How big is this sacrifice? Is it meaningful or can it be ignored?

Which will have me writing fast, stable, highly reliable applications in a reasonable amount of time?

Also, is it better to use Qt for your UI or instead maintain separate, native front ends for each platform?

EDIT: For extra clarity, there are two types applications I want to write: one is an extremely friendly and convenient database frontend and the other, which no doubt will come much later on, is a 3D world editor.


答:
Do other experienced developers notice the same thing happening?

Yes and no, for a number of reasons.

As developers (or anyone in a technical role) get more experienced, they start to look at roles and companies differently. Less experienced developers are happy to take more repetitive  or less desirable positions to get the experience. More experienced developers want more control over direction and higher profile work. Both are looking for jobs that pay well and challenge them but more experienced developers generally ask for higher pay and require something more difficult to challenge them.

Economics also comes into play. Many companies want software written but want to pay a competitive ("low" or "cheap") rate, leading many to off shore work where skills can be bought relatively cheaply. Few companies are prepared to invest in good local talent. Both strategies have merits but market conditions mean it is always easier to find work when you ask for lower pay.

Few interviewers tell the candidate the real reasons why he or she was not selected for a job. Vague answers are relatively safe from litigation, like "not a good fit" or "the role no longer exists" . However, it is important to remember that interviews go both ways and the candidate needs to appraise the potential employer, too. It sounds like the employer may not have been a good fit for the candidate, either.

That said (and I am not suggesting @nbv4 was this but, as a general comment) many senior developers tend to be intimidatingly self confident, particularly to those who are less technical or lack experience. No one likes to be told or inferred they are stupid. From their perspective, they may have been expecting developers to be excited about using the newest and latest tools like Mongo, and felt disappointed when the candidate did not have the expected reaction.

Employers are looking for the right people for the senior jobs, not just people with the right skills. Hiring senior developers is a major investment and the organization needs people that can work with the existing people. For example, the candidate should focus on how he or she can help the company solve their business problems and how he or she can teach and work with the people they have.

Title: Do other developers feel that as they get better, it becomes harder to get jobs?

Body:
When I was starting out, it seemed I had a much better time getting interviews and passing them. But now that I'm more experienced, I'm finding that its harder and harder to find a job. Do other developers out there feel the same way?

I'll give you an example. I did an interview last Wednesday. It was a small start-up with only one other engineer and the CEO. They flew me in from Ohio (they are SF based). When I got there, they had me write them a link shortener, which took me about 10 minutes to write. I was supposed to be there all day working on this. When I finished it early, the interviewer seemed kind of shocked. After that, we were talking, and I asked him what they use to store data. He told me Mongo. I ask why he decided to use mongo. He then stammered and mumbled his answer, which basically boiled down to "We're using it because Mongo is a the trendy database technology and we don't want to be left out", which I've found is pretty much most common reason people use NoSQL these days. The interviewer quickly ended the interview and pretty much shoved me out the door. I was supposed to have lunch with the CEO, but I he kicked me out before I had a chance. The intervier wasn't mean or rude, (and neither was I).

After I got back to Ohio, I got an email from them saying "I wasn't a fit". This sot of thing happens to me all the time. I'm starting to think "not a fit" can sometimes mean "are too high of a skill level that we are". Is this all in my head, or do other experienced developers notice the same thing happening? Back when I used to struggle with coding problems, I would work with the interviewer and it would be a positive thing and I'd get hired. But now I usually blow through the coding part, and the interviewer being left speechless is working against me. Should I feign struggling with coding problems?


答:
I know it's a bit old school, but (on the whole) misunderstandings about what something is to do should be sorted by one of two documents:

Software Requirements Specification (This is what we think you have asked for)

Software Design Specification (This is how we are going to do it)

Both of these should have customer approval, and buy in.

But with more "flexible" development systems (Agile, Scrum etc) the formal life-cycle is being   disapplied.  This (IMHO) is a return to the "wild-west" of Software Engineering of the early days.

This has led to Andrew's Law of Project Management:

We don't have time/budget/resources to do it right the first time, but
  we'll find the time/budget/resources to do it a second (and probably a
  third) time.


问:
Unit testing and Test Driven Development questions
I'm working on an ASP.NET MVC website which performs relatively complex calculations as one of its functions.

This functionality was developed some time ago (before I started working on the  website) and defects have occurred whereby the calculations are not being calculated properly (basically these calculations are applied to each user which has certain flags on their record etc).

Note; these defects have only been observed by users thus far, and not yet investigated in code while debugging.

My questions are:

Because the existing unit tests all pass and therefore do not indicate that the defects that have been reported exist; does this suggest the original code that was implemented is incorrect? i.e either the requirements were incorrect and were coded accordingly or just not coded as they were supposed to be coded?

If I use the TDD approach, would I disgregard the existing unit tests as they don't show there are any problems with the calculations functionality - and I start by making some failing unit tests which test/prove there are these problems occuring, and then add code to make them pass?

Note; if it's simply a bug that is occurring that can be found while debugging the code, do the unit tests need to be updated since they are already passing?

答:
Using TDD and automatic unit testing doesn't imply that the final tests will cover all cases and code will be absolutely correct and bug-free. It is easy not to see some complex use-cases and possible bug.

TDD on the other hand makes it easier to introduce changes for those not-thought-before cases. Simply repeat TDD as if you were developing:

Write new test case, that fails

Implement code, that will make this test succeed

Refactor code to remove duplicities and introduce good abstractions while keeping all tests passing


答:
The Qt way of C++ is great and clean, so please, drop the "ugly behemoth" part, I've tried them both, and personally I'm much more productive/comfortable with Qt/C++ than with Python's Qt binding.
That's my advice if you choose to go with Qt. Plus and beside the native experience that Qt widget provide, Qt5 and QtQuick2 with QML technology and the ability to embed JavaScript and HTML5 within your app, give you a modern web-like look & feel, if you choose to do so.

So, why I don't like Python in desktop apps and I prefer to keep it for scripting or server side things ?

Python breaks a bit the cross-platform joy, your client have to install Python to run your app (especially on Windows), and the different Python versions that are on the python's official website now make the client confused, which one to download/install.

Python to exe, make bigger apps (in term of size).

Python apps, eat more memory.

That's a personal point of view. Qt's parent system, smart pointers, wont let you shoot yourself in the foot, neither legs, the C++11 will give you even more features.


答:
In an ideal world, requirements must be as complete as possible, and there would be no deviation from expectations, since all expectations would be translated into requirements.

In the real world, on the other hand, requirements are often incomplete, which makes room to unwritten expectations. Examples:

An application takes ten minutes to do the simplest task, making it totally unusable (see the answer of David Schwartz above).

An application has blue buttons, while the stakeholder hates blue and her favorite color is yellow.

All user's passwords are stored in plain text and shown to everyone who goes through "Forgot my password" procedure.

The visual design sucks.

The application sends sensitive information back to the developer. The developer also has a back door access to the application, letting him to do whatever he want.

You notice that some expectations are very easily translated into requirements. For example, the first one can be verified with a simple non-functional requirement related to performance:

The loading of [...] performs 85% of the time below 500 ms. when tested on machine with the performances specified in appendix G part 2 and the load below 15% for the CPU, below 40% for memory and no active R/W disk operations.

Others need not one, but several requirements. For example, the third one cannot be expressed as:

The system is secure.

or:

Passwords are stored in a secure way.

since both are not the requirements: they are not precise enough and are subject to interpretation; they cannot be objectively tested. This means that you would need a requirement about the hashing algorithm, and several requirements about how "Forgot my password" procedure works by generating a password with a cryptographically secure pseudo-random number generator, then sending it by email.

Also, some expectations are close to objectiveness then others. At least, most people would agree that the fifth example illustrates something harmful: a developer doesn't have to have a full access to sensitive information, especially when he doesn't work on the project any longer. The same is not true for the point 4, and even more for the point 2: favorite color is something personal and cannot be a reasonable unwritten expectation for a project.

The objectiveness answers your question "[The] stakeholder could see a bug everywhere as he expected it to be like this or that..So how can I really know?":

If most people would have the same expectation for the same product, then you may want to implement the expectation. If you saved all the passwords plain text, it's up to you to correct this and to support the cost of the consequences. If, on the other hand, you hashed them with SHA512, but didn't use the salt, the stakeholder wouldn't be able declare this as a bug just because she expected PBKDF2 to be used instead.

If different people would have different opinions, then the stakeholder should have written more complete requirements, since you couldn't possibly know the taste of the stakeholder.

Note: remember to make the difference between common sense expectations and common practice expectations.

Some requirements are often omitted because they would cover a common practice, expected from any decent developer. Deviating from those practices, justifying it by the fact that there are no requirements, would be unprofessional. For example, I don't see a need to specify that a website must have no SQL Injection, unless I work with very inexperienced programmers.

Why those requirements are omitted? Because it would be to expensive to describe everything. Do we need to tell that a web application should use HTTP? Do we need to tell that it must use a database? Or that you don't save 1 GB-length files in a RDBMS, unless you use FILESTREAM feature of Microsoft SQL Server?

Example of a common sense expectation: "A website should be accessed from anywhere, not just from localhost." Well, yeah, that's what websites are for.

Example of a common practice expectation: "A website should use HTML 4, HTML 5 or XHTML." In fact, written from scratch HTML 3 websites are quite rare those days.


答:
I think it's a good filter for you to be able to find the right job.

I've realized that when I hire someone, its better to prefer someone smarter than me - especially if we can afford them. I would rather work with someone who proves me wrong (or at least provides new perspectives) and shows me a better way of accomplishing our goals rather than just go along. I'm sure the best people to work with will almost always follow this approach, but I do understand that this is not the case with a lot of companies. I guess it's time for you to start being picky about who you want to work with!

As an alternative, why don't you try to be an independent consultant/contractor? At least people don't mind hiring consultants to do something they can't (as opposed to employees). And you can be a little more expensive just to ensure that you don't undersell yourself (underselling not only gets you less money, it also reduces your perceive value in the person who's buying your service).


答:
This is exactly why you would want to consider Behavior driven development and Acceptance Test driven development - unit tests are not a guarantee about whether the system is doing what it is supposed to - it checks only whether it does what it was designed to do. The flip side is that product owners/Business analysts cannot review these tests very easily to verify that they are correct.

On the other hand, if you use acceptance tests, then they can be very easily verified by Business analysts or other non-tech folks. That can be quite useful.

In your particular case, I would say the product owner should take the decision on whether these are bugs or not - if they are, then obviously existing tests are either incorrect or at the very least insufficient - and you will have to write new (failing) ones and maybe even delete some of the old ones (which are expecting wrong things) before writing code that passes the new tests.

Title: Unit testing and Test Driven Development questions

Body:
I'm working on an ASP.NET MVC website which performs relatively complex calculations as one of its functions.

This functionality was developed some time ago (before I started working on the  website) and defects have occurred whereby the calculations are not being calculated properly (basically these calculations are applied to each user which has certain flags on their record etc).

Note; these defects have only been observed by users thus far, and not yet investigated in code while debugging.

My questions are:

Because the existing unit tests all pass and therefore do not indicate that the defects that have been reported exist; does this suggest the original code that was implemented is incorrect? i.e either the requirements were incorrect and were coded accordingly or just not coded as they were supposed to be coded?

If I use the TDD approach, would I disgregard the existing unit tests as they don't show there are any problems with the calculations functionality - and I start by making some failing unit tests which test/prove there are these problems occuring, and then add code to make them pass?

Note; if it's simply a bug that is occurring that can be found while debugging the code, do the unit tests need to be updated since they are already passing?


答: I like to imagine a very clever team of librarians in a beautifully made library with a million random and brilliant books, it would be quite a folly.</p>

Title: Torvalds' quote about good programmer

Body:
Accidentally I've stumbled upon the following quote by Linus Torvalds:

"Bad programmers worry about the code. Good programmers worry about
  data structures and their relationships."

I've thought about it for the last few days and I'm still confused (which is probably not a good sign), hence I wanted to discuss the following:

What interpretation of this possible/makes sense?

What can be applied/learned from it?


问:
What are MPEG I, P and B frames?
I was recently going over MPEG articles and videos to understand how it works. I understand what I, P and B frames do but I do not understand how the prediction is calculated.

Assume that I want to record a video of a ball falling from the sky to the ground and then bouncing a couple of times before finally coming to a halt.

Also, I am not clear with the concept of the 16x16 macroblock.
Please tell me:

 how prediction is calulated

 what is macroblock and how it helps in MPEG encoding

My references:

 MPEG Prediction

 Video on MPEG conversion

答:
Short answer:

Blocks are units for inter-frame comparison;

Prediction is based on amount of blocks presenting on both previous and following images;

Longer answer:

As input, a video encoder receives nothing else but a sequence of frames.

In most cases, the adjacent frames are very similar to each other, and the encoder attempts to figure out whether these frames are indeed similar.

How do you say if two images are similar?

Both images are split into macroblocks (you can't compare entire images, they will certainly differ!)

The algorithm attempts to find if a block from previous image exists on the following image (within a certain proximity to its original position)

If, to a certain threshold, most of the blocks present on the following image, the following image is computed as a difference to the previous one (P-frame);

Of course, differing blocks are encoded as-is;

If not, the following image is considered to belong to another scene, and there's no other way rather than keeping it entirely (I-frame).

In order to understand how prediction works, take a look at this image. It is created by a deshaker plug-in for VirtualDub, and used for a different purpose (detecting camera shakes), but it seems very representative:

The arrows indicate how the current image differs to the previous one;

The entire frame is split into macroblocks (larger than 16x16, however);

The difference for each block, compared to the previous image, is a movement vector;

As you see, most macroblocks (white arrows) follow the common pattern, and therefore they can be encoded by only applying a transposition matrix to a previous frame.

However, there are some blocks (red arrows) do not comply with the common pattern, and therefore they must be encoded as-is.

Of course, if everything is red, there's no choice other than encoding the entire frame as-is.

Title: What are MPEG I, P and B frames?


问:
User Acceptance Testing Defect Classification when developing for an outside client
I am involved in a large development project in which we (a very small start up) are developing for an outside client (a very large company).

We recently received their first output from UAT testing of a fairly small iteration, which listed 12 'defects', triaged into three categories : Low, Medium and High.

The issue we have is around whether everything in this list should be recorded as a 'defect' - some of the issues they found would be better described as refinements, or even 'nice-to-haves', and some we think are not defects at all.

They client's QA lead says that it is standard for them to label every issues they identify as a defect, however, we are a bit uncomfortable about this. Whilst the relationship is good, we don't see a huge problem with this, but we are concerned that, if the relationship suffers in the future, these lists of 'defects' could prove costly for us.

We don't want to come across as being difficult, or taking things too personally here, and we are happy to make all of the changes identified, however we are a bit concerned especially as there is a uneven power balance at play in our relationship.

Are we being paranoid here? Or could we be setting ourselves up for problems down the line by agreeing to this classification?

答:
You can say "Reported Customer Issue" or anything else if it makes people happy.  I'm going to say "Bug" because it has such a grand history and is the industry standard term.  In a brand new bug list, you might expect to fix near 100%.  But the more bugs that are added to the list, the fewer you expect to fix.  In fact, most bug tracking tools let you close bugs for various reasons: duplicate, feature-request, unable-to-reproduce, on-hold, additional-feedback-needed, etc.

The important thing is to capture the feedback and the actions taken on that feedback.  We make it very clear to our customers that we get to choose what bugs we fix and what features we implement.  We do it on the basis of what we think will make the most clients most happy, but it's our choice.

Be respectful in providing feedback on these bugs.  If you aren't going to fix something, tell them why.  Sometimes it's OK to say that you aren't ready to commit to a particular solution to a given bug.  Or that a bug is out of scope for this release (or this product).  Or that a bug in how the system works might be "fixed" through improved documentation (such as tweaking the UI or documentation so that users don't do what caused the bug).  Obviously, if you fix some bugs, your client will be more open to your not fixing others.

If the customer has major problems using your software, no bug naming system will make them happy.  If they love your software, the name won't matter either.  Make great software, be respectful to your client and don't get hung up on bug categories.


答:
I've seen this is numerous areas.

Think about business analysis...   Let's say you're analyzing the best way to support Marketing at a consumer products company like Colgate.  If you start with fancy windows, or the latest technology, you won't help the business nearly as much as if you think through the data needs of the business first, and then worry about presentation later.  The data model outlasts the presentation software.

Consider doing a webpage.  It's much better to think about what you want to show (the HTML) first, and worry about style (CSS) and scripting (pick your tool) after.

This isn't to say coding isn't important too.  You need programming skills to get what you need in the end.  It's that data is the foundation.  A poor data model reflects either an overly complex or unthought business model.

Title: Torvalds' quote about good programmer