答:
I would consider it as a bad habit of coding. Sometimes it works perfectly fine and you will have no problem in compiling and running the code. At other times it may cause serious bugs and you will end up spending hours in fixing that bug.

It is always recommended to modularize your code. If you have to put a while loop in else part put it in a block so that others, when working on your code can easily understand the logic.

```<code>if ( blah )
{
    ...
}
else
{
    while ( !bloop() )
    {
        bar();
    }
}
</code>```

It's a good practice to put code in blocks. It makes it simpler and easier to understand and debug as well.

Body:
I would consider it as a bad habit of coding. Sometimes it works perfectly fine and you will have no problem in compiling and running the code. At other times it may cause serious bugs and you will end up spending hours in fixing that bug.

It is always recommended to modularize your code. If you have to put a while loop in else part put it in a block so that others, when working on your code can easily understand the logic.

if ( blah )
{
    ...
}
else
{
    while ( !bloop() )
    {
        bar();
    }
}

It's a good practice to put code in blocks. It makes it simpler and easier to understand and debug as well.


问:
Rendering design. How can I effectively deal with forward, deferred and transparent rendering?
I have many objects in my game world that all derive from one base class.

Each object will have different materials and will therefore be required to be drawn using various rendering techniques.

I currently use the following order for rendering my objects.

Deferred

Forward

Transparent (order independent)

Each object has a rendering flag that denotes which one of the above methods should be used.

The list of base objects in the scene are then iterated through and added to separate lists of deferred, forward or transparent objects based on their rendering flag value.

The individual lists are then iterated through and drawn using the order above.  Each list is cleared at the end of the frame.

This methods works fairly well but it requires different draw methods for each material type.

For example each object will require the following methods in order to be compatible with the possible flag settings.

```<code>object.DrawDeferred()
object.DrawForward()
object.DrawTransparent()
</code>```

It is also hard to see where methods outside of materials, such as rendering shadow maps, would fit using this "flag & method" design.

```<code>object.DrawShadow()
</code>```

I was hoping that someone may have some suggestions for improving this rendering process, possibly making it more generic and less verbose?

答:
You can use Strategy.

You have a base class IDrawer::draw() with subclasses DefferedDrawer, ForwardDrawer, TransperantDrawer, etc

You then have a base class for your objects: IDrawable which uses an IDrawer drawer delegate for actual draw:
IDrawable::draw() { drawer->draw(); }

IDrawable also has a method for changing the drawer:
IDrawable::setDrawer(IDrawer someDrawer) {this->drawer = someDrawer;}

or the drawer can be automatically updated by some sort of state machine (here it depends on your usage), depending on the context changes.

You then have a single container for your objects (which can be sorted by some criteria) and call obj.draw()

ContentLicense: CC BY-SA 3.0


问:
Maintenance wise, is `else while` without intervening braces considered safe?
Is else while without intervening braces considered "safe" maintenance wise?

Writing if-else code without braces like below...

```<code>if (blah)
    foo();
else
    bar();
</code>```

...carries a risk because the lack of braces make it very easy to change the meaning of the code inadvertently.

However, is below also risky?

```<code>if (blah)
{
    ...
}
else while (!bloop())
{
    bar();
}
</code>```

Or is else while without intervening braces considered "safe"?

答:
I have always been taught to keep everything in braces, indented and commented. I believe it's much easier to read and spot errors. Personally i feel modularity is key so i would always write the code like this :</p>

```<code>    if(blah)
    {
     ....
    }
    else
    {
       while(!bloop()
       {
        bar;
       }
    }
</code>```

Body:
I have always been taught to keep everything in braces, indented and commented. I believe it's much easier to read and spot errors. Personally i feel modularity is key so i would always write the code like this :

    if(blah)
    {
     ....
    }
    else
    {
       while(!bloop()
       {
        bar;
       }
    }


问:
Question regarding code readability
I would like to know, is it considered a common practice to use constructions like  |=, &&, ||, != altogether in the single line of code?

E.g.

hasErrors |= vi2!=null && vi2.hasErrors() || vi.hasErrors();

What can be done to make the code more readable?

The programming language is Java, if it matters.

答:
Personally i think it is fine to use these constructions on one line, if use brackets to separate statements, for example :

```<code>    private boolean hasErrors()
    {
      return ( ( hasErrors |= vi2 != null ) && ( vi2.hasErrors() ) || ( vi.hasErrors() ));
    }
</code>```

This is so you can see exactly what each statement is doing and how they are connected.It is much easier for spotting errors.

Title: Question regarding code readability

Body:
Personally i think it is fine to use these constructions on one line, if use brackets to separate statements, for example :

    private boolean hasErrors()
    {
      return ( ( hasErrors |= vi2 != null ) && ( vi2.hasErrors() ) || ( vi.hasErrors() ));
    }

This is so you can see exactly what each statement is doing and how they are connected.It is much easier for spotting errors.


问:
How do we differentiate between a computer and a calculator?
In this SO Question there is a comment by starblue that

A computer without loops is a calculator

Is this true?

Is that the only difference?

Is there a set of criteria to differentiate or has the line become very blurred?

答:
a computer is generally turing complete

whereas the calculator is either a Pushdown Automaton (when it has brackets and priority of operations) or a Finite State Automat when it doesn't (it excecutes the next operation on the last result)


问:
Why the name 'continue'
The 'continue' keyword in Java (and probably in many other programming languages) is used to skip further execution of the current iteration.

Why was the name 'continue' chosen? Why not something more straightforward like 'skip' ?

答: I always thought of it as just continuing processing data and therefore it was named "continue". I have never seen anyone have issues with the choice of the continue keyword not being straightforward enough.</p>

Title: Why the name 'continue'


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
Get some little blocks of wood.

add metal hooks to one end, and metal eyes to the other.

you can now do a linked list in stuff you can play with.

Try explaining with this physical prop. I often wished I had this when teaching pointers to first year ( freshmen) students.

The little metal hook is the pointer, the block of wood the thing pointed to.

I DEFY anyone to not get it after playing with the blocks.

ContentLicense: CC BY-SA 2.5

Title: What's a nice explanation for pointers?


答:
There's nothing wrong with

```<code>if (blah)
    foo();
else
    bar();
</code>```

just like there's nothing wrong with

```<code>if (blah) foo(); else bar();
</code>```

in the right circumstances (your circumstances may vary, but that particular style is best used when you have a lot of repetitive code - then the view of each line is more important than the stylistic indentation)

But if you choose one way, keep to it - consistency is king. So your second example is very bad, as the if expression had brackets for its statement, the while statement should be inside the brackets for the else clause, not outside it.

besides, I have seen this code before:

```<code>if (x) foo()
{
  bar();
}
</code>```

and it was written by the coding standard nazi himself (who insisted on brackets for everything).

Title: Maintenance wise, is `else while` without intervening braces considered safe?

Body:
Is else while without intervening braces considered "safe" maintenance wise?

Writing if-else code without braces like below...

```<code>if (blah)
    foo();
else
    bar();
</code>```

...carries a risk because the lack of braces make it very easy to change the meaning of the code inadvertently.

However, is below also risky?

```<code>if (blah)
{
    ...
}
else while (!bloop())
{
    bar();
}
</code>```

Or is else while without intervening braces considered "safe"?

Body:
There's nothing wrong with

if (blah)
    foo();
else
    bar();

just like there's nothing wrong with

if (blah) foo(); else bar();

in the right circumstances (your circumstances may vary, but that particular style is best used when you have a lot of repetitive code - then the view of each line is more important than the stylistic indentation)

But if you choose one way, keep to it - consistency is king. So your second example is very bad, as the if expression had brackets for its statement, the while statement should be inside the brackets for the else clause, not outside it.

besides, I have seen this code before:

if (x) foo()
{
  bar();
}

and it was written by the coding standard nazi himself (who insisted on brackets for everything).


答:
I would extract method and make it

```<code>if ( blah )
{
    ...
}
else
{
   newMethod();
}
</code>```

See "extract method" approach explained at Refactoring Catalog site:

You have a code fragment that can be grouped together.

Turn the fragment into a method whose name explains the purpose of the method.

```<code>void printOwing() {
    printBanner();

    //print details
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + getOutstanding());
}
</code>```

```<code>void printOwing() {
    printBanner();
    printDetails(getOutstanding());
}

void printDetails (double outstanding) {
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + outstanding);
}
</code>```

Body:
I would extract method and make it

if ( blah )
{
    ...
}
else
{
   newMethod();
}

See "extract method" approach explained at Refactoring Catalog site:

You have a code fragment that can be grouped together.

Turn the fragment into a method whose name explains the purpose of the method.

void printOwing() {
    printBanner();

    //print details
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + getOutstanding());
}

void printOwing() {
    printBanner();
    printDetails(getOutstanding());
}

void printDetails (double outstanding) {
    System.out.println ("name:    " + _name);
    System.out.println ("amount    " + outstanding);
}


答:
I always put braces, just because you might add another line when in hurry, indent it, forget the braces and scratch your head what's happening. I keep the opening bracket on the same line, but it doesn't matter. I both cases it's better to have them.</p>

```<code>if(blah) {
    foo();
}
else {
    bar();
}
</code>```

Body:
I always put braces, just because you might add another line when in hurry, indent it, forget the braces and scratch your head what's happening. I keep the opening bracket on the same line, but it doesn't matter. I both cases it's better to have them.

if(blah) {
    foo();
}
else {
    bar();
}


答:
Well, despite everyone argues about using braces and seem to love them, I actually prefer the opposite. I only use braces when I have to because I find it more readable and concise without.

```<code>if (...)
   foo();
else while(...)
   bar();
</code>```

...I actually find this "else while(...)" remarkably readable! It even reads like plain English! But I guess people will all find it strange because it's unusual to say the least.

In the end, we all tend to make it idiot-proof with braces though ...because, well, you know.

Body:
Well, despite everyone argues about using braces and seem to love them, I actually prefer the opposite. I only use braces when I have to because I find it more readable and concise without.

if (...)
   foo();
else while(...)
   bar();

...I actually find this "else while(...)" remarkably readable! It even reads like plain English! But I guess people will all find it strange because it's unusual to say the least.

In the end, we all tend to make it idiot-proof with braces though ...because, well, you know.


问:
What if I forgot to include someone elses copyright info in old commit?
Assume I have a public source code repository. Am I violating copyright laws if there's any old commit where I have not yet added all copyright info for other people's open source code?

Details: Consider this theoretical scenario:

I copy-paste someone else's open source code files into a repository.

I commit.

I prefix copyright and licensing info at the top of the above-mentioned files.

I commit.

Many months passes, many people fork various versions of the master branch.

Now, many months later, I realize that there are files in commit no. 1 with no copyright info.

Do I have to squash the two above-mentioned commits, and rebase the whole repository? (Although it's been published! Everyone would be annoyed?)

Or does it suffice that the current repo version provides all needed copyright info?

Rephrased, for Git: If the HEAD of all Git branches, and all "published" Git tags, contain all required copyright and licensing info, do you think that  suffice? And it'd be other people's responsibilities if they check out other commits and redistribute? Or am I the culprit, and will be thrown in prison?

答: Copyright law does not require a copyright notice on each copy made, so you are not directly in violation of copyright law.  However, without a copyright notice, you may technically be in violation of the distribution license, depending on which license.  The primary goal of open source licenses is to promulgate any modifications, which you are doing, and you corrected the notice, so I wouldn't worry about it, unless there is some reason people would commonly check out the version without the notice.  </p>


答: It's not true if you're talking about a standard calculator. I would consider conditionals to be very important here as well.</p>

Title: How do we differentiate between a computer and a calculator?

Body:
In this SO Question there is a comment by starblue that

A computer without loops is a calculator

Is this true?

Is that the only difference?

Is there a set of criteria to differentiate or has the line become very blurred?


答:
A universal positive unconditional sentence cannot be true. (This one, for example, is universal, but negative). Here Joachim Sauer is correct.

"A computer without loops is a calculator" is a definition. It cannot be true or false at all. You can accept it or not.

But any definition can be widely or universally accepted or not to be. Or maybe it was sometimes accepted. Here you should choose yourself, what do you want.

As for history, in the middle of the XX century in fantastic literature all computers were called calculators.  Later, in 70/80-ties, programmable calculators had hundreds of command places, arrays, cycles, conditional branches, gotos and everything. As I remember, much more programs were made for them than for "large" computers.

Now programmable calculators are a minor business, but they do exist and there are new models of them. Look here.

So, the answers are: no; no(difference is in size mostly); yes, it is blurred.
Of course, as  far as you take wiki as widely accepted opinion


问:
What to do when a sprint is finished early?
What to do when a sprint is finished early?

At the moment our Scrum team works off stories from the backlog, if the sprint is finished early.

What happens with stories taken from the backlog? Will the stories be added to the current Sprint ? If yes, what if these stories won't be finished in time. Is the Sprint failed then?

答:
I'd encourage slack to be used for personal improvement. Sure, pull in stories from the backlog, but make sure you spend some time on yourselves: learn a new language, practice your craft with a kata, refactor some stuff, tweak, refine or write new tools to help you out, go and talk to a stakeholder, colleague or client, find out what your QA team does, take time to understand how your UX process works. </p>

<p>There is a huge list of things you can do that will provide value to your business and yourself AND improve your velocity or the amount of quality value you provide that don't involve pulling things from a backlog, try those first. </p>

Body:
I'd encourage slack to be used for personal improvement. Sure, pull in stories from the backlog, but make sure you spend some time on yourselves: learn a new language, practice your craft with a kata, refactor some stuff, tweak, refine or write new tools to help you out, go and talk to a stakeholder, colleague or client, find out what your QA team does, take time to understand how your UX process works.

There is a huge list of things you can do that will provide value to your business and yourself AND improve your velocity or the amount of quality value you provide that don't involve pulling things from a backlog, try those first.


问:
How do people define the minimum hardware requirements for software?
How do people define the minimum hardware requirements for software? For example: how can a software development company tell the customer that they will need 8 GB of RAM to run the program properly?</p>

答:
First off, not all requirements are hard requirements, but rather the minimum supported hardware.  If someone has less than the minimum, it may run - but not optimally, or it may not run at all.  In either case, its not a supported system and the problems you have are your own.

The simplest way to get hardware requirements is guess.  The developer looks at their machine and says "Yep, it runs on mine, that’s the requirements."

In a more rigorous environment, the development company has a suite of test systems.  It may not be in house (non in house apple developers occasionally use the Apple Compatibility Lab).  As part of the testing process, one tests on all the hardware available and determines the minimum requirements for it to run.

Another factor in hardware requirements is the base requirements for the operating system.  In theory, Windows 7 requires a minimum of 1GB of ram to run.  So testing against a 512 MB system running Windows 7 is nonsensical.

Test the system running with 1 GB of ram.  Does it work?  Nope... upgrade the ram.  Repeat the test and upgrades until the application works in a supportable way and list those as the minimum requirements.

When performance becomes part of the promise of the software the 'supportable' includes that in addition to actually running, that the operation meets the minimum performance expectation.


问:
Just how bad is it not to Dispose() SqlConnections?
Personally, I break out in hives if I don't put ADO objects that implement IDisposable in using statements.  But at my current contract, I've found that their homegrown enterprise framework "data access provider" code does not 1) implement IDisposable and 2) call Dispose() on anything it uses, at any point, ever.  Users have been complaining a great deal about performance issues in the Winforms applications that heavily use this framework for data access, and though there are a LOT of other problems in the code that could be hitting performance, this one just screams at me and is more low-hanging-fruit than the others.

So, beyond saying something like "Dispose is there for a reason, use it," what can I tell these people to convince them that this is really, really bad?

答:
The database connection pool is limited in size, and if it fills up, new connections will wait for old connections to be released. If you don't dispose them as soon as you're finished with them, they'll eventually get released when the finaliser runs, but that's an indeterminate amount of time in the future... So at best, you're going to see long delays when opening new connections.

At worst, they might've disabled the connection pool. Perhaps they discovered that after a while their app was returning "timeout waiting for connection" errors and disabling the connection pool "solved" that problem. However, this is much worse because it means you're creating a whole new connection every time - which is surprisingly resource intensive. If you've got hundreds of connections to the database open, it would be no wonder you're seeing performance problems.

The correct way to solve all of these problems is to dispose of your connection as soon as you're finished with it. The best idea is to hold the connection open for exactly as long as needed, and no longer.


答:
First off, the bitwise-or-and-assign |= is simply what you're doing with the expression. It's usually an assignment operator =, and a reader has to catch that this line is different, but it's fundamentally the goal of what you're doing. So it's perfectly fine to mix it with other logical operators found in the expression.

As for question of putting it all on one line, I think it's a matter of length. One or two operators on one line works if the variable names are short and there's nothing complex:

hasErrors |= vi2.hasErrors() || vi.hasErrors() || vi3.hasErrors();

I'm not a real hard-ass when it comes to 80 length lines, but you don't want to go past that limit too far:

```<code>isfuzzywuzzy |= themodulewithcats.fuzzycats.hairlegth > 5 || themodulewithcats.shaggycats.hairlength > 7 || genericContainerclass.Isuckatnamingconventions.feelsbadman();
</code>```

This is better displayed by breaking it into multiple lines

```<code>isfuzzywuzzy |= themodulewithcats.fuzzycats.hairlegth > 5 ||
                themodulewithcats.shaggycats.hairlength > 7 ||
                genericContainerclass.Isuckatnamingconventions.feelsbadman();
</code>```

Ideally aligning with the start of the expression, but auto-formatting never catches that so it's kind of a pain.

And if you have a mix of operators in the expression, or anything that makes it more complex, it's best to split it out and put parameters around things that need to be explicit. Breaking the line on the logical-or works best because of it's low order of operation.

```<code>hasCrazyErrors |= hasErrors > someObscureCode() ||
                  (vi2!=null && vi2.hasErrors()) ||
                  vi.hasErrors();
</code>```

And while don't like implied brackets and long lines, all this is different if you're dealing with a large set of such instructions:

```<code>if(Bit1) errors |= vi2.hasErrors() || vi.hasErrors() || vi3.hasErrors(); else errors = 0;
</code>```

Looks horrible right? Simply hard to read. But if you put enough of that together you get something where the eye can easily diff and tell what the hell is going on. (This is ultimately an example of breaking Don't Repeat Yourself, but it comes up a lot in embedded programming.)

```<code>if(Bit1) errors |= vi1.hasErrors() || vi.hasErrors() || vi3.hasErrors(); else errors = 0;
if(Bit2) errors |= vi2.hasErrors() || vi.hasErrors() || vi4.hasErrors(); else errors = 0;
if(Bit3) errors |= vi3.hasErrors() || vi.hasErrors() || vi5.hasErrors(); else errors = 0;
if(Bit4) errors |= vi4.hasErrors() || vi.hasErrors() || vi6.hasErrors(); else errors = 0;
if(Bit5) errors |= vi5.hasErrors() || vi.hasErrors() || vi7.hasErrors(); else errors = 0;
</code>```

And remember, if you're working on a team, the convention everyone uses is better than your own personal convention. Uniformity is more important.

Title: Question regarding code readability

Body:
I would like to know, is it considered a common practice to use constructions like  |=, &&, ||, != altogether in the single line of code?

E.g.

hasErrors |= vi2!=null && vi2.hasErrors() || vi.hasErrors();

What can be done to make the code more readable?

The programming language is Java, if it matters.

Body:
First off, the bitwise-or-and-assign |= is simply what you're doing with the expression. It's usually an assignment operator =, and a reader has to catch that this line is different, but it's fundamentally the goal of what you're doing. So it's perfectly fine to mix it with other logical operators found in the expression.

As for question of putting it all on one line, I think it's a matter of length. One or two operators on one line works if the variable names are short and there's nothing complex:

hasErrors |= vi2.hasErrors() || vi.hasErrors() || vi3.hasErrors();

I'm not a real hard-ass when it comes to 80 length lines, but you don't want to go past that limit too far:

isfuzzywuzzy |= themodulewithcats.fuzzycats.hairlegth > 5 || themodulewithcats.shaggycats.hairlength > 7 || genericContainerclass.Isuckatnamingconventions.feelsbadman();

This is better displayed by breaking it into multiple lines

isfuzzywuzzy |= themodulewithcats.fuzzycats.hairlegth > 5 ||
                themodulewithcats.shaggycats.hairlength > 7 ||
                genericContainerclass.Isuckatnamingconventions.feelsbadman();

Ideally aligning with the start of the expression, but auto-formatting never catches that so it's kind of a pain.

And if you have a mix of operators in the expression, or anything that makes it more complex, it's best to split it out and put parameters around things that need to be explicit. Breaking the line on the logical-or works best because of it's low order of operation.

hasCrazyErrors |= hasErrors > someObscureCode() ||
                  (vi2!=null && vi2.hasErrors()) ||
                  vi.hasErrors();

And while don't like implied brackets and long lines, all this is different if you're dealing with a large set of such instructions:

if(Bit1) errors |= vi2.hasErrors() || vi.hasErrors() || vi3.hasErrors(); else errors = 0;

Looks horrible right? Simply hard to read. But if you put enough of that together you get something where the eye can easily diff and tell what the hell is going on. (This is ultimately an example of breaking Don't Repeat Yourself, but it comes up a lot in embedded programming.)

if(Bit1) errors |= vi1.hasErrors() || vi.hasErrors() || vi3.hasErrors(); else errors = 0;
if(Bit2) errors |= vi2.hasErrors() || vi.hasErrors() || vi4.hasErrors(); else errors = 0;
if(Bit3) errors |= vi3.hasErrors() || vi.hasErrors() || vi5.hasErrors(); else errors = 0;
if(Bit4) errors |= vi4.hasErrors() || vi.hasErrors() || vi6.hasErrors(); else errors = 0;
if(Bit5) errors |= vi5.hasErrors() || vi.hasErrors() || vi7.hasErrors(); else errors = 0;

And remember, if you're working on a team, the convention everyone uses is better than your own personal convention. Uniformity is more important.


问:
Number of semi-random combinations / permutations given a set of constraints

Background:

There are around 60 students at the boarding school I work for. The counselor asked my colleague and me to come up with a better way to come up with seating arrangements for dinner than by hand. He would like assignments for the rest of the school year. He also asked us to try to solve some of the issues he has hearing about from students and faculty.

Constraints:

Most of the students are not from the US, so when they are surrounded by people of the same nationality (i.e., at the dinner table), they speak the language they are fluent in, instead of practicing English,

Complaints are made when students have sat at a certain table "too many" times overall,

or if they sit at the same table more than twice in a row,

and some of the students do not get along, so they cannot sit together.

Input:

At run time, the program is supplied with:

A set of people,

A set of tables, and

Each table has a different number of seats (repetition is allowed)

The size of both sets, and the size of each table does not change between each assignment.

Tests:

I am using 18 people of different nationalities, and 4 tables of size 3 through 6, inclusive. I picked numbers that I thought made sense for that data set:

No more than 3 people of the same nationality can sit together at a time

No person can sit at a table more than 4 times

Results:

I have run the generator around 15 times without changing the input data. Each time, it comes with anywhere from 6 to 12 "weeks" of assignments.

Questions:

(least to most important)

Why do I get a different number of generated assignments every time I run the program? The data set isn't changing between runs.

How do I find the...

minimum number of people of the same nationality that can sit at a given table,

minimum number of overall times they sit at a given table, all while

maximizing the number of generated assignments?

How do I guarantee that these actually are the correct numbers?

Edit:

Each time I generate a new assignment, I call Collections.shuffle(List) on the list of people to randomize their order. I then pass the list of tables and people to a backtracking method based off of kapilid's eight queens implementation on github to assign people to tables.

答:
Update:

I realized I didn't directly answer your questions.  I suppose it helps to read all of the question before firing off an answer...

You don't specify what algorithm you're using to generate the seating arrangements.  Presumably there is some element of variability / randomness in order to create different assignments for the duration of the term.  That randomness is most likely the reason why you're getting differing results on each run.  I'd mark that as working as designed instead of a bug.

a. You don't specify the algorithm, so we don't really know.  We also don't know the counts for each nationality.  By simple logic, 0 or 1 would be the absolute minimum at a table, but I suspect that's not very helpful to you.  Ultimately it depends upon the number of each nationality and how they populate the other tables.

b. Run your program, throw the results in a database or spreadsheet and have it count for you.  Or alter the program to keep track of those things.

c. The answer here is going to be dependent upon the number of each nationality and the other constraints you supplied.  Table size will also affect it.  The answer to this portion is really just a multiplication of the number of potential permutations.  Fortunately (for me) this is a site about programming, not statistics.

You have two issues to contend with here.  First is validating that your constraints accurately reflect the reality of the situation.  Talk to the counselor to verify your constraints are correct.  Second is verifying your results fulfill your constraints.  Write some methods that check the returned seating charts for the constraints you provided.  And / or manually inspect the charts to verify they are okay.

This SO Question has a similar question and suggests that this is equivalent to the bin packing problem or the knapsack problem

This SO Question Seat guests based on prioritized parameters seems to address exactly what you're looking for.

This SO Question discusses problems the author had in solving this problem using the bin-packing algorithm.  I'd suggest reading the answers to get a better insight in how to work around them.

And for the obligatory xkcd reference, here's a link from their forums discussing seating plan optimization and using a modified genetic algorithm to solve the problem.

If this is a real scenario, then best of luck.  And if this is just homework then you've got more than enough material to move you forward with.


答:
Given the code :

int v=42; // declaring and initializing a simple variable

int *p = &v; // creating a point p to the variable v

Following can be said about the above code:

int * p   // "int pointer p"  ... this is how you declare a pointer to variable of type int

*p       //   "pointed to by p"  ... that is the data that p points to, its same as v.

&v      //   "address of  the variable v" ... this represents the literal value for p

Title: What's a nice explanation for pointers?

Body:
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.


问:
How does a competition like Rails Rumble Work?
I am not sure weather it is a proper question to ask out here but it is really bothering for a while. As the official website writes:

The Rails Rumble is a distributed programming competition where teams
  of one to four people, from all over the world, have 48 hours to build
  an innovative web application, with Ruby on Rails or another
  Rack-based Ruby web framework. After the 48 hours are up, a panel of
  expert judges will pick the top ten winners.

One thing I don't get is how judges make sure that the app was made in the given time constraint. The quality of apps is so magnificent that I am really skeptical that such elegant apps could be made within 48hrs, even if you have planned it straight out on paper.

答:
From other such 48 hour competitions I know that preparation is not only allowed, but necessary. However, you cannot prepare anything in detail, because normally the subject/topic of the competition is revealed only once it begins.

This means that you can prepare some general parts in advance, which you will most likely be able to adapt to any given scenario. An inherent problem with such competitions is that there is no way to enforce the limit on the number of participants per team. If there's a team with a whole gfx/design crew behind them they could still submit as a 4 person team and you'll never really know.

Another point though is that in all team competitions experience and dedicated roles increase efficiency a lot. If everyone knows everyone's roles and you can thus keep down the communication complexity, then each person can work extremely efficient without too many interruptions. You shouldn't confuse this kind of efficiency with a normal workplace situation though. The small team, the small time-frame, the freedom in the competition rules, the extreme focusing, etc are all reasons why such a team can seemingly outperform normal workplace teams by several magnitudes. (Seemingly, because a lot of the work you have to perform in workplace conditions is left out for competitions - testing, requirements analysis/management, configuration management, reporting, ...)


问:
Refactoring several huge C++ classes / methods. How to start?

Possible Duplicate:

  I’ve inherited 200K lines of spaghetti code — what now?

I'm dealing with legacy code. It contains some BIG classes (line count 8000+) and some BIG methods (line count 3000+). For one of these methods I wrote a unit test that covers at least some code. This function has no specific structure, it is a mess of nested loops and conditions. I'd like to refactor but still I have no idea how to start.

I actually started by extracting one single function. In the end it had to have 21 parameters :-/

Should I ...

1. continue extracting awful functions knowing that in the long run I will succeed?

2. start extracting even bigger functions? So I expose the structure of this monster and then I can start the real refactoring.

3. only extract small "good" functions (and / or classes) just because I am a helluva clean coder?

4. do something completely different?

答:
Refactoring is somewhat the whole books is written about. It's hard to retell all the methods and pitfalls.

Before starting refactoring write the tests for a piece you want to refactor.

Start refactoring with small and clean pieces of those big functions

Find the piece that can be rewritten as a function and make it a function.

Run tests to be sure you've done the things right and no side effects appears

After this you should have and idea what has to be done with all other (big one) pieces.
When the whole thing becomes clearer then you can make a higher-level redesign.

P.S. it's just a brief sketch. About refactoring itself is better to read some books (like M. Fowler - Refactoring, etc.)

OwnerDisplayName: maverik


问:
I've stopped coding for fun, is this a bad sign?
At some point in time, I just stopped coding for fun.  I used to go to work, finish my assignments and then upon arriving home I'd go and write stuff on the side for fun.  However, I now just go home and try to avoid the computer.  I'd rather read the paper, watch TV, go out to the bar, etc.

Is this a bad sign?  I mean I still try to keep up on the latest trends, hit up the developer forums/blogs/etc but I haven't said, "I want to learn language X - I wonder if I could write app Y in it"

Has this happened to anyone else?

答:
I would be concerned about that, especially at your age. I'm thankful that I still find programming fun, because it's about the only thing I know how to do.

Here are some things I've found that help:

Find a way to use your skill for something outside work. I made a small app, based on C++ and MySQL, to help run charity auctions. Then I get to help run the auctions and sweat through a night of fund-raising, hoping I got rid of the bugs. Great fun!

Get a book or two on something interesting. For me, it was things like theorem proving, quantum computers, machine language, vision, and learning. Then try to write little programs to try them out. The smaller the better.

Learn some math. I had to go back and limber-up my skills with differential equations, calculus, linear algebra, and bayesian statistics. For everything, I write a little program to help me understand what I'm doing.

I hope you continue to find programming fun, but if it's not, I hope you find out what is fun for you.


答:
Code Complete recommends creating an interface or a wrapper between the legacy code and new code that uses it. Keep the interface clean and as you need to make changes to the legacy code, refactor or rewrite the pieces that you need to and move them forward.

If you need to make enough changes, then eventually the classes will be brought up to par with new code.

Title: Refactoring several huge C++ classes / methods. How to start?

Body:
Possible Duplicate:

  I’ve inherited 200K lines of spaghetti code — what now?

I'm dealing with legacy code. It contains some BIG classes (line count 8000+) and some BIG methods (line count 3000+). For one of these methods I wrote a unit test that covers at least some code. This function has no specific structure, it is a mess of nested loops and conditions. I'd like to refactor but still I have no idea how to start.

I actually started by extracting one single function. In the end it had to have 21 parameters :-/

Should I ...

1. continue extracting awful functions knowing that in the long run I will succeed?

2. start extracting even bigger functions? So I expose the structure of this monster and then I can start the real refactoring.

3. only extract small "good" functions (and / or classes) just because I am a helluva clean coder?

4. do something completely different?


问:
Does async/await makes simple thing unnecessary complicated?
After exposing to Windows App Store development for a month, I begin to feel that async / await programming model does more harm than good. It makes simple thing complicated.

Take an example, folder creation. In Java or Desktop .NET, I can simply do

Java

```<code>public Constructor()
{
    new File("c:\\folder").mkdirs();
    System.out.println("I am pretty sure c:\\folder is ready now");
}
</code>```

Desktop .NET

```<code>Constructor()
{
    System.IO.Directory.CreateDirectory("c:\\folder");
    Console.WriteLine("I am pretty sure c:\\folder is ready now");
}
</code>```

But when comes to

Windows App Store .NET

```<code>Constructor()
{
    // Damm it! Another async function? I don't need aysnc!
    Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);
    // I am not sure c:\\folder is ready right now!
    // OK. I know I can use ContinueWith. No no no. I don't want.
    // Why I have to use ContinueWith with such a simple operation?
}
</code>```

So, my question is, do you find the newly introduced async / await programming model in Windows App Store,

Improve your productivity?

Make programming life easier?

For me, I don't! Perhaps I have been missing out certain useful techniques.

I know, Microsoft says, it helps us to write responsive UI code.

But I would say, No thanks! Hey look, my code is already in non-UI code!

Most of my current operation code is fast enough and doesn't block UI. When my operation code is not fast enough, I am pretty comfortable in making those slow operation code run in separate Thread/ Task.

Forcing me to use async / await which I do not need, only makes my code more complicated.

Message to Microsoft : May I beg to you, besides async functions, can you provide a same set of non-async functions, please? I already build up my habit of running code in non-UI thread. I promise I will continue make your Windows App perform as smooth as iOS :)

答:
I see that the problem here is that you can't use await in a constructor and that GetResult won't work. But have you tought about using a static helper method to create your object?

```<code>class AsyncCreated
{
    public static async Task<AsyncCreated> CreateWithFolder()
    {
        var folder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);

        return new AsyncCreated(folder); // There you do the usual stuff
    }

}

// elsewhere in your code

var myObject = await AsyncCreated.CreateWithFolder();
</code>```

The added bonus is that now it's more explicit that some work is being done while you initialise the type.

Body:
I see that the problem here is that you can't use await in a constructor and that GetResult won't work. But have you tought about using a static helper method to create your object?

class AsyncCreated
{
    public static async Task<AsyncCreated> CreateWithFolder()
    {
        var folder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);

        return new AsyncCreated(folder); // There you do the usual stuff
    }

}

// elsewhere in your code

var myObject = await AsyncCreated.CreateWithFolder();

The added bonus is that now it's more explicit that some work is being done while you initialise the type.


问:
Why C# doesn’t support multiple inheritance?
Even if it could be bad practices, I would say that there is time that it would fulfill its purpose.</p>

答:
Because the language designers apparently wanted to produce a better C++, not a better language in general.  (How successful they were can be debated.)

C++-style multiple inheritance has some problems, and so people deriving from C++ generally omitted it (Java, C#, D).  Other languages, Eiffel and Common Lisp to name two, do it differently and don't seem to have the same problems.


问:
Is there ever a reasonable time to have test fixtures test MVC3 controller construction?
I've recently started with a new firm and I'm trying to understand the mechanics behind something, so I'll anonymize the code and present but a sample:

```<code>[Test(Description = "Retreives the New view for XXXX.")]
public void New()
{
  "~/XXXX/New".ShouldMapTo<XXXXController>(x => x.New());
  "~/XXXX/New".WithMethod(HttpVerbs.Post).ShouldMapTo<XXXXController>(x => x.New(null));
}
</code>```

and again:

```<code>[Test(Description = "Test the model injection into the New view.")]
public void New()
{
  var @new = WXYZController.New();
  @new.AssertViewRendered();

  Assert.IsInstanceOf<WXYZSettingsModel>(@new.ViewData.Model, "Expected the data model to be of type WXYZSettingsModel, but the model was another type.");
  var model = @new.ViewData.Model as WXYZSettingsModel;
  if (model == null)
    Assert.Fail("Failed to cast data model to type WXYZSettingsModel.");

    Assert.IsNotNull(model.YYYY, "Expected an instantiated service message, but a null message was returned.");
    Assert.AreEqual(model.YYYY.Status, WXYZ.Success, "Expected a success status code, but another code was returned.");
    Assert.IsNotNull(model.Categories, "");
    Assert.AreEqual(model.ZZZZ.Status, ABCD.Success, "Expected a success status code, but another code was returned.");
}
</code>```

It seems to me this violates the purpose of unit-testing, as you should never unit-test the framework, but rather, your own code, right? Did someone just get carried away?

Or am I missing some fundamental component of this code that is just obvious to someone who is more familiar with unit testing.

Note that there are entire files (one of each of the above per controller) that never test a single line of internal code, but are filled with these tests. Even to the point of this is fairly boilerplate now that I've anonymized it.

If we were instead testing like this (pseudocode now)

```<code>[Test(Description = "thingy tester, duh")]
public void ThingTest(){
  var mock = new MyDataMock();
  var finalMock = new MyFinalMock();
  var controller = new thingController();

  var test = controller.Thing(mock);
  assert.AreNotEqual(test,mock,"It didn't change it");
  assert.AreEqual(test,finalMock,"It worked!");
}
</code>```

I would expect that to be what the unit tests I should see should look like, no?

答:
There are cases when you might want to sanity check the framework's fitness that you're working with, especially in a regulated environment.

For example, in medical software development, if you follow the standard IEC 62304, the use of Software Of Unknown Providence (SOUP) is a risk (using third-party frameworks like ASP.NET MVC Framework or even the .NET Framework is considered risky under the standard). Depending on the Class of the software (A, B, or C), you may have certain burdens laid upon you to assess the risks that SOUP brings to your software system. One way to do this is to perform black-box unit and integration testing of the functions you intend to use in your software system, to verify they they work correctly for your purposes. If you follow IEC 62304, you're technically on the hook for any compiler you use, let alone 3rd-party components or frameworks you might decide to use.

Ultimately, if your software and process is audited by the FDA or a third-party, you have to be able to show to these auditors that you took reasonable steps to validate SOUP components, so you might have tests like these.


问:
Acceptance tests for large multi-step online form
I have to extend/fix a large online form written by other developer. There is a lot of code, mixing PHP and JS. It's kind of write-only style of coding and I want to redo it completely, but currently I can't.

It works like this:

It is a wizard-style form with 12 steps - let's call them phases to not confuse with steps of the tests.

User has to fill at least ~100 fields to finish.

Some fields are grouped by 3-5. Those groups can be dynamically added and removed with JS.

Validation is done after submitting each phase. If some errors occured, user is notified immediately and cannot go further until he/she fixes all errors.

Submitted data is temporarily stored in the session between phases. No permanent storage.

User cannot skip phases, only sequentially go back and forth to already completed phases.

It is ridiculous to test this thing manually, so I wrote a test using Behat with Mink and Selenium2.

I have only 1 test now, which completes all 12 phases of the form. To go to specific point in the process of filling the form, I created a step definition wich just makes webdriver wait 1 hour (laugh at me). When I need to test some specific phase, I just add this step where I want Selenium to stop - this leaves browser window open so I can do whatever I want manually without having to fill all previous fields.

It saves a ton of time, but feels stupid. I have reasons to do that:

Has to be done ASAP.

I cannot test each separate step in the form.

I cannot reuse parts of the filling process without having to write quite a lot of PHP code. Now my test is just ~120 lines written in Gherkin language.

Simplified version of my question is: how should I test this?

I can think of several ways:

Modify the code to allow skipping phases. This can be done safely by detecting environment parameters withing the application and deciding whether client (webdriver or user) can or cannot skip phases, so skipping is not allowed in a production environment.

Just write more tests with a lot of copy-pasting and be a bigger monkey.

Write step definitions to complete specific phases separately. So, I could just write

```<code>When I complete phase 1
And complete phase 2
And complete phase 3
...
</code>```

in the tests.

So, the full version of my question is: which way is preferable and what (dis)advantages each way has? Maybe there are other ways, like designing an application in a completely different way so there are no such problems.

答:
First off, don't change the code for the convenience of testing.  Honestly, that's a case of the tail wagging the dog.

There are some cases where it's justifiable to restructure the code to simplify testing, but for what you've laid out, it's a horrible idea.  When you receive a legacy "gift" like this, your first order of business is to change nothing until you can start boxing its effects.

More to your question...

Take an approach of structuring the test steps around the phases of input.  We'll pretend that there are business requirements that indicate that the inputs should be received in the fashion you described.  (Okay, we know that's a lie, but let's give the benefit of the doubt).

This pretense actually makes it easier to test the code.  It's an implied business rule that phase 2 cannot be tested unless phase 1 is complete AND correct.  Take a step back and you'll see that this dramatically simplifies the number of scenarios you have to test.  Tests within phase 2 can now assume everything is kosher within phase 1 because the business rules say you can't proceed to phase 2 unless 1 is okay.

It sounds like you're taking the right approach to testing things given the constraints you're under.  In other words - triage.  In an ideal world you could rewrite everything as well as writing perfect test cases at the same time.  In the meantime, deadlines are looming and updates need to get shipped.  Start with the "heavy hitter" test cases, and add in additional nuances as time allows.  This is honestly no different than most other development.  Time is generally a luxury that a project cannot afford.

Your ill-at-ease feelings are the conflict between the ideal way of testing the code versus the pragmatic way of testing the code.  That's a pretty normal reaction to compromises taken within the development process.  Comment the shortcuts you needed to take, indicate the areas to improve, and keep incrementing.

To help with testing later phases, create re-usable sections of mock-up code that complete prior sections correctly.  So to test phase 3, you'll make two calls to complete phase 1 and 2 correctly and allow phase 3 to be exposed.  It's a smidge of a hack, but it also reflects the business rules involved in the application.  In other words, break out your existing single test into 12 components.  This will allow you to exercise the downstream phases more easily / independently.


问:
Is adhering to one assert per test foolish consistency in this case?
I have a class that I'm testing. The class has a function: apply(List<IRule> rules, List<ITarget> targets);

In one test I want to ensure that each target has been passed to one rule, a la:

```<code>rule1.AssertWasCalled(fnord => fnord.Test(target1));
rule1.AssertWasCalled(fnord => fnord.Test(target2));
rule1.AssertWasCalled(fnord => fnord.Test(target3));
</code>```

It seems to me that limiting myself to a single assertion statement would be quite the hobgoblin. Am I correct in this assumption, or is there some other way that I could assert that each target had, in fact, been tested?

答:
The three asserts are in essence one test. You are testing behaviour of a method on a collection, to make sure that each item has been a parameter for a specific call (i.e. that each item has been processed properly).

Setting the data up three times and in three different methods is wasteful and less readable than the alternative of having several asserts.

The single assert "rule" is more about making asserts of different types in the same methods (essentially testing different things), which doesn't really apply in this case, where you are testing for a single behaviour.


答:
I have struggled with this one, too.

The purist (in me) insists on one assert per test so I'll know *exactly* where things blew up.

And then I find myself cutting / pasting a lot of the same, redundant test setup code.  After the third or fourth layer of this, you start to say "Oy! Enough!"

My compromise has been to find the aspects that "never" break.  And I'll layer those pieces together and then add in one new element that could break.  Just to be clear, layering multiple volatile areas in one test would be a violation of this compromise.

Title: Is adhering to one assert per test foolish consistency in this case?

Body:
I have a class that I'm testing. The class has a function: apply(List<IRule> rules, List<ITarget> targets);

In one test I want to ensure that each target has been passed to one rule, a la:

```<code>rule1.AssertWasCalled(fnord => fnord.Test(target1));
rule1.AssertWasCalled(fnord => fnord.Test(target2));
rule1.AssertWasCalled(fnord => fnord.Test(target3));
</code>```

It seems to me that limiting myself to a single assertion statement would be quite the hobgoblin. Am I correct in this assumption, or is there some other way that I could assert that each target had, in fact, been tested?


答:
It might.

But what's probably really happening is that it is keeping complicated things complicated.

Creating a file is complicated.  It can be over a network share.  It can already exist.  The hard drive might be slow.  It might be a RAM disk.  Point is, it can take different amounts of time, or might outright fail.

Jeff Atwood wrote a great post about this 8 years ago. He basically said that we should embrace multithreading and asyncronous code, but most developers aren't prepared to deal with it because it's a very complex topic, and the tools at the time weren't suitable to make it easy enough to write asynchronous code.

The async and await keywords (along with other tools, like the thread-safe collections) are Microsoft's answer to his request to improve the tools to bring easy async programming to the unwashed masses. My opinion is that they have mostly succeeded. In that a majority of cases, you can use the async APIs in WinRT as if they were not asynchronous, then just pepper in a few async and await keywords, compile and bask in the glow of responsive, non-blocking code.

Constructors, as well as a few more things, are where the limitations of the tools appear and trip up even the average programmer, who is just trying to write a program to do his job.

Jeff also commented that one reason why BeOS failed to attract developers was because, like WinRT, the entire OS API was asyncronous, and writing anything beyond a utility was torture. I think for the most part it's a small learning curve, but the tools are much more approachable than they were 8 years ago. We'll see how Microsoft fares in the future.

Title: Does async/await makes simple thing unnecessary complicated?

Body:
After exposing to Windows App Store development for a month, I begin to feel that async / await programming model does more harm than good. It makes simple thing complicated.

Take an example, folder creation. In Java or Desktop .NET, I can simply do

Java

```<code>public Constructor()
{
    new File("c:\\folder").mkdirs();
    System.out.println("I am pretty sure c:\\folder is ready now");
}
</code>```

Desktop .NET

```<code>Constructor()
{
    System.IO.Directory.CreateDirectory("c:\\folder");
    Console.WriteLine("I am pretty sure c:\\folder is ready now");
}
</code>```

But when comes to

Windows App Store .NET

```<code>Constructor()
{
    // Damm it! Another async function? I don't need aysnc!
    Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);
    // I am not sure c:\\folder is ready right now!
    // OK. I know I can use ContinueWith. No no no. I don't want.
    // Why I have to use ContinueWith with such a simple operation?
}
</code>```

So, my question is, do you find the newly introduced async / await programming model in Windows App Store,

Improve your productivity?

Make programming life easier?

For me, I don't! Perhaps I have been missing out certain useful techniques.

I know, Microsoft says, it helps us to write responsive UI code.

But I would say, No thanks! Hey look, my code is already in non-UI code!

Most of my current operation code is fast enough and doesn't block UI. When my operation code is not fast enough, I am pretty comfortable in making those slow operation code run in separate Thread/ Task.

Forcing me to use async / await which I do not need, only makes my code more complicated.

Message to Microsoft : May I beg to you, besides async functions, can you provide a same set of non-async functions, please? I already build up my habit of running code in non-UI thread. I promise I will continue make your Windows App perform as smooth as iOS :)


答:
For your particular example, you can get away with "one" assert statement if you do something like:

```<code>foreach target in targets
{
     rule1.AssertWasCalled(fnord => fnord.Test(target))
}
</code>```

It's what I do to avoid feeling guilty about having multiple asserts in one test.

Body:
For your particular example, you can get away with "one" assert statement if you do something like:

foreach target in targets
{
     rule1.AssertWasCalled(fnord => fnord.Test(target))
}

It's what I do to avoid feeling guilty about having multiple asserts in one test.


答:
If the setup code for target1 is different from the setup code for target2, this type of corner-cutting tends to eventually lead overly long test initialization code.  This in turn is either a mess or ends up being refactored and re-used.  If your tests are complex enough to justify refactoring them, your test is probably testing more than one thing.

If the setup code for each target is essentially the same, splitting your test into multiple individual tests is probably overkill.

If target1 and target2 are different implementations of the same interface, you should instead be adding a unit test to the interface (and allowing your test framework to generate a test for every implementation of that interface).


答:
For some applications the requirements may actually be hard requirements, such as when the developer has analyzed or profiled their app and knows exactly how many megaflops, MIPS, polygons per second, array working set sizes, etc. are required to meet some specified performance benchmark.

For small developers, cost may be the issue.  They only have one system available, and so they declare that system's specs as the minimum, as they haven't been able to test the app on anything else (slower, smaller, etc.) and have little clue on how the app would do with less resources.

Body: How do people define the minimum hardware requirements for software? For example: how can a software development company tell the customer that they will need 8 GB of RAM to run the program properly?</p>


答:
It's my belief that this one assert per test rule exists to keep your tests focused on one issue.  If you test 20 things in one test, it's really hard to tell what your coverage is.  You know it's causing a problem when you can't name the test method without the word and in it.  For example, if your test method would be more accurately named as testFooIsTrueAndDbExistsAndBarIsNullAndAnExceptionDoesntOccur(), you're probably testing too much in one test.

In your case, I think it's probably ok to assert three times.  If you want to make your code more readable, you could extract those three asserts into a method named assertWasCalledOnTargets(...).


问:
Does auto make C++ code harder to understand?
I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand—every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

```<code>auto x = GetX();
</code>```

Than:

```<code>someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();
</code>```

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder—does auto make C++ code harder to understand?

答:
Readability is subjective; you'll need to look at the situation and decide what's best.

As you pointed out, without auto, long declarations can produce a lot of clutter. But as you also pointed out, short declarations can remove type information which may be valuable.

On top of this, I'd also add this: be sure you're looking at readability and not writeability.  Code that's easy to write is generally not easy to read and vice versa.  For instance, if I were writing, I'd prefer auto.  If I were reading, maybe the longer declarations.

Then there's consistency; how important is that to you?  Would you want auto in some parts and explicit declarations in others, or one consistent method throughout?

OwnerDisplayName: Felics


答:
It's a case-by-case situation.

It sometimes makes code harder to understand, sometimes not. Take, for instance:

```<code>void foo(const std::map<int, std::string>& x)
{
   for ( auto it = x.begin() ; it != x.end() ; it++ )
   {
       //....
   }
}
</code>```

is definitely easy to understand and definitely easier to write than the actual iterator declaration.

I've been using C++ for a while now, but I can guarantee that I'd get a compiler error at my first shot at this because I'd forget about the const_iterator and would initially go for the iterator... :)

I'd use it for cases like this, but not where it actually obfuscates the type (like your situation), but this is purely subjective.

Title: Does auto make C++ code harder to understand?

Body:
I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand—every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

```<code>auto x = GetX();
</code>```

Than:

```<code>someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();
</code>```

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder—does auto make C++ code harder to understand?

Body:
It's a case-by-case situation.

It sometimes makes code harder to understand, sometimes not. Take, for instance:

void foo(const std::map<int, std::string>& x)
{
   for ( auto it = x.begin() ; it != x.end() ; it++ )
   {
       //....
   }
}

is definitely easy to understand and definitely easier to write than the actual iterator declaration.

I've been using C++ for a while now, but I can guarantee that I'd get a compiler error at my first shot at this because I'd forget about the const_iterator and would initially go for the iterator... :)

I'd use it for cases like this, but not where it actually obfuscates the type (like your situation), but this is purely subjective.

OwnerDisplayName: Luchian Grigore


答:
Yes, it makes it easier to know the type of your variable if you don't use auto. The question is: do you need to know the type of your variable to read the code? Sometimes the answer will be yes, sometimes no. For example, when getting an iterator from a std::vector<int>, do you need to know that it's a std::vector<int>::iterator or would auto iterator = ...; suffice? Everything that anybody would want to do with an iterator is given by the fact it's an iterator - it just doesn't matter what the type is specifically.

Use auto in those situations when it doesn't make your code harder to read.

OwnerDisplayName: sftrabbit


答:
This question solicits opinion, which will vary from programmer to programmer, but I would say no.  In fact in many cases just the opposite, auto can help to make code easier to understand by allowing the programmer to focus on the logic rather than the minutiae.

This is especially true in the face of complex template types.  Here is a simplified & contrived example.  Which is easier to understand?

```<code>for( std::map<std::pair<Foo,Bar>, std::pair<Baz, Bot>, std::less<BazBot>>::const_iterator it = things_.begin(); it != things_.end(); ++it )
</code>```

.. or...

```<code>for( auto it = things_.begin(); it != things_.end(); ++it )
</code>```

Some would say the second is easier to understand, others may say the first.  Yet others might say that a gratuitous use of auto may contribute to a dumbing-down of the programmers that use it, but that's another story.

Body:
This question solicits opinion, which will vary from programmer to programmer, but I would say no.  In fact in many cases just the opposite, auto can help to make code easier to understand by allowing the programmer to focus on the logic rather than the minutiae.

This is especially true in the face of complex template types.  Here is a simplified & contrived example.  Which is easier to understand?

for( std::map<std::pair<Foo,Bar>, std::pair<Baz, Bot>, std::less<BazBot>>::const_iterator it = things_.begin(); it != things_.end(); ++it )

.. or...

for( auto it = things_.begin(); it != things_.end(); ++it )

Some would say the second is easier to understand, others may say the first.  Yet others might say that a gratuitous use of auto may contribute to a dumbing-down of the programmers that use it, but that's another story.

OwnerDisplayName: John Dibling


答:
Look at it another way. Do you write:

```<code>std::cout << (foo() + bar()) << "\n";
</code>```

or:

```<code>// it is important to know the types of these values
int f = foo();
size_t b = bar();
size_t total = f + b;

std::cout << total << "\n";
</code>```

Sometimes it doesn't help to spell the type out explicitly.

The decision whether you need to mention the type isn't the same as the decision whether you want to split the code across multiple statements by defining intermediate variables. In C++03 the two were linked, you can think of auto as a way to separate them.

Sometimes making the types explicit can be useful:

```<code>// seems legit
if (foo() < bar()) { ... }
</code>```

vs.

```<code>// ah, there's something tricky going on here, a mixed comparison
if ((unsigned int)foo() < bar()) { ... }
</code>```

In cases where you declare a variable, using auto lets the type go unspoken just as it is in many expressions. You should probably try to decide for yourself when that helps readability and when it hinders.

You can argue that mixing signed and unsigned types is a mistake to begin with (indeed, some argue further that one should not use unsigned types at all). The reason it's arguably a mistake is that it makes the types of the operands vitally important because of the different behaviour. If it's a bad thing to need to know the types of your values, then it probably isn't also a bad thing not to need to know them. So provided the code isn't already confusing for other reasons, that makes auto OK, right? ;-)

Particularly when writing generic code there are cases where the actual type of a variable shouldn't be important, what matters is that it satisfies the required interface. So auto provides a level of abstraction where you ignore the type (but of course the compiler doesn't, it knows). Working at a suitable level of abstraction can help readability quite a lot, working at the "wrong" level makes reading the code a slog.

Body:
Look at it another way. Do you write:

std::cout << (foo() + bar()) << "\n";

or:

// it is important to know the types of these values
int f = foo();
size_t b = bar();
size_t total = f + b;

std::cout << total << "\n";

Sometimes it doesn't help to spell the type out explicitly.

The decision whether you need to mention the type isn't the same as the decision whether you want to split the code across multiple statements by defining intermediate variables. In C++03 the two were linked, you can think of auto as a way to separate them.

Sometimes making the types explicit can be useful:

// seems legit
if (foo() < bar()) { ... }

vs.

// ah, there's something tricky going on here, a mixed comparison
if ((unsigned int)foo() < bar()) { ... }

In cases where you declare a variable, using auto lets the type go unspoken just as it is in many expressions. You should probably try to decide for yourself when that helps readability and when it hinders.

You can argue that mixing signed and unsigned types is a mistake to begin with (indeed, some argue further that one should not use unsigned types at all). The reason it's arguably a mistake is that it makes the types of the operands vitally important because of the different behaviour. If it's a bad thing to need to know the types of your values, then it probably isn't also a bad thing not to need to know them. So provided the code isn't already confusing for other reasons, that makes auto OK, right? ;-)

Particularly when writing generic code there are cases where the actual type of a variable shouldn't be important, what matters is that it satisfies the required interface. So auto provides a level of abstraction where you ignore the type (but of course the compiler doesn't, it knows). Working at a suitable level of abstraction can help readability quite a lot, working at the "wrong" level makes reading the code a slog.

OwnerDisplayName: Steve Jessop


答:
Personally I use auto only when it's absolutely obvious for the programmer what it is.

Example 1

```<code>std::map <KeyClass, ValueClass> m;
// ...
auto I = m.find (something); // OK, find returns an iterator, everyone knows that
</code>```

Example 2

```<code>MyClass myObj;
auto ret = myObj.FindRecord (something)// NOT OK, everyone needs to go and check what FindRecord returns
</code>```

Body:
Personally I use auto only when it's absolutely obvious for the programmer what it is.

Example 1

std::map <KeyClass, ValueClass> m;
// ...
auto I = m.find (something); // OK, find returns an iterator, everyone knows that

Example 2

MyClass myObj;
auto ret = myObj.FindRecord (something)// NOT OK, everyone needs to go and check what FindRecord returns

OwnerDisplayName: aleguna


问:
Do I have to learn html and javascript to create web applications?
I am an experienced Java programmer, and I want to create a complex web application requiring dynamic pages, drawings, etc (take SO as an example). Do I have to learn javascript/html in order to create such an application?

It is not that I don't want to learn another language (I've done this before), but technology on the javascript environment seems to change so fast that when you finish learning one framework it is already obsolete. I have checked a number of java framework for web development (spring, play), but not deeply. So can these frameworks (or other possible java frameworks that I'm not aware of) be used without learning html/javascript? I also have some python experience. So if I can do the app in python it is also an option.

答:
I will join the chorus in saying that that you will most likely have to learn HTML/CSS/Javascript at some point.

However, you seem to be asking for frameworks that do not invovle writing front-end code. I can relate to that sentiment. Unfortunately, there's very few mature technologies that abstract that stuff (for a number of good reasons).

Take a look at Wt and the Java version JWt. It might be what you are looking for.

In a nutshell, that framework attempts to make web-apps widget-centric so that rather than writing HTML templates you code UI as if it was a desktop application. It uses some new technologies like web sockets, does progressive enhancement, and generally abstracts you from having to do much front end.


答:
HTML is the language of the web, so you'll have to know it somewhat.

Javascript not so much ... you can use PHP, etc. as well. Javascript isn't 100% necessary.

If you're building a website entirely I'd recommend Javascript for sure, since it's supported by basically all browsers, and will retain compatibility between different browsing programs.

But if you're just creating web applications, this applies much less than if you're creating a website.

Title: Do I have to learn html and javascript to create web applications?

Body:
I am an experienced Java programmer, and I want to create a complex web application requiring dynamic pages, drawings, etc (take SO as an example). Do I have to learn javascript/html in order to create such an application?

It is not that I don't want to learn another language (I've done this before), but technology on the javascript environment seems to change so fast that when you finish learning one framework it is already obsolete. I have checked a number of java framework for web development (spring, play), but not deeply. So can these frameworks (or other possible java frameworks that I'm not aware of) be used without learning html/javascript? I also have some python experience. So if I can do the app in python it is also an option.


问:
Web versus desktop development - is web development worse?
As a longtime desktop developer looking at doing our first large-scale web application, what are the pros and cons of doing web development?

Is developing a web application much worse than developing a desktop app?  E.g., is it more tedious or annoying?  Is the time to market much worse?  Is the web platform excessively limiting?  If the answer to any of these is yes, then why?

(And how does developing a Flash or Silverlight app compare?)

答:
As someone who's dealt with both (more desktop than web though): by far my biggest gripe is the sense of "general clunkiness" in web development. Even with the very best tools and frameworks, the abstractions are still very leaky and you're constantly dealing with the fact that you're running over a stateless protocol.

Another related annoyance is the mix of technologies that's used to implement web apps. There is no nice, monolithic, modular environment and language that everything can be done in. Even relatively simple web apps require you to code things in a handful of separate programming, scripting, and markup languages.

So as a general answer: YES, it really is that bad. At least if you're coming from a traditional desktop background where you're used to coding things in a clean, seamless environment, using a technology and platform where everything is quite linear and well defined. The best way is to just not try to think of it as the same field. If you keep subconsciously expecting web development to be "like desktop development", it'll always look very obnoxious and annoying.


问:
Java style classes in c++
I came across this article proposing a style of coding in c++ that looks a bit weird at first. But after reading it over and pondering for a bit I'm really considering giving it a try.

The most appealing benefit is the ease of refactoring methods. I find myself constantly changing method names, parameters and so on while writing a new class and in c++ it's quite annoying having to change a method name in two files (.h, .cpp).

I tried to find something wrong with this style but apart from the fact that the code will look and feel really strange to seasoned c++ programmers I can't spot any major flaw. But since I am quite a inexperienced c++ programmer I hope that someone here might alert me to any potential dangers.

So my question is:

Are there any serious drawbacks of using this style of coding?

答:
It's not exactly a new idea.  Beginning programmers avoid declarations like the plague, and mostly get away with it because their programs are so small.  The consequence is that you now have to worry about the order you define your functions.  The consequence of worrying about definition order is a temptation to minimize the problem by making your functions too big.

You also lose the nice separation of interface and implementation.  The author himself laments the private members being part of the header file, then "solves" the problem by making all implementation details a part of the header file.

Title: Java style classes in c++


问:
Does low latency code sometimes have to be "ugly"?
(This is mainly aimed at those who have specific knowledge of low latency systems, to avoid people just answering with unsubstantiated opinions).

Do you feel there is a trade-off between writing "nice" object orientated code and writing very fast low latency code? For instance, avoiding virtual functions in C++/the overhead of polymorphism etc- re-writing code which looks nasty, but is very fast etc?

It stands to reason- who cares if it looks ugly (so long as its maintainable)- if you need speed, you need speed?

I would be interested to hear from people who have worked in such areas.

答:
Complex and ugly aren't the same thing. Code that has many special cases, that's optimized to eek out every last drop of performance, and that looks at first like a tangle of connections and dependencies may in fact be very carefully engineered and quite beautiful once you understand it. Indeed, if performance (whether measured in terms of latency or something else) is important enough to justify very complex code, then the code must be well designed. If it's not, then you can't be sure that all that complexity is really better than a simpler solution.

Ugly code, to me, is code that's sloppy, poorly considered, and/or unnecessarily complicated. I don't think you'd want any of those features in code that has to perform.


答:
That looks to me to be just giving a goofy name to doing forward declarations instead of #include <blah>.

The benefits to the forward declarations is that your compile times can be significantly faster, but the main drawback IMO is you have to be mindful of when you can and cannot get away with a forward declaration, and when you screw it up, you can get seemingly incomprehensible error messages for a trivial error.

Title: Java style classes in c++

Body:
I came across this article proposing a style of coding in c++ that looks a bit weird at first. But after reading it over and pondering for a bit I'm really considering giving it a try.

The most appealing benefit is the ease of refactoring methods. I find myself constantly changing method names, parameters and so on while writing a new class and in c++ it's quite annoying having to change a method name in two files (.h, .cpp).

I tried to find something wrong with this style but apart from the fact that the code will look and feel really strange to seasoned c++ programmers I can't spot any major flaw. But since I am quite a inexperienced c++ programmer I hope that someone here might alert me to any potential dangers.

So my question is:

Are there any serious drawbacks of using this style of coding?


答:
IMO, you're looking at this pretty much in reverse.

It's not a matter of auto leading to code that's unreadable or even less readable. It's a matter of (hoping that) having an explicit type for the return value will make up for the fact that it's (apparently) not clear what type would be returned by some particular function.

At least in my opinion, if you have a function whose return type isn't immediately obvious, that's your problem right there. What the function does should be obvious from its name, and the type of the return value should be obvious from what it does. If not, that's the real source of the problem.

If there's a problem here, it's not with auto. It's with the rest of the code, and chances are pretty good that the explicit type is just enough of a band-aid to keep you from seeing and/or fixing the core problem. Once you've fixed that real problem, readability of the code using auto will generally be just fine.

I suppose in fairness I should add: I've dealt with a few cases where such things weren't nearly as obvious as you'd like, and fixing the problem was fairly untenable as well. Just for one example, I did some consulting for a company a couple years ago that had previously merged with another company. They ended up with a code base that was more "shoved together" than really merged. The constituent programs had started out using different (but quite similar) libraries for similar purposes, and though they were working to merge things more cleanly, they still did. In a fair number of cases, the only way to guess what type would be returned by a given function was to know where that function had originated.

Even in such a case, you can help make quite a few things clearer. In that case, all the code started out in the global namespace. Simply moving a fair amount into some namespaces eliminated the name clashes and eased type-tracking quite a bit as well.


问:
Would using Quercus make my code fall under the GPL?
Quercus is an implementation of PHP written in Java, and released under the GPL.

If I use it, does my PHP code fall under the GPL?

What about my Java code?

Assuming I write new Java code, and new PHP code, and use Quercus to run my PHP code on the JVM and call into my Java code, which pieces fall under the GPL?

Also, assume that the result is commercial software that I want to distribute.

答: Generally, if you start to distribute Quercus with your code, then your code will also fall under the GPL.  For alternative licensing terms, you should contact their representatives.</p>


答:
I will take the point of less readable code as an advantage, and will encourage the programmer to use it more and more. Why? Clearly if the code using auto is difficult to read, then it will be difficult to write too. The programmer is <strong> forced to use the meaningful variable name </strong>, to make his/her job better. <br>
Maybe in the beginning the programmer may not write the meaningful variable names. But eventually while fixing the bugs, or in code review, when he/she has to explain the code to others, or in not so near future, he/she explaining the code to maintenance people, the programmer will realize the  mistake and will use the meaningful variable name in future.   </p>

Body:
I will take the point of less readable code as an advantage, and will encourage the programmer to use it more and more. Why? Clearly if the code using auto is difficult to read, then it will be difficult to write too. The programmer is  forced to use the meaningful variable name , to make his/her job better.

Maybe in the beginning the programmer may not write the meaningful variable names. But eventually while fixing the bugs, or in code review, when he/she has to explain the code to others, or in not so near future, he/she explaining the code to maintenance people, the programmer will realize the  mistake and will use the meaningful variable name in future.


答:
I decide on the following:

If my code runs only with the GPL licensed library my code has also to be GPL.

If my code can run without the library (in your example the PHP code) it does not need to be GPL.

Disclaimer: IANAL.

Title: Would using Quercus make my code fall under the GPL?

Body:
Quercus is an implementation of PHP written in Java, and released under the GPL.

If I use it, does my PHP code fall under the GPL?

What about my Java code?

Assuming I write new Java code, and new PHP code, and use Quercus to run my PHP code on the JVM and call into my Java code, which pieces fall under the GPL?

Also, assume that the result is commercial software that I want to distribute.


问:
How to do external API testing (blackbox)
Assume you are using APIs from a vendor, how to make sure their API is working as expected?

My main concern is sometimes the vendor pushed the changes to their code and break the API, we want to have some sort of automatic software to test them continually. How to deal with this?

答:
Short answer: you need a test suite for a third-party vendor API - so you will have to develop one.

Don't expect anyone else to do it for you, and don't expect a "magic bullet" for generating automatically the right tests.

Some things you could try additionally:

ask the vendor if they provide a list of "breaking changes" for each new release

ask them how they care about API compatibility/inform them that this is an important feature for you

check if the API provides specific testing hooks, logging output or something like that for parts which could not be tested easily either

wrap important API calls with your own logging code, writing input and related output of the API to a log file, this will make it easier to debug things if something unexpected happens

add assertions to API calls to check pre- and postconditions, so if a new release of the API shows up unexpected behaviour within your application, you get informed early by an error message

If these things work or not depends on who is your vendor and what kind of API you have in mind. An API which produces some inspectable output like files is much easier to test than an API which controls some physical device where you have to observe the behaviour of the thing to decide whether the API call was successful or not.


问:
design for interruptable operations
I couldn't find a better topic but here it is;

1) When user clicks a button, code starts t work,

2) When another button is clicked, it would stop doing whatever it does and start to run the second button's code,

3) Or with not user interaction, an electrical power down detected from a connected device, so our software would cancel the current event and start doing the power down procedure.

How is this design mostly applied to code? I mean "stop what you are doing" part?

If you would say events, event handlers etc. how do you bind a condition to the event? and how do you tell the program without using laddered if's to end it's process?

```<code>method1();
if (powerdown) return;
method2();
if (powerdown) return;
</code>```

etc.

答:
An alternative to threads is using an event (interrupt) mechanism coupled with a a "main loop" that runs the button and power down code, and a timer interval as the "scheduler" to figure out which piece of code to run next. In this case there are three types of events that you need to deal with:

button1 or button2 pressed

power down signal

timer signal, in an interval of say every 500ms

The idea is as follows:

each time a button gets pressed, remember which button this was

each time the timer fires, check which piece of the (button) event code is supposed to run next

run the event code as part of the main loop

split the event code in multiple pieces, after each piece check if the power down signal has occurred. If so, exit.

In the timer handler, check which part of the event code is supposed to run next, according to whatever button was figured in step 1. This is the "scheduler". In case of the power down signal, remember not to run any further button code, and in the main loop, run the power down code instead.

The main loop does exactly as it's name suggests:

```<code>    interrupted = false; // assigned true on alternative button pressed
    stopped = false; // assigned true at the end of power down
    while(!stopped) {
       while(!interrupted) {
         run the code (piece of event code) determined by the scheduler
       }
   }
</code>```

EDIT: explaining the example in more detail:

Wait, that's just the same as the OP example, but more complicated!?
No. Here the event handling, scheduling and execution are factored out and do not pollute the "buttons' code". Rather, the button code is kept simple and does not "know" of any partitions, nor does it need to provide for "cancellation" logic. Note that splitting the event code means that each piece is essentially a simple, seperate method whose execution is triggered from the main loop. There are no "if-ladders" as by OP's example. This keeps the actual logic readable and maintainable.

What if the event code is supposed to run only once?
The scheduler can also be extended to allow the event code, or some parts of it, to run only once. For this introduce a data structure that keeps track of which piece has run. Every time the scheduler runs, it updates the data structure and depending on the conditions you set for each piece of code, decides whether it should be scheduled or execution.

Why not run the button code directly in each event handler?
You could also run the button code directly in step 1, but this would make the UI sluggish, as it wouldn't respond until the code has finished to run. This is why the the timer handler needs to implement a scheduler. It determines which code to run. The actual code only gets to run on the main loop.

Why not run button code within the timer handler?
You could also run the buttons' code directly within the timer handler. The downside is that you'd have to ensure the code does not overrun the length of the timer interval to avoid interrupt overflows, or worse.

Isn't this too complex?
This design may seem overly complicated at first, but it makes sure the system continues to run smoothly by separating UI, scheduling and actual code running. The alternative, of course, is to use threads, but then the whole point of this answer is to show a solution withouth threads.

Are there improvements, e.g. for real time constraints?
Essentially, this all boils down to a scheduling problem. See Scheduling Algorithms (Wikipedia) for more sophisticated approaches, e.g. to deal with real time requirements.

Title: design for interruptable operations

Body:
An alternative to threads is using an event (interrupt) mechanism coupled with a a "main loop" that runs the button and power down code, and a timer interval as the "scheduler" to figure out which piece of code to run next. In this case there are three types of events that you need to deal with:

button1 or button2 pressed

power down signal

timer signal, in an interval of say every 500ms

The idea is as follows:

each time a button gets pressed, remember which button this was

each time the timer fires, check which piece of the (button) event code is supposed to run next

run the event code as part of the main loop

split the event code in multiple pieces, after each piece check if the power down signal has occurred. If so, exit.

In the timer handler, check which part of the event code is supposed to run next, according to whatever button was figured in step 1. This is the "scheduler". In case of the power down signal, remember not to run any further button code, and in the main loop, run the power down code instead.

The main loop does exactly as it's name suggests:

    interrupted = false; // assigned true on alternative button pressed
    stopped = false; // assigned true at the end of power down
    while(!stopped) {
       while(!interrupted) {
         run the code (piece of event code) determined by the scheduler
       }
   }

EDIT: explaining the example in more detail:

Wait, that's just the same as the OP example, but more complicated!?
No. Here the event handling, scheduling and execution are factored out and do not pollute the "buttons' code". Rather, the button code is kept simple and does not "know" of any partitions, nor does it need to provide for "cancellation" logic. Note that splitting the event code means that each piece is essentially a simple, seperate method whose execution is triggered from the main loop. There are no "if-ladders" as by OP's example. This keeps the actual logic readable and maintainable.

What if the event code is supposed to run only once?
The scheduler can also be extended to allow the event code, or some parts of it, to run only once. For this introduce a data structure that keeps track of which piece has run. Every time the scheduler runs, it updates the data structure and depending on the conditions you set for each piece of code, decides whether it should be scheduled or execution.

Why not run the button code directly in each event handler?
You could also run the button code directly in step 1, but this would make the UI sluggish, as it wouldn't respond until the code has finished to run. This is why the the timer handler needs to implement a scheduler. It determines which code to run. The actual code only gets to run on the main loop.

Why not run button code within the timer handler?
You could also run the buttons' code directly within the timer handler. The downside is that you'd have to ensure the code does not overrun the length of the timer interval to avoid interrupt overflows, or worse.

Isn't this too complex?
This design may seem overly complicated at first, but it makes sure the system continues to run smoothly by separating UI, scheduling and actual code running. The alternative, of course, is to use threads, but then the whole point of this answer is to show a solution withouth threads.

Are there improvements, e.g. for real time constraints?
Essentially, this all boils down to a scheduling problem. See Scheduling Algorithms (Wikipedia) for more sophisticated approaches, e.g. to deal with real time requirements.


问:
How are open-source projects able to sustain themselves?
I always had this question in mind but couldn't find a proper place to ask. There are some really nice and great open source free software available on the net. How do these products sustain themselves financially? It is one thing writing a small utility which does something nice but writing a complicated product with whole lot of features is a totally different ball game. So to repeat myself again, how do they work financially?</p>

答: If you develop OSS with a strong copyleft licence (GPL or AGPL), you can then charge for exceptions to that licence, allowing people to include your code in their proprietary products. If you use a more permissive license (X11, Apache, MPL), they can include your code in their product anyway, so you have nothing to sell them.