问:
Passing parameters in same object as responses
I have a number of operations that need to be performed, in series, on the same set of data.  As the operations progress, later operations require information from the prior operations.  So the initial object passed in to the first method snowballs as it collects results and metadata.

At first I was passing around both a request and a response, but that painted me into a corner a couple times.  So now what I intend to do is just have one parameter object that contains all the initial data, it remembers interim values, and delivers the final results, all within a single object that is passed around to many void methods.

My questions:  Is this a pattern?  Or is this bad form?

My contrived example is below.

```<code>    class Program
    {
        static void Main()
        {
            var MyObj = new RequestResponseInfo();
            MyObj.InitalValue = "fo";
            foobar.DoStuff(MyObj);
            Console.WriteLine(MyObj.FinalAnswer);
            Console.ReadKey();
        }
    }

    public static class foobar
    {
        public static void DoStuff(RequestResponseInfo myObj)
        {
            DoSomething_A(myObj);
            DoSomething_B(myObj);
            myObj.FinalAnswer = myObj.A + myObj.B;
        }

        private static void DoSomething_A(RequestResponseInfo myObj)
        {
            myObj.A =  myObj.InitalValue + "ob";
        }

        private static void DoSomething_B(RequestResponseInfo myObj)
        {
            myObj.B = "ar";
        }
    }

    public class RequestResponseInfo
    {
        public string InitalValue { get; set; }
        public string A { get; set; }
        public string B { get; set; }
        public string FinalAnswer { get; set; }
    }
</code>```

答:
What you are showing is programming with heavy side effects, which has the risk to lead to unmaintainable code, because it depends heavily on the correct order of execution, and the signatures of the Do... methods don't provide any information about their input and output. Here is an alternative design:

```<code>public class MyFooBarClass
{
    public MyFooBarClass(string initialVal)
    {
          InitalValue=initialVal;
    }
    public readonly string InitalValue;

    public string A { get { return InitalValue + "ob";}}
    public string B { get {return "ar"; }}
    public string FinalAnswer { get{return A+B;} }
}
</code>```

Now, the order of execution is always correct, you can access the properties A ,B or FinalAnswer in any order you like, the object has become immutable, which makes it more robust against changes or multithreading. Of course, when you call FinalAnswer multiple times, the same calculation will be repeated again, so if your notice a (measurable!) loss of performance, you may have to introduce memoizing techniques (but I would avoid any premature optimization if there is no real reason for this).

Another design alternative, if you really need to separate the result object from the calculation class:

```<code> public static class foobar
 {
    public static Result DoStuff(string initialVal)
    {
        string a = DoSomething_A(initialVal);
        string b = DoSomething_B();
        string finalAnswer = A + B;
        return new Result(initialVal,a,b,finalAnswer);
    }

    private static string DoSomething_A(string initialVal)
    {
        return initialVal + "ob";
    }

    private static string DoSomething_B()
    {
        return "ar";
    }
 }

   public class Result
   {
       public Result(string initalValue, string a, string b, string finalAnswer)
       {
           InitalValue=initalValue;
           A=a;
           B=b;
           FinalAnswer=finalAnswer;
       }
       public readonly string InitalValue;
       public readonly string A;
       public readonly string B;
       public readonly string FinalAnswer;
   }
</code>```

This makes the data flow much more expressive, you now see immediately what each of the Do methods uses as input, what it returns as output, and the result object is still immutable.

Body:
What you are showing is programming with heavy side effects, which has the risk to lead to unmaintainable code, because it depends heavily on the correct order of execution, and the signatures of the Do... methods don't provide any information about their input and output. Here is an alternative design:

public class MyFooBarClass
{
    public MyFooBarClass(string initialVal)
    {
          InitalValue=initialVal;
    }
    public readonly string InitalValue;

    public string A { get { return InitalValue + "ob";}}
    public string B { get {return "ar"; }}
    public string FinalAnswer { get{return A+B;} }
}

Now, the order of execution is always correct, you can access the properties A ,B or FinalAnswer in any order you like, the object has become immutable, which makes it more robust against changes or multithreading. Of course, when you call FinalAnswer multiple times, the same calculation will be repeated again, so if your notice a (measurable!) loss of performance, you may have to introduce memoizing techniques (but I would avoid any premature optimization if there is no real reason for this).

Another design alternative, if you really need to separate the result object from the calculation class:

 public static class foobar
 {
    public static Result DoStuff(string initialVal)
    {
        string a = DoSomething_A(initialVal);
        string b = DoSomething_B();
        string finalAnswer = A + B;
        return new Result(initialVal,a,b,finalAnswer);
    }

    private static string DoSomething_A(string initialVal)
    {
        return initialVal + "ob";
    }

    private static string DoSomething_B()
    {
        return "ar";
    }
 }

   public class Result
   {
       public Result(string initalValue, string a, string b, string finalAnswer)
       {
           InitalValue=initalValue;
           A=a;
           B=b;
           FinalAnswer=finalAnswer;
       }
       public readonly string InitalValue;
       public readonly string A;
       public readonly string B;
       public readonly string FinalAnswer;
   }

This makes the data flow much more expressive, you now see immediately what each of the Do methods uses as input, what it returns as output, and the result object is still immutable.


问:
Access items of a container with a pattern
I've two C++ classes with a relation: a container class which has a list of items. For example a library has got many books. The classes are the library and the book.

Now from the external world I have to create, update and delete books. In addition there other classes that are interested to know when an event on a book happens and these (observers) instances can be created at run-time.

Now I've got different ways to proceed:

1) Use always the container to do the operation: central point of management but I have to create couples of methods for example setTitle(bookID) that call setTitle() on the book, bad;

2) Use a getBook() on the container to return a reference of the book, allow the modification, at this point I have to use a commit method to notify the container which can notify the observer but in this way the pattern doesn't force a "commit", I mean if the external caller doesn't call commit() I loose :)

3) Use a getBook() on the container to return a copy of the book and an update method of the container to overwrite the book, central point of management again but the book if big is a problem, a lot of copies are really bad.

Any tips? Is there any pattern that covers this use case?

答:
Interesting question.  If the language were C# or Java, you could use reflection, proxies, or delegates in order to learn whether or not an event occurred in the book class.  Granted, these solutions are a little heavy handed for such a simple matter, however the problem remains.

C++ doesn't have reflection, proxies, or delegates.  However, what you can do is ensure that objects like Book derive from a common class that keeps track of changes.

Specifically, I'm talking about the Subject/Observer pattern.  Book would derive from the Subject class whose sole methods would be:

```<code>public:
   bool isChanged() const;
   void resetChanged();

   void addChangeObserver(Observer &observer);
protected:
   void setChanged();
</code>```

The idea is that Subject can tell you if an object has changed and its changed status can be reset.  In addition it lets you keep track of observers through addChangeObserver.

Book would derive from Subject, and Library would initially reset the change status of all added books.  It would then have a getBook method and assuming Book responsibly sets the change status, Library could later know it.  If you wish to perform an action upon a change event, then it would add itself as an Observer for all books added (at which point Library would also have to derive from Observer).

Again, this is a little overboard, but you gain all the advantages of decoupling at the slight expensive of complicating the code.  However, in a large project, you almost have to do it this way since keeping code decoupled is increasingly important as it grows.

I hope that helps.

ContentLicense: CC BY-SA 3.0

Body:
Interesting question.  If the language were C# or Java, you could use reflection, proxies, or delegates in order to learn whether or not an event occurred in the book class.  Granted, these solutions are a little heavy handed for such a simple matter, however the problem remains.

C++ doesn't have reflection, proxies, or delegates.  However, what you can do is ensure that objects like Book derive from a common class that keeps track of changes.

Specifically, I'm talking about the Subject/Observer pattern.  Book would derive from the Subject class whose sole methods would be:

public:
   bool isChanged() const;
   void resetChanged();

   void addChangeObserver(Observer &observer);
protected:
   void setChanged();

The idea is that Subject can tell you if an object has changed and its changed status can be reset.  In addition it lets you keep track of observers through addChangeObserver.

Book would derive from Subject, and Library would initially reset the change status of all added books.  It would then have a getBook method and assuming Book responsibly sets the change status, Library could later know it.  If you wish to perform an action upon a change event, then it would add itself as an Observer for all books added (at which point Library would also have to derive from Observer).

Again, this is a little overboard, but you gain all the advantages of decoupling at the slight expensive of complicating the code.  However, in a large project, you almost have to do it this way since keeping code decoupled is increasingly important as it grows.

I hope that helps.


问:
Do we tell the object to do something or do we do something (on/with/to/etc.) the object?
Take the (unprecedented and groundbreaking) example of the calculator:

```<code>public class Calculator
{
    public double Add(double augend, double addend)
    {
        return augend + addend;
    }
}
</code>```

When I write calculator.Add(val1, val2) which of the following am I doing?

Telling the calculator to add the inputs

Adding the inputs with the calculator

(One could also ask: "Is it a method of the object or is it a method on the object?")

Other examples: do we tell the repository to add the entity or do we add the entity to the repository? Do we tell the message service to deliver a message or do we send a message through the message service? Do we tell the can of paint to mix itself or do we mix the can of paint?

答:
is it a method of the object or is it a method on the object?

It is a method of the class.

You create instances of classes to encapsulate state, not code.  All of the code in that method is the same code across all of the objects; only the state (private variables) varies between objects.

Calling methods is a form of message passing.  You send a message to an object by calling a method.  The method can send back a message of its own by returning some value. The method may also cause side effects by altering the state of the object, writing to a log, etc.

Do we tell the can of paint to mix or do we mix the can of paint?

If you call

```<code>canOfPaint.Mix();
</code>```

You are telling the can of paint to mix.

If you call

```<code>Mix(canOfPaint)
</code>```

You are mixing the can of paint.

Body:
is it a method of the object or is it a method on the object?

It is a method of the class.

You create instances of classes to encapsulate state, not code.  All of the code in that method is the same code across all of the objects; only the state (private variables) varies between objects.

Calling methods is a form of message passing.  You send a message to an object by calling a method.  The method can send back a message of its own by returning some value. The method may also cause side effects by altering the state of the object, writing to a log, etc.

Do we tell the can of paint to mix or do we mix the can of paint?

If you call

canOfPaint.Mix();

You are telling the can of paint to mix.

If you call

Mix(canOfPaint)

You are mixing the can of paint.


问:
How is quality important to the programmer, the person?
I didn't ask how the quality of the software is important to the product itself, the customers/users, the manager or the company. I want to know how it is important to the programmer that build it.

I'll be interested in any books (please specify the chapter), articles, blog post, and of course your personal opinion on the subject regardless your experience.

答:
There are some programmers who take professional pride in the work they deliver. Who take personal responsibility to ensure that they test and validate their code, and want to leave a legacy for other programmers to follow in their footsteps.

The fact that their code is clear, well tested, easily extendible and used by paying customers is a key part to their sense of satisfaction of a job well done.

ContentLicense: CC BY-SA 2.5


答:
In my opinion it's a matter of the context in the system, and sometimes depends on the conceptual role of the component in the system.

For example in a game, a character might have a method attack(). Is it meant to allow other characters to attack this character? Or is it a method used to tell the character to attack? Totally depends on your system.

Title: Do we tell the object to do something or do we do something (on/with/to/etc.) the object?

Body:
Take the (unprecedented and groundbreaking) example of the calculator:

```<code>public class Calculator
{
    public double Add(double augend, double addend)
    {
        return augend + addend;
    }
}
</code>```

When I write calculator.Add(val1, val2) which of the following am I doing?

Telling the calculator to add the inputs

Adding the inputs with the calculator

(One could also ask: "Is it a method of the object or is it a method on the object?")

Other examples: do we tell the repository to add the entity or do we add the entity to the repository? Do we tell the message service to deliver a message or do we send a message through the message service? Do we tell the can of paint to mix itself or do we mix the can of paint?


问:
Fixing bugs generated by another team
I'm facing the following situation:

There are 2 different teams working on the same project using Scrum, and every now and then, bugs related to user stories developed by team "A" are being assigned to team "B".  We're used to fixing bugs made by other people when they belong to the same team, but things get a bit more complicated when different teams are involved. Some of the developers don't like working this way and say that the bugs must be fixed by the ones who made them, and this is causing some conflicts between the teams.

While reading some of the similar questions I've found some interesting ones (Is fixing bugs made by other people a good approach? and also Parallel teams and scrum/agile), but they are not about the same situation, or at least I don't see them that way.

During our discussions here we got 2 possible approaches: Leave the situation as is, or determine that the bugs must be assigned to the team that developed the feature. Do you guys have any suggestions?

答:
I can see this happening in two situations, and those situations need different ways to resolve the issue.

The two teams work on different areas of the overall application, they have different areas of expertise and the bugs get assigned to the wrong team because the issue appears at first glance to belong to that team.

In that case, welcome to the world of large scale software development.

The issue can be addressed relatively easy in this case. If you realize that, after analyzing the bug, it doesn't lie in your area of expertise, you re-assign the bug to the right team/person.

If it happens very frequently, you could think about setting up a small team with people from both teams "A" and "B" to pre-analyze incoming issues and ensure they get assigned to the right team.

The teams work on the same parts of the overall application and they have overlapping areas of expertise.

In this case, they should really be regarded as one big team and the core issue seems to be that the team members don't view it as such. In this situation, the solution should be looked for more in the area of getting teams "A" and "B" to become to regard each other as members of a bigger team.

Title: Fixing bugs generated by another team


问:
Is lack of whitespace a sign of a cargo cult programmer?
Eric Lippert has written about cargo cult programming, and Steve McConnell has tackled the subject from a Software Engineering point of view.

Eric provides a fairly succinct description:

They understood the form but not the content.  There are lots of cargo cult programmers -- programmers who understand what the code does, but not how it does it.  Therefore, they cannot make meaningful changes to the program.  They tend to proceed by making random changes, testing, and changing again until they manage to come up with something that works.

This isn't to say that cargo cult programmers are bad, per se, just that they approach coding differently than others.  Their goal is to get things done; not understand why the code is doing something.  This Programmers question discusses formatting and "sloppy programmers", but it's different in that it doesn't focus on whitespace and it's clear the programmers are considered bad.

Much has been written on Programmers about using comments as well as the use of whitespace.

The general acceptance is to use comments to explain "why not what" and to use whitespace to separate out logical constructs within the code.  To borrow from traditional writing, whitespace provides paragraphs of text to read instead of facing a wall of text.  It separates out key concepts.

I'm in the middle of re-factoring some code originally written by a cargo cult programmer, and one of the challenges I have encountered is consistent lack of whitespace to indicate context or concepts within the program.  Looking over the code, it's clear to me the developer didn't understand the why or the context behind the task they were assigned.  Ignoring the incorrect copy & paste issues, the code just doesn't read well because of disjointed flow amongst statements.

I realize that use of whitespace is biased by the original language that someone first learns, but I can't help but wonder if "illogical" use of or lack of use of whitespace is an indicator of a cargo cult programmer.

My question: -- Is there a correlation between not using whitespace correctly and the odds of the person being a cargo cult programmer?

Addendum:

I realize my question is subjective, but I think it falls into the good subjective category because this question is best answered with a "why" type answer rooted in experience and / or potentially some amount of research.  Likewise, I believe there is an answer to the question, and I have focused the question on identifying if there is a correlation while avoiding any potential ranting.

In my question, I am using the broader definition of cargo cult programming as defined by Eric.  Cargo Cult Programmers mix and match forms because the snippet they took appears to solve the problem at hand.  Yet they do not understand why the sections they copied resolve the issue.  In this context, I don't see Cargo Cult Programming as attempting to imitate another person's style, but rather just trying to "fix" whatever the problem at hand is with whatever code they can find.

答:
I would say there's a correlation but not necessarily causation.  People who have difficulty understanding the meaning behind a program also tend to have difficulty  seeing how whitespace enhances other people's understanding of that meaning.

The same effect is seen in prose.  People who have trouble coherently grouping their thoughts also tend to see little value in separating those groupings with paragraphs.

It's possible for technically solid code to be very poorly formatted, but in general you can assume programmers' formatting skills are commensurate with the rest of their programming skills.  I've seen a few exceptions, mostly with programmers who have worked alone for many years, or naturally very talented programmers straight out of school.

Whether poorly formatted code confirms a cargo-cult mentality or not doesn't change the result.  It makes you trust the code less, so even if you fix the whitespace you will be on the lookout for other problems, instead of believing the code does what it says it does.  In other words, if you want your code to be taken seriously, it needs to look nice.

ContentLicense: CC BY-SA 4.0


问:
Is there any reason not to use Optional as a method argument in the case where you know the argument is something that may or may not be needed?
With Java 8, I've seen more and more articles about the use of Option/Optional. I understand what they trying to represent, and I see many examples of them being used as returns. However what I don't see is them being used as method/function arguments in languages that don't have the syntax for default/optional parameters.

Is there any reason not to use Optional as a method argument in the case where you know the argument is something that may or may not be needed? Here's an example I could think of:

```<code>Optional<Customer> lookupCustomer(String firstName, Optional<String> middleName, String lastName)
</code>```

答:
There aren't very many languages that don't support default arguments, so this is not a common usage.  I personally think your usage isn't terrible, but it's not going to be idiomatic Java.  Java very intentionally doesn't have default arguments, to force the use of overloading instead, which has the advantage of the compiler checking your arguments instead of requiring if statements inside the function.

In other words, you're going to be making two different versions of the query: one with a middle name and one without.  If you can do that in a concise way, using an option is a good idea.  If it's verbose enough that you'd want it in two separate functions anyway, you may as well use the overloading and make it idiomatic.


问:
Is it correct to call the assignment symbol an "operator" when it is actually a statement?
In some languages (C++, Java, Ruby, etc.) an assignment returns a value and can be used in an expression:

```<code>x = (y = z);    // ok, 'x' gets the value of 'z'
</code>```

In other languages (Ada, VHDL), an assignment is a proper statement and cannot be used in as expression:

```<code>x := (y := z);   -- error!
</code>```

However, in both cases, it is possible to find teaching material where the assignment symbol is called the "assignment operator".

My question is, is it technically correct to call the assignment symbol an "operator" in the second case, where it is actually a statement, does not return a value, and cannot be
used in the middle of an expression?

答:
The assignment statement is made up of three parts:

The target, or lvalue.

The assignment operator.

The value to be assigned, or rvalue.

The rvalue can be a constant or an expression that returns a value of the correct (or not necessarily correct, in some languages) type. The requirement is that the value to be assigned itself forms a valid rvalue under the rules of the specific language.

As you point out, some languages make an assignment statement return the assigned value. C, C++, C#, Java, and a whole slew of others do it that way, some with restrictions. This is a potentially dangerous practice, but it is an incredibly useful shorthand notation in the hands of those who know how to use it. As we know, that means people will misuse it, either deliberately or because they don't understand the finer details of the syntax involved. The technical way to express this is that the assignment statement does form a rvalue.

So some other languages make assignment statements valid only as stand-alone statements, and dictate that the assignment operator is only valid inside a valid assignment statement. In other words, in these languages a complete assignment statement is not a valid rvalue.

Both are valid ways to design a language, depending on one's goals. Always keep in mind that C was designed to be able to do basically anything assembly language can do, only in a portable and preferably more readable fashion, and many C-like languages derive many features directly from C, even if the syntax is slightly different. Ada on the other hand was designed to make it extremely hard to write programs that do anything but exactly what is expected.

It follows from the above reasoning that = in C, C++, C#, Java, ...; := in Pascal, Ada, ...; and so on, can all properly be called the assignment operator, which forms one part of a complete assignment statement. Whether a complete assignment statement forms a valid rvalue is a different matter and really has nothing to do with the status of the character sequence as such which is used to indicate assignment to a lvalue.


答:
One reason is that conceptually, firstName, middleName, and lastName are logically one argument, not three. They're all parts of a bigger whole, and one can imagine that they're almost always passed together. In functional languages they'd likely be passed as a tuple or record; Java lacks those, so they'd probably be aggregated into a Name class. Note that if you needed to compose functions that take and return full names, you wouldn't be able to without aggregating them - you can only return one value, after all.

Maybe it just doesn't come up very often that a value is optional and also not part of a bigger whole. If the function requires a certain value to do its work, then that function shouldn't be accepting an Optional. If you need to chain operations that might not return a value, aborting with Nothing if any function along the way fails, you can chain calls to flatMap, and if you want to fail with an exception you can use get() at any step of the way or at the end of the chain.

If a value is truly optional and a function does two different things based on its presence or absence, that's a code smell unless the function is a wrapper of two smaller functions that do one thing each, and that particular combination of decisions is very common.

I don't think it's so much that it's wrong as it is a relatively uncommon use case.

Body:
With Java 8, I've seen more and more articles about the use of Option/Optional. I understand what they trying to represent, and I see many examples of them being used as returns. However what I don't see is them being used as method/function arguments in languages that don't have the syntax for default/optional parameters.

Is there any reason not to use Optional as a method argument in the case where you know the argument is something that may or may not be needed? Here's an example I could think of:

```<code>Optional<Customer> lookupCustomer(String firstName, Optional<String> middleName, String lastName)
</code>```


问:
Why can't a server continue to act on a request after sending the response?
Say for example I've got a RESTful webservice, and I need to support creating a widget via a POSTed http request. I need to

Deserialize the POSTed widget.

Validate the deserialized widget.

Persist the widget to a backing service.

Send a success response back to the client.

Now, the problem is that my SLA does not allow 3 to block 4--persistence in this case takes too long and the client needs to know right away that the request has succeeded (this is the standard use case for the 202 http status code).

Almost everywhere I look, the assumption is that the way to solve this is to "background" the expensive persistence part. This is typically an awkward process with many moving parts and often its own latency (e.g. making a blocking call to a separate queuing service).

Simply parallelizing 3 and 4 using native constructs is generally out of the question, as is switching the order so that 4 blocks 3. As near as I can tell, this is mainly because the web and app servers are built with the fundamental assumption that a process (and any children it's forked off) is free to be killed/reused as soon as it's sent its response. Or, equivalently, that the response can't be sent until the app has finished doing everything it's going to do.

This is intensely frustrating to me! In any other context, I can do what I like with the program's control flow. But when I'm running a Phusion Passenger -> Ruby on Rails setup, and I want to do a thing after I send the response, I'm left with a wide variety of baroque options that all seem to consider it perfectly natural and acceptable to, say, serialize the application state, post it to Amazon SQS, have basically separate web service that polls SQS, deserializes the old application state, then do the thing. I had application state all set up the way I wanted it after sending the response! Why isn't anything written so I can just do

```<code>def create
  widget = Widget.new(params[:widget])
  if widget.valid?
    respond_with(widget)
    widget.save
  else
    respond_with(widget.errors)
  end
end
</code>```

Why is there a pervasive assumption that web service stacks will never support this kind of flow? Is there a hidden drawback, or tradeoff, to making it possible to do this?

答: I think that the problem here stems from the fact that the client now assumes that widget exists and will be available even though its entirely possible for save to have failed for any number of reasons.  This leaves your front and backend in an inconsistent state, also REST is Representational state transfer, if you aren't actually transferring an accurate representation of the state, its not really REST</p>


答:
To keep within the story of the Cargo Cult, this would be like someone who writes code that does "Some Amazing Thing" and thinks hoards of programmers will contribute to this open source project even though the code itself is poorly formatted. Everyone else gets tons of contributors and my app is just as amazing as theirs.

How many people will look at this and not even bother? Maybe someone with some time on their hands will put in all the white space and that will get the project some traction. it leaves a lot of doubt about the lead developer. Who knows, maybe this code was copied from somewhere else and put into Word.

There are some who don't think formatting matters especially in "this" case. Good programmers format without even thinking about it, so there isn't even a drop in productivity.

A good carpenter touches a piece of material the fewest number of times as necessary: cut a small piece off a board, throw it in the scrap bin and not on the floor only to have to pick it up and throw it away later.

Title: Is lack of whitespace a sign of a cargo cult programmer?

Body:
Eric Lippert has written about cargo cult programming, and Steve McConnell has tackled the subject from a Software Engineering point of view.

Eric provides a fairly succinct description:

They understood the form but not the content.  There are lots of cargo cult programmers -- programmers who understand what the code does, but not how it does it.  Therefore, they cannot make meaningful changes to the program.  They tend to proceed by making random changes, testing, and changing again until they manage to come up with something that works.

This isn't to say that cargo cult programmers are bad, per se, just that they approach coding differently than others.  Their goal is to get things done; not understand why the code is doing something.  This Programmers question discusses formatting and "sloppy programmers", but it's different in that it doesn't focus on whitespace and it's clear the programmers are considered bad.

Much has been written on Programmers about using comments as well as the use of whitespace.

The general acceptance is to use comments to explain "why not what" and to use whitespace to separate out logical constructs within the code.  To borrow from traditional writing, whitespace provides paragraphs of text to read instead of facing a wall of text.  It separates out key concepts.

I'm in the middle of re-factoring some code originally written by a cargo cult programmer, and one of the challenges I have encountered is consistent lack of whitespace to indicate context or concepts within the program.  Looking over the code, it's clear to me the developer didn't understand the why or the context behind the task they were assigned.  Ignoring the incorrect copy & paste issues, the code just doesn't read well because of disjointed flow amongst statements.

I realize that use of whitespace is biased by the original language that someone first learns, but I can't help but wonder if "illogical" use of or lack of use of whitespace is an indicator of a cargo cult programmer.

My question: -- Is there a correlation between not using whitespace correctly and the odds of the person being a cargo cult programmer?

Addendum:

I realize my question is subjective, but I think it falls into the good subjective category because this question is best answered with a "why" type answer rooted in experience and / or potentially some amount of research.  Likewise, I believe there is an answer to the question, and I have focused the question on identifying if there is a correlation while avoiding any potential ranting.

In my question, I am using the broader definition of cargo cult programming as defined by Eric.  Cargo Cult Programmers mix and match forms because the snippet they took appears to solve the problem at hand.  Yet they do not understand why the sections they copied resolve the issue.  In this context, I don't see Cargo Cult Programming as attempting to imitate another person's style, but rather just trying to "fix" whatever the problem at hand is with whatever code they can find.


答:
nothing is stopping a web service from continuing to process data after a response is sent. Your problem is probably due to the choice of framework forcing you into a simplistic request-response-done interaction.

Your service could start a thread and send it data to work on, or pass it (asynchronously) to another service to work on.

You could implement a websocket and send multiple responses to the client as data becomes available.

The issues you might have are generally down to scalability. What if your background worker takes a long time to process, or every request spins off a thread - you may end up with a lot of background work being done so there is much less resources available for client requests.

Title: Why can't a server continue to act on a request after sending the response?

Body:
Say for example I've got a RESTful webservice, and I need to support creating a widget via a POSTed http request. I need to

Deserialize the POSTed widget.

Validate the deserialized widget.

Persist the widget to a backing service.

Send a success response back to the client.

Now, the problem is that my SLA does not allow 3 to block 4--persistence in this case takes too long and the client needs to know right away that the request has succeeded (this is the standard use case for the 202 http status code).

Almost everywhere I look, the assumption is that the way to solve this is to "background" the expensive persistence part. This is typically an awkward process with many moving parts and often its own latency (e.g. making a blocking call to a separate queuing service).

Simply parallelizing 3 and 4 using native constructs is generally out of the question, as is switching the order so that 4 blocks 3. As near as I can tell, this is mainly because the web and app servers are built with the fundamental assumption that a process (and any children it's forked off) is free to be killed/reused as soon as it's sent its response. Or, equivalently, that the response can't be sent until the app has finished doing everything it's going to do.

This is intensely frustrating to me! In any other context, I can do what I like with the program's control flow. But when I'm running a Phusion Passenger -> Ruby on Rails setup, and I want to do a thing after I send the response, I'm left with a wide variety of baroque options that all seem to consider it perfectly natural and acceptable to, say, serialize the application state, post it to Amazon SQS, have basically separate web service that polls SQS, deserializes the old application state, then do the thing. I had application state all set up the way I wanted it after sending the response! Why isn't anything written so I can just do

```<code>def create
  widget = Widget.new(params[:widget])
  if widget.valid?
    respond_with(widget)
    widget.save
  else
    respond_with(widget.errors)
  end
end
</code>```

Why is there a pervasive assumption that web service stacks will never support this kind of flow? Is there a hidden drawback, or tradeoff, to making it possible to do this?


答:
Now, the problem is that my SLA does not allow 3 to block 4--persistence in this case takes too long and the client needs to know right away that the request has succeeded (this is the standard use case for the 202 http status code).

But until the state change is persisted, you can't know that you're successful. You might have a sudden problem with electrical power and an errant backhoe (this stuff happens!) and then when the service resumes, it's completely forgotten about the resource. The client comes back and the server has no idea what its talking about. That's not good.

No, you need to speed up commits (and avoid unnecessary processing in the critical path).

You may need to think about how you can logically commit faster, about what it means to commit; you can just commit the fact that there is work to do instead of having to require the result of the work, which can be done much more rapidly. Then when the user comes back, either the processing is done in which case you can 301 to the results, or you can give a result that says why things are still processing or that they've failed.

Getting faster commits might mean thinking more carefully about how you deploy. Are you using the right database choice? Is that database hosted on the right hardware? (Commit-heavy loads are much faster when you've got an SSD to host the transaction log on.) I know it's nice to ignore these things and just deal with the data model at an abstract level, but performance is one of those things where the underlying details have a habit of leaking through.

In response to comments clarifying…

If you've got a genuinely expensive task to perform (e.g., you've asked for a collection of large files to be transferred from some third party) you need to stop thinking in terms of having the whole task complete before the response comes back to the user. Instead, make the task itself be a resource: you can then respond quickly to the user to say that the task has started (even if that is a little lie; you might just have queued the fact that you want the task to start) and the user can then query the resource to find out whether it has finished. This is the asynchronous processing model (as opposed to the more common synchronous processing model).

There are many ways to handle letting the user know that the task has finished. By far the simplest is to just wait until they poll and tell them then. Alternatively, you can push a notification somewhere (maybe an Atom feed or by sending an email?) but these are much trickier in general; push notifications are unfortunately relatively easy to abuse. I really advise sticking to polling (or using cleverness with websockets).

The case where a task might be quick or might be slow and the user has no way to know ahead of time is really evil. Unfortunately, the sane way to resolve it is to make the processing model be asynchronous; it's possible to do either way flipping with REST/HTTP (it's either sending a 200 or a 202; the 202's content would include a link to the processing task resource) but it is quite tricky. I don't know if your framework supports such things nicely.

Be aware that most users really do not understand asynchronous processing. They do not understand having to poll for results. They do not appreciate that a server can be doing things other than handling what they asked it to do. This means that if you are serving up an HTML representation, you probably ought to include some Javascript in it to do the polling (or connecting to a websocket, or whatever you choose) so that they can not need to know about page refreshing or details like that. Like that you can go a long way towards pretending that you're just doing what they asked it to do, but without all the problems associated with actual long-running requests.


问:
Logging system interactions as a user vs as a flag
When running a site that has a CRM with a logging facility that logs users interactions (someone changing a name, address or user permission etc), is it better to log system interactions (automated tasks and alike) as a fake user set up as a constant either in a "users" object, or as part of the application settings so you can either do applicationscope.SystemUser or UserObject.getSystemUser().

Having talked in work, some colleagues believe it is an abuse of the User database to have a fake user in there to represent the System and believe it better to alter up the database so tables that are affected by such a change carry a isSystem flag that would be set to 1 should the system make changes.

答:
The issue is that the system authorization context is the right thing to be associating with the system tasks, but it's not really a user. But spreading lots of “isSystem” magic flags all over the place is just a recipe for getting it wrong (seriously; you're looking at something that will tend to produce errors and in ways that fail in ways that can be really embarrassing for you). We need another way. Fortunately, there is one; it's all really a matter of you having your conceptual class hierarchy wrong.

Right now, you have all users as instances of UserObject, and nominate one of them as being special. Well, we want to put the special-ness of the system identity in the class hierarchy (nominating special instances is problematic in itself). We do that by defining a SystemUser, which is different in that you create a (singleton?) instance of it and prohibit it from logging in. Subclass it from UserObject and you've captured what's going on…

Except… it doesn't sound like a user really, does it? So let's change the class hierarchy. Instead of having SystemUser inherit from UserObject, let's have a new superclass/interface, IdentityContext, and have SystemIdentityContext (note the name change; we don't need to pretend that it's a user now) and UserObject both inherit from it. You can then make logging in an added feature of UserObject, safe in the knowledge that the system can definitely never log in — you're not abusing that humble database of users — and yet you've got an unambiguous notion of identity that clearly marks those system tasks for what they are.

(Whenever you've got a problem where you've got two alternatives that appear to be both equally valid in some way and yet neither is perfect, take a moment to step back and think “Is there another way that I've not spotted yet?” There usually is…)


答:
Generally speaking, it doesn't matter.

If you're telling a Calculator object to add, your code looks like this:

```<code>class Calculator {
  public Double add(Double a, Double b) {
    return a + b;
  }
}
</code>```

If you're adding two number with a Calculator, it looks like this:

```<code>class Calculator {
  public Double add(Double a, Double b) {
    return a + b;
  }
}
</code>```

The implementation is the same. And I suspect your code will be the same in most cases regardless of which preposition you use to describe it. In most cases, your object is both the subject and direct object of the verb. In cases where it won't be the same, you should try to clarify the method name or include adequate documentation to indicate what role the object plays in the action.

Body:
Generally speaking, it doesn't matter.

If you're telling a Calculator object to add, your code looks like this:

class Calculator {
  public Double add(Double a, Double b) {
    return a + b;
  }
}

If you're adding two number with a Calculator, it looks like this:

class Calculator {
  public Double add(Double a, Double b) {
    return a + b;
  }
}

The implementation is the same. And I suspect your code will be the same in most cases regardless of which preposition you use to describe it. In most cases, your object is both the subject and direct object of the verb. In cases where it won't be the same, you should try to clarify the method name or include adequate documentation to indicate what role the object plays in the action.


问:
Pure Front end JavaScript with Web API versus MVC views with ajax
This was more a discussion for what peoples thoughts are these days on how to split a web application.

I am used to creating an MVC application with all its views and controllers. I would normally create a full view and pass this back to the browser on a full page request, unless there were specific areas that I did not want to populate straight away and would then use DOM page load events to call the server to load other areas using AJAX.

Also, when it came to partial page refreshing, I would call an MVC action method which would return the HTML fragment which I could then use to populate parts of the page. This would be for areas that I did not want to slow down initial page load, or areas that fitted better with AJAX calls. One example would be for table paging. If you want to move on to the next page, I would prefer it if an AJAX call got that info rather than using a full page refresh. But the AJAX call would still return an HTML fragment.

My question is. Are my thoughts on this archaic because I come from a .net background rather than a pure front end background?

An intelligent front end developer that I work with, prefers to do more or less nothing in the MVC views, and would rather do everything on the front end. Right down to web API calls populating the page. So that rather than calling an MVC action method, which returns HTML, he would prefer to return a standard object and use javascript to create all the elements of the page.

The front end developer way means that any benefits that I normally get with MVC model validation, including client side validation, would be gone. It also means that any benefits that I get with creating the views, with strongly typed html templates etc would be gone.

I believe this would mean I would need to write the same validation for front end and back end validation. The javascript would also need to have lots of methods for creating all the different parts of the DOM. For example, when adding a new row to a table, I would normally use the MVC partial view for creating the row, and then return this as part of the AJAX call, which then gets injected into the table. By using a pure front end way, the javascript would would take in an object (for, say, a product) for the row from the api call, and then create a row from that object. Creating each individual part of the table row.

The website in question will have lots of different areas, from administration, forms, product searching etc. A website that I don't think requires to be architected in a single page application way.

What are everyone's thoughts on this?

I am interested to hear from front end devs and back end devs.

答:
I have a love-hate relationship with front end heavy applications.

On one hand, I love writing JavaScript and I love the browser as an execution environment.

On the other hand, both feel like a Formula 1 race car with holes in the engine. It really boils down to this: Can you prevent duplication of business logic between C# and JavaScript? If so, use whatever method for generating the view you deem worthy. If you are duplicating business logic in two languages, you may have a front end developer who just wants to write JavaScript, and doesn't quite see the big picture.

As for technical differences:

Rendering a partial and delivering it to the client:

Easy and fast to implement

Prevents backend business logic from being duplicated on the front end

Can result in a much larger HTTP payload to the browser. Not a bad thing on a desktop with a high bandwidth connection. Very bad on a weak mobile phone whilst you are sitting on a rush hour train speeding down the track at 60mph and 1,000 other mobile phones are simultaneously disconnecting from one cell tower and trying to reconnect to the next cell tower.

Delivering JSON and rendering a client side template:

Can result in a smaller HTTP payload than HTML, which can make the application seem more responsive over unreliable or slow network connections

Many JavaScript templating languages are fully featured, meaning we don't need a backend just to generate some HTML

Sometimes I think the newer JavaScript frameworks are throwing the baby out with the bath water --- man I hope I'm not becoming a grumpy curmudgeon programmer...


问:
Looping Exhaustive Test Cases - A Good Practice?
Sometimes we have code like this:

```<code>private static final List<Goat> INEDIBLE_GOATS = [GOAT_A, GOAT_B, GOAT_C]

void eatGoat(Goat goat) {
   if(INEDIBLE_GOATS.contains(goat)) {
       throw new CantEatGoatException();
   }
   ...
}
</code>```

Should it best tested (along with whatever tests for the actual eating) as:

```<code>for(Goat goat: INEDIBLE_GOATS) {
   // forgive abuse of syntax
   assertThrows(CantEatGoatException, eatGoat(goat));
}
</code>```

Or more like?

```<code>assertThrows(CantEatGoatException, eatGoat(GOAT_A));
</code>```

Should tests verify each and every sort of inedible goat? Or should they test a representative goat from the list and trust that it works for the other goats?

答:
Your question is an important one. To restate more generically: should you test all possible inputs or just selected ones? As @cbojar points out, the former is typically either (a) not practical or (b) not useful.

The question then becomes how to whittle the list of all possible test inputs into a set of optimal test inputs. To do this, divide the set of all possible inputs into groups based on expected outcomes. Any input from one group should yield equivalent (though not identical) results. Such groups are called equivalence classes. and this process of identifying such classes is equivalence partitioning.

As a simple example, to test a square root function that takes an integer input, a good starting point would be these equivalence classes:

```<code> 1   -- all positive integers
-1   -- all negative integers
 0   -- zero
</code>```

You might refine that list further:

```<code> 1   -- all positive integers that are not perfect squares
 4   -- all positive integers that are perfect squares
-1   -- all negative integers
 0   -- zero
</code>```

And if you are a real stickler, you might add maxint and minint for your integer type. But with any of these you have infinitely less test cases than the set of all possible inputs :-) -- a pretty good savings!

(For more, see my answer to a related question, What should you test with unit tests?)

Body:
Your question is an important one. To restate more generically: should you test all possible inputs or just selected ones? As @cbojar points out, the former is typically either (a) not practical or (b) not useful.

The question then becomes how to whittle the list of all possible test inputs into a set of optimal test inputs. To do this, divide the set of all possible inputs into groups based on expected outcomes. Any input from one group should yield equivalent (though not identical) results. Such groups are called equivalence classes. and this process of identifying such classes is equivalence partitioning.

As a simple example, to test a square root function that takes an integer input, a good starting point would be these equivalence classes:

 1   -- all positive integers
-1   -- all negative integers
 0   -- zero

You might refine that list further:

 1   -- all positive integers that are not perfect squares
 4   -- all positive integers that are perfect squares
-1   -- all negative integers
 0   -- zero

And if you are a real stickler, you might add maxint and minint for your integer type. But with any of these you have infinitely less test cases than the set of all possible inputs :-) -- a pretty good savings!

(For more, see my answer to a related question, What should you test with unit tests?)


问:
What does it mean that file IO binary flag is only relevant on Windows
I was reading a question and one of the comments mentioned that "The binary flag is only relevant on Windows". Given the context of the question and answer, I interpret this statement as on non-windows machines, we don't need to specify text or binary mode when doing file IO

The context of the question is to read all bytes of a file into a string (presumably preserving bytes). It seems very relevant to me whether I'm reading the data as text or bytes, since reading text involves dealing with encoding. If I'm reading a UTF-16 file, for example, what I get in text mode is much different from what I get in binary mode.

Assuming my interpretation of the statement is correct, is it unnecessary to specify whether a file should be opened in text or binary mode on non-windows machines? That is, all files are read in binary mode by default.

Otherwise, what could the statement be referring to? (the comment received a number of upvotes so presumably this is not just one person's opinion)

答:
The "binary" flag exists for the fopen() function call in the C standard library. On my nearest Linux system, the documentation states:

The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above.  This is strictly for compatibility  with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux.  (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)

The C standard library functions do not deal with text encodings. Data read from or written to files are bytes. On some systems such as Windows, the line-endings are conventionally \r\n but on POSIX systems, the line-endings are just \n. This is one of the things that the "binary" flag controls (another thing may be the details of end-of-file handling).

However, in Ruby, the IO::new function treats the "b" flag as follows (emphasis mine):

"b"  Binary file mode

       Suppresses EOL <-> CRLF conversion on Windows. And
       sets external encoding to ASCII-8BIT unless explicitly
       specified.

This means that additionally, Ruby sets the character encoding depending on whether the "b" flag is included. This means that its use is not specific to Windows, and can affect the behaviour of your program even on a POSIX system.


问:
What's so bad about creative coding?
I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately.

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection.  My goal is to write respectable (and therefore maintainable and functioning) code, by improving my skills.  Yet, I code creatively.

Let me explain what I mean by "coding creatively":

My first steps in a project are often to sit down and bash out some code.  For bigger things, I plan a bit out here and there, but mostly I just dive in.

I don't diagram any of my classes, unless I'm working with others who are creating other pieces in the project.  Even then, it certainly isn't the first thing I do.  I don't typically work on huge projects, and I don't find the visual very useful.

The first round of code I write will get rewritten many, many times as I test, simplify, redo, and transform the original hack into something reusable, logical, and efficient.

During this process, I am always cleaning.  I remove unused code, and comment anything that isn't obvious.  I test constantly.

My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

I know that most of the griping about bad code is that someone got stuck with a former employee's mess, and it cost a lot of time and money to fix.  That I understand.  What I don't understand is how my process is wrong, given that the end result is similar to what you would get with planning everything from the start.  (Or at least, that's what I have found.)

My anxiety over the issue has been so bad lately that I have stopped coding until I know everything there is about every method for solving the particular problem I am working on.  In other words, I have mostly stopped coding altogether.

I sincerely appreciate your input, no matter what your opinions are on the issue.

Edit:  Thank you all for your answers.  I have learned something from each of them.  You have all been most helpful.

答:
There is nothing wrong with your approach as a creative art form. If you are developing for personal benefit, and what you are doing works for you, and that you find enjoyable are probably just as important as the final outcome as the product itself.

In a professional work environment, if your project time scales are short, perhaps around 2 - 3 weeks or less, then your approach is called rapid prototyping and is quite appropriate to the tasks ahead.

However on longer projects, even ones when you are working on your own, such an approach is probably an expensive luxury for your employer.  Spending a few days of the project budget on upfront architecture design and then testing the architecture against what if management decide to change the spec by... is normally time well spent and will develop your skills to becoming a more valuable programmer/architect further on in your career.

Title: What's so bad about creative coding?


答:
What are you trying to optimise for?

Code quality: This is your chance to figure out how this bug escaped from the lab in the first place. Depending on how much time you want to spend on this, you could look at performing a code review with the whole team, or root cause analysis.

Not just looking at the code but everything around your development and test process

Why didn't this get found in testing? You are using test first, right? Do you consider all the quadrants?

Why didn't you train your team members in this area?

Do you have broken processes that caused this defect or allowed it to be created and not found?

Team knowledge / learning: Pair an expert from the team that created the bug (expert in this area, not just anyone from that team) with someone else who does not know that area, their knowledge will spread and you will have more experts in this area.

Happiness of team: Try to find the solution everyone, or most people, are happy with, discuss the issue in an open and non-judgemental way with the teams and come to a consensus.

Speed: Assign the bug to whoever has the bandwidth to work on it right now. This can be a tough one to optimise for, who will get it done the fastest, who can start working on it now, is it better to get started or to wait for someone else. Beware this one, even when optimised efficiently, aside from possibly having a negative effect on all the other parameters mentioned here, it can lead to technical debt piling up even more. Remember: more haste, less speed.

Title: Fixing bugs generated by another team

Body:
I'm facing the following situation:

There are 2 different teams working on the same project using Scrum, and every now and then, bugs related to user stories developed by team "A" are being assigned to team "B".  We're used to fixing bugs made by other people when they belong to the same team, but things get a bit more complicated when different teams are involved. Some of the developers don't like working this way and say that the bugs must be fixed by the ones who made them, and this is causing some conflicts between the teams.

While reading some of the similar questions I've found some interesting ones (Is fixing bugs made by other people a good approach? and also Parallel teams and scrum/agile), but they are not about the same situation, or at least I don't see them that way.

During our discussions here we got 2 possible approaches: Leave the situation as is, or determine that the bugs must be assigned to the team that developed the feature. Do you guys have any suggestions?


问:
Does C++ compiler remove/optimize useless parentheses?
Will the code

```<code>int a = ((1 + 2) + 3); // Easy to read
</code>```

run slower than

```<code>int a = 1 + 2 + 3; // (Barely) Not quite so easy to read
</code>```

or are modern compilers clever enough to remove/optimize "useless" parentheses.

It might seems like a very tiny optimization concern, but choosing C++ over C#/Java/... is all about optimizations (IMHO).

答:
No, but yes, but maybe, but maybe the other way, but no.

As people have already pointed out, (assuming a language where addition is left-associative, such as C, C++, C# or Java) the expression ((1 + 2) + 3) is exactly equivalent to 1 + 2 + 3. They're different ways of writing something in the source code, that would have zero effect on the resulting machine code or byte code.

Either way the result is going to be an instruction to e.g. add two registers and then add a third, or take two values from a stack, add it, push it back, then take it and another and add them, or add three registers in a single operation, or some other way to sum three numbers depending on what is most sensible at the next level (the machine code or byte code). In the case of byte code, that in turn will likely undergo a similar re-structuring in that e.g. the IL equivalent of this (which would be a series of loads to a stack, and popping pairs to add and then push back the result) would not result in a direct copy of that logic at the machine code level, but something more sensible for the machine in question.

But there is something more to your question.

In the case of any sane C, C++, Java, or C# compiler, I would expect the result of both of the statements you give to have the exact same results as:

```<code>int a = 6;
</code>```

Why should the resultant code waste time doing math on literals? No changes to the state of the program will stop the result of 1 + 2 + 3 being 6, so that's what should go in the code being executed. Indeed, maybe not even that (depending on what you do with that 6, maybe we can throw the whole thing away; and even C# with it's philosophy of "don't optimise heavily, since the jitter will optimise this anyway" will either produce the equivalent of int a = 6 or just throw the whole thing away as unnecessary).

This though leads us to a possible extension of your question though. Consider the following:

```<code>int a = (b - 2) / 2;
/* or */
int a = (b / 2)--;
</code>```

and

```<code>int c;
if(d < 100)
  c = 0;
else
  c = d * 31;
/* or */
int c = d < 100 ? 0 : d * 32 - d
/* or */
int c = d < 100 && d * 32 - d;
/* or */
int c = (d < 100) * (d * 32 - d);
</code>```

(Note, this last two examples are not valid C#, while everything else here is, and they are valid in C, C++ and Java.)

Here again we've exactly equivalent code in terms of output. As they aren't constant expressions, they won't be calculated at compile time. It's possible that one form is faster than another. Which is faster? That would depend on the processor and perhaps on some rather arbitrary differences in state (particularly since if one is faster, it's not likely to be a lot faster).

And they aren't entirely unrelated to your question, as they are mostly about differences in the order in which something is conceptually done.

In each of them, there's a reason to suspect that one may be faster than the other. Single decrements may have a specialised instruction, so (b / 2)-- could indeed be faster than (b - 2) / 2. d * 32 could perhaps be produced faster by turning it into d << 5 so making d * 32 - d faster than d * 31. The differences between the last two are particularly interesting; one allows some processing to be skipped in some cases, but the other avoids the possibility of branch mis-prediction.

So, this leaves us with two questions: 1. Is one actually faster than the other? 2. Will a compiler convert the slower into the faster?

And the answer is 1. It depends. 2. Maybe.

Or to expand, it depends because it depends on the processor in question. Certainly there have existed processors where the naïve machine-code equivalent of one would be faster than the naïve machine-code equivalent of the other. Over the course of the history of electronic computing, there hasn't been one that was always the faster, either (the branch mis-prediction element in particular wasn't relevant to many when non-pipelined CPUs were more common).

And maybe, because there are a bunch of different optimisations that compilers (and jitters, and script-engines) will do, and while some may be mandated in certain cases, we'll generally be able to find some pieces of logically equivalent code that even the most naïve compiler has exactly the same results and some pieces of logically equivalent code where even the most sophisticated produces faster code for one than for the other (even if we have to write something totally pathological just to prove our point).

It might seems like a very tiny optimization concern,

No. Even with more complicated differences than those I give here, it seems like an absolutely minute concern that has nothing to do with optimisation. If anything, it's a matter of pessimisation since you suspect the harder to read ((1 + 2) + 3 could be slower than the easier to read 1 + 2 + 3.

but choosing C++ over C#/Java/... is all about optimizations (IMHO).

If that's really what choosing C++ over C# or Java was "all about" I'd say people should burn their copy of Stroustrup and ISO/IEC 14882 and free up the space of their C++ compiler to leave room for some more MP3s or something.

These languages have different advantages over each other.

One of them is that C++ is still generally faster and lighter on memory use. Yeah, there are examples where C# and/or Java are faster and/or have better application-lifetime use of memory, and these are becoming more common as the technologies involved improve, but we can still expect the average program written in C++ to be a smaller executable that does its job faster and using less memory than the equivalent in either of those two languages.

This isn't optimisation.

Optimisation is sometimes used to mean "making things go faster". It's understandable, because often when we really are talking about "optimisation" we are indeed talking about making things go faster, and so one has become a shorthand for the other and I'll admit I misuse the word that way myself.

The correct word for "making things go faster" is not optimisation. The correct word here is improvement. If you make a change to a program and the sole meaningful difference is that it is now faster, it isn't optimised in any way, it's just better.

Optimisation is when we make an improvement in regards to a particular aspect and/or particular case. Common examples are:

It's now faster for one use case, but slower for another.

It's now faster, but uses more memory.

It's now lighter on memory, but slower.

It's now faster, but harder to maintain.

It's now easier to maintain, but slower.

Such cases would be justified if, e.g.:

The faster use case is more common or more severely hampered to begin with.

The program was unacceptably slow, and we've lots of RAM free.

The program was grinding to a halt because it used so much RAM it spent more time swapping than executing its super-fast processing.

The program was unacceptably slow, and the harder to understand code is well-documented and relatively stable.

The program is still acceptably fast, and the more understandable code-base is cheaper to maintain and allows for other improvements to be more readily made.

But, such cases would also not be justified in other scenarios: The code hasn't been made better by an absolute infallible measure of quality, it's been made better in a particular regard that makes it more suitable for a particular use; optimised.

And choice of language does have an effect here, because speed, memory use, and readability can all be affected by it, but so can compatibility with other systems, availability of libraries, availability of runtimes, maturity of those runtimes on a given operating system (for my sins I somehow ended up having Linux and Android as my favourite OSs and C# as my favourite language, and while Mono is great, but I still come up against this one quite a bit).

Saying "choosing C++ over C#/Java/... is all about optimizations" only makes sense if you think C++ really sucks, because optimisation is about "better despite..." not "better". If you think C++ is better despite itself, then the last thing you need is to worry about such minute possible micro-opts. Indeed, you're probably better off abandoning it at all; happy hackers are a quality to optimise for too!

If however, you're inclined to say "I love C++, and one of the things I love about it is squeezing out extra cycles", then that's a different matter. It's still a case that micro-opts are only worth it if they can be a reflexive habit (that is, the way you tend to code naturally will be the faster more often than it is the slower). Otherwise they're not even premature optimisation, they're premature pessimisation that just make things worse.

Body:
No, but yes, but maybe, but maybe the other way, but no.

As people have already pointed out, (assuming a language where addition is left-associative, such as C, C++, C# or Java) the expression ((1 + 2) + 3) is exactly equivalent to 1 + 2 + 3. They're different ways of writing something in the source code, that would have zero effect on the resulting machine code or byte code.

Either way the result is going to be an instruction to e.g. add two registers and then add a third, or take two values from a stack, add it, push it back, then take it and another and add them, or add three registers in a single operation, or some other way to sum three numbers depending on what is most sensible at the next level (the machine code or byte code). In the case of byte code, that in turn will likely undergo a similar re-structuring in that e.g. the IL equivalent of this (which would be a series of loads to a stack, and popping pairs to add and then push back the result) would not result in a direct copy of that logic at the machine code level, but something more sensible for the machine in question.

But there is something more to your question.

In the case of any sane C, C++, Java, or C# compiler, I would expect the result of both of the statements you give to have the exact same results as:

int a = 6;

Why should the resultant code waste time doing math on literals? No changes to the state of the program will stop the result of 1 + 2 + 3 being 6, so that's what should go in the code being executed. Indeed, maybe not even that (depending on what you do with that 6, maybe we can throw the whole thing away; and even C# with it's philosophy of "don't optimise heavily, since the jitter will optimise this anyway" will either produce the equivalent of int a = 6 or just throw the whole thing away as unnecessary).

This though leads us to a possible extension of your question though. Consider the following:

int a = (b - 2) / 2;
/* or */
int a = (b / 2)--;

and

int c;
if(d < 100)
  c = 0;
else
  c = d * 31;
/* or */
int c = d < 100 ? 0 : d * 32 - d
/* or */
int c = d < 100 && d * 32 - d;
/* or */
int c = (d < 100) * (d * 32 - d);

(Note, this last two examples are not valid C#, while everything else here is, and they are valid in C, C++ and Java.)

Here again we've exactly equivalent code in terms of output. As they aren't constant expressions, they won't be calculated at compile time. It's possible that one form is faster than another. Which is faster? That would depend on the processor and perhaps on some rather arbitrary differences in state (particularly since if one is faster, it's not likely to be a lot faster).

And they aren't entirely unrelated to your question, as they are mostly about differences in the order in which something is conceptually done.

In each of them, there's a reason to suspect that one may be faster than the other. Single decrements may have a specialised instruction, so (b / 2)-- could indeed be faster than (b - 2) / 2. d * 32 could perhaps be produced faster by turning it into d << 5 so making d * 32 - d faster than d * 31. The differences between the last two are particularly interesting; one allows some processing to be skipped in some cases, but the other avoids the possibility of branch mis-prediction.

So, this leaves us with two questions: 1. Is one actually faster than the other? 2. Will a compiler convert the slower into the faster?

And the answer is 1. It depends. 2. Maybe.

Or to expand, it depends because it depends on the processor in question. Certainly there have existed processors where the naïve machine-code equivalent of one would be faster than the naïve machine-code equivalent of the other. Over the course of the history of electronic computing, there hasn't been one that was always the faster, either (the branch mis-prediction element in particular wasn't relevant to many when non-pipelined CPUs were more common).

And maybe, because there are a bunch of different optimisations that compilers (and jitters, and script-engines) will do, and while some may be mandated in certain cases, we'll generally be able to find some pieces of logically equivalent code that even the most naïve compiler has exactly the same results and some pieces of logically equivalent code where even the most sophisticated produces faster code for one than for the other (even if we have to write something totally pathological just to prove our point).

It might seems like a very tiny optimization concern,

No. Even with more complicated differences than those I give here, it seems like an absolutely minute concern that has nothing to do with optimisation. If anything, it's a matter of pessimisation since you suspect the harder to read ((1 + 2) + 3 could be slower than the easier to read 1 + 2 + 3.

but choosing C++ over C#/Java/... is all about optimizations (IMHO).

If that's really what choosing C++ over C# or Java was "all about" I'd say people should burn their copy of Stroustrup and ISO/IEC 14882 and free up the space of their C++ compiler to leave room for some more MP3s or something.

These languages have different advantages over each other.

One of them is that C++ is still generally faster and lighter on memory use. Yeah, there are examples where C# and/or Java are faster and/or have better application-lifetime use of memory, and these are becoming more common as the technologies involved improve, but we can still expect the average program written in C++ to be a smaller executable that does its job faster and using less memory than the equivalent in either of those two languages.

This isn't optimisation.

Optimisation is sometimes used to mean "making things go faster". It's understandable, because often when we really are talking about "optimisation" we are indeed talking about making things go faster, and so one has become a shorthand for the other and I'll admit I misuse the word that way myself.

The correct word for "making things go faster" is not optimisation. The correct word here is improvement. If you make a change to a program and the sole meaningful difference is that it is now faster, it isn't optimised in any way, it's just better.

Optimisation is when we make an improvement in regards to a particular aspect and/or particular case. Common examples are:

It's now faster for one use case, but slower for another.

It's now faster, but uses more memory.

It's now lighter on memory, but slower.

It's now faster, but harder to maintain.

It's now easier to maintain, but slower.

Such cases would be justified if, e.g.:

The faster use case is more common or more severely hampered to begin with.

The program was unacceptably slow, and we've lots of RAM free.

The program was grinding to a halt because it used so much RAM it spent more time swapping than executing its super-fast processing.

The program was unacceptably slow, and the harder to understand code is well-documented and relatively stable.

The program is still acceptably fast, and the more understandable code-base is cheaper to maintain and allows for other improvements to be more readily made.

But, such cases would also not be justified in other scenarios: The code hasn't been made better by an absolute infallible measure of quality, it's been made better in a particular regard that makes it more suitable for a particular use; optimised.

And choice of language does have an effect here, because speed, memory use, and readability can all be affected by it, but so can compatibility with other systems, availability of libraries, availability of runtimes, maturity of those runtimes on a given operating system (for my sins I somehow ended up having Linux and Android as my favourite OSs and C# as my favourite language, and while Mono is great, but I still come up against this one quite a bit).

Saying "choosing C++ over C#/Java/... is all about optimizations" only makes sense if you think C++ really sucks, because optimisation is about "better despite..." not "better". If you think C++ is better despite itself, then the last thing you need is to worry about such minute possible micro-opts. Indeed, you're probably better off abandoning it at all; happy hackers are a quality to optimise for too!

If however, you're inclined to say "I love C++, and one of the things I love about it is squeezing out extra cycles", then that's a different matter. It's still a case that micro-opts are only worth it if they can be a reflexive habit (that is, the way you tend to code naturally will be the faster more often than it is the slower). Otherwise they're not even premature optimisation, they're premature pessimisation that just make things worse.


答:
Not necessarily. As you mentioned, whitespace is biased by their "natural" programming language. However, I've also noticed some developers seem to have some kind of strange aversion to scrolling down to read more code.

I work with a developer who is not a cargo cult programmer, but does use far less whitespace than I find readable (or, if you ask him, would say that I use excessive white space). He codes using vim, often with several windows open for reference as he's working. As a result, he tends to prefer smaller windows, but still wants to be able to see more than a few lines of code in the window. The result is a bare minimum of whitespace in anything he's written.

At my last job, code ran on for as long as it took to type everything, with no line-wrapping whatsoever. Instead, you'd have to constantly scroll to the right to see what all was going on. I'm not sure why, but in every instance the people responsible weren't cargo cult programmers. Personally, I think it speaks more to a lack of style guidelines than it does anything else.


答:
Brad, you're not alone.  I know very good programmers who work in exactly the same way as you describe. :)

If you clean up your code and know how to make it efficient and readable, then you certainly have developed a sense of how to write clean and efficient code upfront too.

Furthermore, nothing can fully be planned in advance, and the shortest route to discovering subtleties is often to run the code and understand details that were overlooked.

I think that you're doing perfectly fine, and that the programming style that you describe is perfectly valid.

Title: What's so bad about creative coding?

Body:
I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately.

The community of folks here and on Stack Overflow seem to reject any whiff of imperfection.  My goal is to write respectable (and therefore maintainable and functioning) code, by improving my skills.  Yet, I code creatively.

Let me explain what I mean by "coding creatively":

My first steps in a project are often to sit down and bash out some code.  For bigger things, I plan a bit out here and there, but mostly I just dive in.

I don't diagram any of my classes, unless I'm working with others who are creating other pieces in the project.  Even then, it certainly isn't the first thing I do.  I don't typically work on huge projects, and I don't find the visual very useful.

The first round of code I write will get rewritten many, many times as I test, simplify, redo, and transform the original hack into something reusable, logical, and efficient.

During this process, I am always cleaning.  I remove unused code, and comment anything that isn't obvious.  I test constantly.

My process seems to go against the grain of what is acceptable in the professional developer community, and I would like to understand why.

I know that most of the griping about bad code is that someone got stuck with a former employee's mess, and it cost a lot of time and money to fix.  That I understand.  What I don't understand is how my process is wrong, given that the end result is similar to what you would get with planning everything from the start.  (Or at least, that's what I have found.)

My anxiety over the issue has been so bad lately that I have stopped coding until I know everything there is about every method for solving the particular problem I am working on.  In other words, I have mostly stopped coding altogether.

I sincerely appreciate your input, no matter what your opinions are on the issue.

Edit:  Thank you all for your answers.  I have learned something from each of them.  You have all been most helpful.


答:
I would not view lack of vertical whitespace as any kind of indication.

I would view excessive (in my opinion) vertical whitespace as an indication that the programmer was not as experienced as he might have thought he was.

Research going back decades demonstrates beyond reasonable doubt that programmer comprehension is limited by what he can see at one glance, without scrolling or turning pages.  Once scrolling, or page changing, becomes necessary, programmer comprehension drops dramatically.

This is also why larger monitors are so strongly desirable.

Whitespace is best used very sparingly.  If you don't need it, don't throw it in.  If you do need it, consider whether reworking/refactoring might not be a better option.


问:
How to effectively cooperate in a team having mixed background/mindset regarding OOP?
I've been recently assigned for a new high-performance C++ project (finance) together with 3 other guys who, like, me, refer to themselves as "primarily C/C++ programmers", meaning, all of us have also done Java & other stuff, we all have comparable experience (8 to 10 years) and have successfully collaborated for the making of other projects (not C/C++).

I soon found out we have such different mindsets when it comes to our "mother programming tongue" that it risks not only the good delivery of the project but also the general well-being of the team/office. Specifically:

They come from an electrical engineering/automation/polytechnic type of background, so their reasoning is intimately related to how hardware works, how bytes move around, processor workings, instruction caching, generally everything at the lower layers. They did embedded programming, ARM programming (I barely know what those are). I soon found out their practical experience is with mostly C, not C++. They think procedurally, not OOP.

I, on the other hand, have trained myself to think in a more abstract way, to apply principles such as encapsulation, low coupling/high cohesion for creating reusable, modular software. My speciality is the C++ programming language, with an accent on language constructs that help you get both fast and reusable, generic code. I think design patterns, idioms, concepts. Throughout 9 years of developing software I consistently witnessed how poor maintainability of software systems is by far the #1 burden of teams. I generously document my code, write careful interfaces. I embrace template meta-programming as a way to obtain fast and reusable products. I embrace the new C++11 standard features.

Where I see reusability and loose coupling, they see "complication". They want to "see it all there". They want to see char*, not some buffer class in interface methods. At one point one even said "I don't care how simple your interfaces are if your implementation looks complicated". The trouble is, we really are trying to transition from a monolithic style of systems to a reusable one - we are writing a library. Yet they don't wish to see their C-style structs being polluted with templated methods, typedefs and c-tors, even if neither makes their structs non-POD. They also don't wish to see static_assert(std::is_pod<...>). They love memcpy and pointers and generally stay away from references. They tend to think typedefs are somehow evil.

I really tried to make them see an abstraction for what it is. It is code together with data it operates on. By necessity, a library needs to define some interfaces for the user to be able to plug it into a larger product. They tend to see these interfaces as ways in which my code requires their code behave/look as I wish and doesn't allow them to do things their way, but without actually telling me a specific functionality they can't obtain.

Make no mistake, I'm no ignorant when it comes to performance. I know about cache lines, branch prediction, the overhead of method virtualization, heap allocation, hash lookups. I'm good with complexity of algorithms (though that doesn't matter so much here), data structures, inlining and some other compiler optimizations such as RVO. I believe with a modern compiler a reusable, layered OOP C++ product can get within 10% of the performance of a C-only monolithic product, when carefully written and optimized.

I honestly believed we would complement each other in our thinking.

What are your thoughts? Please don't be too harsh, we need to make this work.

答:
Ok, I'm going to take a crack at this since nobody else has yet.

My experience is perhaps somewhat similar. I transferred from the software department to the embedded software department at my workplace a little over a year ago, and I have definitely heard echoes of the sentiments you're expressing here.

Here are a few observations I made that are along the lines of what you've listed here. These represent viewpoints of the different groups.

Embedded programmers love the stack and RAII. Why use smart pointers, etc. if you don't need them. The heap is evil. They're actually kind of right about this.

Software programmers tend to love interfaces because they see the power that abstraction brings. Sometimes hiding information is better. Dependency inversion improves testability.

Embedded programmers often do better functional testing, software programmers do better unit testing.

My general takeaway? The embedded/EE background often times comes with lesser ability to architect (especially large-scale systems), and the software background tends to be more prickly about things that don't matter and more of a focus on theoretically improving performance rather than measuring and improving it. Your mileage may vary.

From a team-building perspective, I've found that building respect for the mutual viewpoints is crucial. It's been my goal and I think it's gone quite some ways.

From a C++ usage perspective, I'd like to make a few, perhaps painful, suggestions. Please take all of these from the perspective of things I noticed different between software and embedded software approaches, not as mere flame-worthy editorial on style.

While performance is important, it is unlikely this is on an embedded device. That means that if you're dealing with a modern computer, many of the typical embedded tricks don't quite apply. That said, some still do and it would be good to talk with the team to see which ones they think do. Knowing these upfront means you can architect with them in mind!

There's a difference between shiny things like metaprogramming and simply having reusable interfaces. Frankly, I find that from a reusability standpoint, you will get the most out of having good sane interfaces. This is worth fighting for... but...

While I'm a fan of some template metaprogramming, I tend to find the statement that you "embrace" it as a possibly suspect indicator... Do you really need to push metaprogramming? Or possibly traits? Or possibly lambdas? Or hardly any C++ 11 features? I understand that these are some of your favorite tools, but are they really worth picking a fight over? I'm frankly not sold that these increase resuability all that much. They do increase programmer productivity and other things, but this seems like a place where some compromise may be good.

There's a place for plain old data and a place for classes that are not blittable. Generally speaking, stick with some simple convention like structs vs. classes and call it good: do you really need is_pod if you do something like this?

I would argue references are worth pushing, especially if you're doing a lot of stack-based programming (which you are, right? RAII and all?). In the past, I too thought references were evil because I didn't properly understand their limitations and correct usage. Just show them you don't have to worry about NULL pointers for a good chunk of your code and maybe they'll agree.

You may want to talk about threading upfront. Embedded programs often do lots of work on a single thread with a scheduler, whereas higher level software opts towards many threads. Arguably the scheduler way is faster in certain respects (especially when combined with multiple threads), but the reason I bring it up is that how your work slices up may drastically change depending on which way you go. Scheduled work tends to happen in horizontal slices, threaded work in vertical ones. Also, I have often seen a bit weaker approach to locking on the embedded side, due to the often singly-threaded nature; this may be worth double-checking too.

Templates can often be great (hooray for the STL!), but there are definitely tricky syntax things here - I'm looking at you, typename keyword. Also, make sure your .h/.hpp etc. convention is stated clearly. I've seen mixed opinions from embedded programmers about templates - usually more about code size and complexity rather than speed, though. Try not to write code that your teammates won't touch.

I'm torn about typedefs. On one hand, they can help abstract away a type and make some things easier. But I've seen code with lots of typedefs in it and it was quite hard to pick up and read. The four places where I've seem them used to good effect are 1) publicly scoped for abstracting hardware-related types, 2) privately scoped for types of header fields so you can do sizeof and still be ok, 3) privately scoped for iterators, 4) publicly scoped for function pointers. Use cases beyond these have often made me start to see cross-eyed if not done sparingly.

Of course, you put two programmers in a room and you get three opinions. I realize that. But on the boundary between embedded software and software, these are things I've noticed. I hope that they are helpful. (But I've preemptively put on the heat-retardant suit, just in case.)

And one last thing. Along the lines of building up mutual respect and admiration, it may not hurt to meet them halfway and perhaps look at things like Template based register access and start a friendly discussion about something like this.


问:
How do you get relevant and useful information out of a client in regards to a job?
A brief background on this specific question:

After meeting with a client and hearing all of their requests,
  requirements, and other comments about a specific software job,
  planning out the software functionality, design, and basic user experience,
  the client comes back with a comment regarding, "That is not what we
  are looking for. You can't do what we want to do."

Now, I understand the concept that not everyone understands tech, and that some people are more visual than others and may need to see things before they can be sure about something.

I also understand the process of revisions and other modifications to meet specific functionality demands or requirements that may only come up after you start putting things together. I mean, if everyone got it right in version 1.0, imagine how great a world this would be!

Given: There is no magic formula for a guaranteed success rate when a lot of the work is artistic in the sense that the same set of directions can be interpreted differently by different people.

I'm aware that asking the right questions is important, and I have done some research about what questions others are asking in similar jobs. I also have previous experience with clients (this isn't my first job), and through it all, I have developed my own little system for getting this information-- which has had a 99% success rate up to this point. Usually if I don't get it right the first time, it's fixed during the revision and modification process. I know I'm not perfect, but I've never really had a client flat out refuse what they asked for...

So how do you get relevant and useful information out of a client in regards to job requirements and specifics?

答:
Agile.

If you cannot agree a full set of specification up-front (and you should be able to at least get agreement on the intended product even if many details are missed) then you have to try the "other way", and build a continually improving prototype that the customer can see, verify and update as they realise what their needs were all along.

Asking how to ask a client what they want isn't really an answerable question. You'd need to find out why your meetings failed so badly. (I would guess that they have different teams working on this internally, and although one team agrees, the other may have different requirements).


问:
What are some effective ways of making scrum more dynamic earlier in a sprint?
My team does 2-week sprints, and the trend we've identified (which we want to move away from) is that our daily standup scrums are relatively straightforward early in the sprint, but then transform into a more frantic scramble toward the end.

The first week developers are heads down in coding, analysts are developing test plans and answering developer questions, and testers are refining existing tests and identifying areas to test (but not necessarily testing just yet since there isn't as much out there actually ready to test). Blockers and scope creep tend to emerge into the second week, and then as we see how close we're getting to the end, we force ourselves to make tough choices and be more communicative.

How can we "spread the wealth" and increase the overall "tempo" (I guess?) of our scrums from the beginning of the sprint to the end?

答:
You seem to have a number of dysfunctions but here are two that I'd look to address early:

Your original question gives me the impression that you're working as a group of individuals. The analyst does their bit, passes it to the developer who does their bit before passing it to a tester ... and so on. Scrum needs cross-functional individuals, not silo'd specialists.

Scrum teams focus ruthlessly on moving a single product backlog item to done. It doesn't read like this is happening with your team. The late announcement of blockers and emerging work gives me the impression that you're running a mini-waterfall where all the testing is being left to the end.

So, based on my assumptions, here's my advice:

Encourage cross-functional skilling in the scrum team. There's no reason why a tester can't help with analysis or a software developer can't help with testing, etc. The team does the work that's in front of them and needs doing.

Reduce Work In Progress (WIP). Focus on moving one product backlog item to 'done' before starting the next one. Yes, sometimes that's silly because you have people stepping on each other's toes so try this simple guidance: The amount of product backlog items being worked on simultaneously must be no more than half the size of the team.


问:
Lexer/Parser for multidimensional Languages
How does Lexer/Parser work in a 2D programming language like Funciton in order to transform such an unusual source-code to the correct AST?

答:
It is just dataflow: only the visual representation displayed to the user is 2D. Internally, this is a graph structure with a list of nodes and a list of vertices.

Look at VHDL, Verilog or any hardware description language for text-based dataflow languages.

Look at Excel or any spreadsheet for another representation of dataflow language.

The main difference is not in parsing, it is in runtime.

EDIT

The Funciton language actually is very specific in that source code is sort of ASCII art of boxes and edges. The first commit of the interpreter gives the general algorithm used for parsing that ASCII art:

Find boxes and their outgoing edges

Start finding a box here if this is a top-left corner of a box

Find width of box by walking along top edge

Find height of box by walking along left edge

Verify the bottom edge

Verify the right edge

...

Parse the connections between nodes and discover all the loose ends ...