问:
Programming principles with regard to software (computational) efficiency and the use of variables
I'm classically trained psychologist, not a programmer, so sometimes the more advanced aspects of programming escape me, in particular regarding program efficiency and/or certain best practices, in this case with regard to the use of variables.

Here is some pseudo-code:

```<code>var a;
var b;
var c;
function GetSomeInformation() {
    returns "XYZ";
}

a = GetSomeInformation();
b = GetSomeInformation();
c = GetSomeInformation();
</code>```

So my question is:

Is it more or less efficient (or the same) to store data into a variable once and reference that as opposed to repeated calls to the same function?

I.E., is this code more efficient?

```<code>var results = GetSomeInformation();
a = results;
b = results;
c = results;
</code>```

If so, is this gain or loss in efficiency generally the same across languages, or does it vary by language? Are there thresholds where it becomes better to name a variable as opposed to using a repeated function call or vice versa? What aspects might change its efficiency (e.g., is there a difference whether it's a member function of a class vs. a regular function in the global scope)? etc.

If possible, I'd like to know specifically how such a notion applies to C++/MFC dialogs, as it arose when I was writing some code in that framework.

```<code>// define pointers to the items in my form
CListBox *pLISTBOX = (CListBox*) GetDlgItem(LISTBOX);
CStatic *pSTATIC_A = (CStatic*) GetDlgItem(STATIC_A);
CStatic *pSTATIC_B = (CStatic*) GetDlgItem(STATIC_B);
CEdit *pEDIT_BOX_A = (CEdit*) GetDlgItem(EDIT_BOX_A);
CEdit *pEDIT_BOX_B = (CEdit*) GetDlgItem(EDIT_BOX_B);
int SelectedIndex = pLISTBOX->GetCurSel();
pSTATIC_A->SetWindowText(pLISTBOX->GetItemData(SelectedIndex));
pSTATIC_B->SetWindowText(pLISTBOX->GetItemData(SelectedIndex));
pEDIT_BOX_A->SetWindowText(pLISTBOX->GetItemData(SelectedIndex));
pEDIT_BOX_B->SetWindowText(pLISTBOX->GetItemData(SelectedIndex));
</code>```

答:
To answer your question: It is generally more efficient to store data in a variable and reference that. Additional local variables are cheap.

Starting with a simple example, suppose you have the code fragment:

```<code>x = 5;
y = x*x + 1;
z = x*x + 2;
</code>```

If you look at the above code and pretend you're the CPU executing it step by step, the CPU would do the multiplication twice with the same value of x. That's almost always less efficient than doing the multiplication once:

```<code>x = 5;
x2 = x*x;
y = x2 + 1;
z = x2 + 2;
</code>```

Now, modern compilers almost always have an optimisation called common subexpression elimination, which will have the same effect of extracting x2 as in the above example. So you often don't have to worry about it, because the compiler has your back.

Having said that, using a variable such as x2 might substantially reduce the complexity of the following lines, so there's nothing wrong with introducing a variable like that for readability reasons.

In the case of your MFC code, you are repeatedly calling pLISTBOX->GetItemData(SelectedIndex). Since this is a function call that makes a call into the OS to get further data, the compiler can't do common subexpression elimination on that. Instead, I would introduce a new variable so you only have to do the call once:

```<code>int SelectedIndex = pLISTBOX->GetCurSel();
const char *data = pLISTBOX->GetItemData(SelectedIndex);
pSTATIC_A->SetWindowText(data);
pSTATIC_B->SetWindowText(data);
pEDIT_BOX_A->SetWindowText(data);
pEDIT_BOX_B->SetWindowText(data);
</code>```

Body:
To answer your question: It is generally more efficient to store data in a variable and reference that. Additional local variables are cheap.

Starting with a simple example, suppose you have the code fragment:

x = 5;
y = x*x + 1;
z = x*x + 2;

If you look at the above code and pretend you're the CPU executing it step by step, the CPU would do the multiplication twice with the same value of x. That's almost always less efficient than doing the multiplication once:

x = 5;
x2 = x*x;
y = x2 + 1;
z = x2 + 2;

Now, modern compilers almost always have an optimisation called common subexpression elimination, which will have the same effect of extracting x2 as in the above example. So you often don't have to worry about it, because the compiler has your back.

Having said that, using a variable such as x2 might substantially reduce the complexity of the following lines, so there's nothing wrong with introducing a variable like that for readability reasons.

In the case of your MFC code, you are repeatedly calling pLISTBOX->GetItemData(SelectedIndex). Since this is a function call that makes a call into the OS to get further data, the compiler can't do common subexpression elimination on that. Instead, I would introduce a new variable so you only have to do the call once:

int SelectedIndex = pLISTBOX->GetCurSel();
const char *data = pLISTBOX->GetItemData(SelectedIndex);
pSTATIC_A->SetWindowText(data);
pSTATIC_B->SetWindowText(data);
pEDIT_BOX_A->SetWindowText(data);
pEDIT_BOX_B->SetWindowText(data);


答:
A general principle I follow is that if I don't know how a function is implemented, it might be expensive and if I know that I only need the value from that function once, I just store it locally. Your code example would then become:

```<code>// define pointers to the items in my form
//...
int SelectedIndex = pLISTBOX->GetCurSel();
String text = pLISTBOX->GetItemData(SelectedIndex); //Ok, so maybe String isn't a valid type here but you get the idea...
pSTATIC_A->SetWindowText(text);
pSTATIC_B->SetWindowText(text);
pEDIT_BOX_A->SetWindowText(text);
pEDIT_BOX_B->SetWindowText(text);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Programming principles with regard to software (computational) efficiency and the use of variables

Body:
I'm classically trained psychologist, not a programmer, so sometimes the more advanced aspects of programming escape me, in particular regarding program efficiency and/or certain best practices, in this case with regard to the use of variables.

Here is some pseudo-code:

```<code>var a;
var b;
var c;
function GetSomeInformation() {
    returns "XYZ";
}

a = GetSomeInformation();
b = GetSomeInformation();
c = GetSomeInformation();
</code>```

So my question is:

Is it more or less efficient (or the same) to store data into a variable once and reference that as opposed to repeated calls to the same function?

I.E., is this code more efficient?

```<code>var results = GetSomeInformation();
a = results;
b = results;
c = results;
</code>```

If so, is this gain or loss in efficiency generally the same across languages, or does it vary by language? Are there thresholds where it becomes better to name a variable as opposed to using a repeated function call or vice versa? What aspects might change its efficiency (e.g., is there a difference whether it's a member function of a class vs. a regular function in the global scope)? etc.

If possible, I'd like to know specifically how such a notion applies to C++/MFC dialogs, as it arose when I was writing some code in that framework.

```<code>// define pointers to the items in my form
CListBox *pLISTBOX = (CListBox*) GetDlgItem(LISTBOX);
CStatic *pSTATIC_A = (CStatic*) GetDlgItem(STATIC_A);
CStatic *pSTATIC_B = (CStatic*) GetDlgItem(STATIC_B);
CEdit *pEDIT_BOX_A = (CEdit*) GetDlgItem(EDIT_BOX_A);
CEdit *pEDIT_BOX_B = (CEdit*) GetDlgItem(EDIT_BOX_B);
int SelectedIndex = pLISTBOX->GetCurSel();
pSTATIC_A->SetWindowText(pLISTBOX->GetItemData(SelectedIndex));
pSTATIC_B->SetWindowText(pLISTBOX->GetItemData(SelectedIndex));
pEDIT_BOX_A->SetWindowText(pLISTBOX->GetItemData(SelectedIndex));
pEDIT_BOX_B->SetWindowText(pLISTBOX->GetItemData(SelectedIndex));
</code>```

Body:
A general principle I follow is that if I don't know how a function is implemented, it might be expensive and if I know that I only need the value from that function once, I just store it locally. Your code example would then become:

// define pointers to the items in my form
//...
int SelectedIndex = pLISTBOX->GetCurSel();
String text = pLISTBOX->GetItemData(SelectedIndex); //Ok, so maybe String isn't a valid type here but you get the idea...
pSTATIC_A->SetWindowText(text);
pSTATIC_B->SetWindowText(text);
pEDIT_BOX_A->SetWindowText(text);
pEDIT_BOX_B->SetWindowText(text);


答:
Yes, the second code is marginally more efficient than the first code, in most languages.

It probably doesn't make any practical difference.

It probably does make a difference in readability, so go with the cleaner code.

Also, a good compiler (including Java's JIT) will inline repeated method calls and cache repeatedly used values, so the two examples would probably end up performing comparably.

Reference the following rules of thumb:

Make it work, make it right, make it fast... in that order. - Kent Beck

The First Rule Of Optimization: Don't.

The Second Rule Of Optimization: Don't... yet.

The Third Rule of Optimization: Profile Before Optimizing

Premature Optimization is the root of all evil. - Donald Knuth

In most cases, >90% of your program's time will be spent in <10% of the code, and without profiling your code, you have no idea which 10% that is. So don't even worry about it until you get feedback; it's much more valuable to optimize for programmer time than run time.


答: Variables are essentially free, but the function call has an unknown cost, so always go with the variable.</p>


答:
It is usually more efficient to store a computed value in a local variable, assuming your compiler didn't already optimize that for you.  In fact, sometimes this is built into a function itself, in a technique called memoization.

However, most of the time, the efficiency gain is small enough to be considered negligible.  Readability should usually be your primary concern after correctness.

That being said, using a local variable also often happens to make it more readable, giving you the best of both worlds.  Using your example:

```<code>const char* text = pLISTBOX->GetItemData(SelectedIndex);
pSTATIC_A->SetWindowText(text);
pSTATIC_B->SetWindowText(text);
pEDIT_BOX_A->SetWindowText(text);
pEDIT_BOX_B->SetWindowText(text);
</code>```

This is much more clear to a human reader.  Not only do you not have to read that long function call on every line, it is explicitly clear that all the widgets are receiving the exact same text.

Body:
It is usually more efficient to store a computed value in a local variable, assuming your compiler didn't already optimize that for you.  In fact, sometimes this is built into a function itself, in a technique called memoization.

However, most of the time, the efficiency gain is small enough to be considered negligible.  Readability should usually be your primary concern after correctness.

That being said, using a local variable also often happens to make it more readable, giving you the best of both worlds.  Using your example:

const char* text = pLISTBOX->GetItemData(SelectedIndex);
pSTATIC_A->SetWindowText(text);
pSTATIC_B->SetWindowText(text);
pEDIT_BOX_A->SetWindowText(text);
pEDIT_BOX_B->SetWindowText(text);

This is much more clear to a human reader.  Not only do you not have to read that long function call on every line, it is explicitly clear that all the widgets are receiving the exact same text.


问:
Deliverables in a software development project
Following a standard framework of project management, for a software development project we will provide deliverables (documents and software) at the end of each month :

My question is:

From May to June, while software is in development, what would be the deliverable for each month?

Each document starts as version 1.0. Is it possible to deliver same document one or two months later as version 2.0? Because it could happen changes on the way.

Users and clients ask me they want to see something as deliverable for each month, so they won't feel that the project is going without direction.

答:
As you said changes could happen along the way, would it be possible to shorten the cycle time to just 1 - 2 weeks and not wait until the end of each month? This will give user something to see as you're developing the software and also user can give some feedback more quickly. This will make them feel that they visually see something changed, and not see waiting nervously at the end of each month.  So you can have a short meeting to let them know what will be deliverables for each week or two weeks. This is because I think small features doesn't have to be the whole month to complete. If the task is too big you could slice it and break it down to smaller ones. Then users will think they have seen a lot more than they expect.

And I think version number is just the thing you need to agree with the users. Smaller changes i would call it 1.1.1 and goes up every week to 1.1.2 then if the end of each month you can certainly raise to 1.2 or 1.3.


问:
How to create high quality code producing teams? (as a group leader)
I come with a clear agenda on how to code correctly. I used to be a team leader, and I managed using significant amount of mentoring to create a team that creates high quality code.

Now I have 3 teams under me, each one has its own team leader. My time is mostly spent on strategic meetings and I can't devote enough of it to mentor my teams.

Once I do get to see code or design, I usually finds flaws in it, but I get to see little of that and I am afraid that all the code I can not see is designed or written poorly.

How can I make sure my teams produce great code?

Note: I am not in the position to fire anyone.

答:
Can you trust your team leader on each team? Are they good enough so you could trust to look after the codebase? If so, I guess you could have each of your team leaders to pair with the developers to kind of control the quality of the code. After pairing for a while your whole team should be familiar the coding style or standard of the code you're looking for. This will help you delegate your work to your team leaders as well. And if you have some time then come and pair with the developer or organise some code review session. This will help spreading out the standard you're looking for faster than pair with each one of them.

Or you could mix people who you can trust that they are strong and have them paired with the other junior developers.

Or one thing that I find the most interesting is coding-dojo session.


答:
People often confuse quality control (testing) with its sibling quality assurance. (See QaIsNotQc)  The latter is about the processes that assure that the product (in this case code) is of a high quality.

Accepting and understanding quality assurance processes is key.  This often has the scary (at least to developers) concepts of governance, ISO, CMM, and the like.

Use tools (sonar, pmd, findbugs, checkstyle and the like) that help identify problems with code.  Sonar in particular has a technical debt plugin.  Use it, keep that number low.  Sonar has a nice dashboard that managers can look at and go "oh, that's ugly."

Remember also from your days as a developer the negative impacts on code quality.  Shortened time lines, poor estimates, over commitments.  Strive to make sure these things don't happen.  Schedule time for cleanup of code.

Title: How to create high quality code producing teams? (as a group leader)

Body:
I come with a clear agenda on how to code correctly. I used to be a team leader, and I managed using significant amount of mentoring to create a team that creates high quality code.

Now I have 3 teams under me, each one has its own team leader. My time is mostly spent on strategic meetings and I can't devote enough of it to mentor my teams.

Once I do get to see code or design, I usually finds flaws in it, but I get to see little of that and I am afraid that all the code I can not see is designed or written poorly.

How can I make sure my teams produce great code?

Note: I am not in the position to fire anyone.


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答:
Early arcade games.

Completely restricted by memory, processing power, I/O ...

What those programmers achieved in this environment was amazing.

E.g. Pacman - Perfect. Still playable after all these years.

ContentLicense: CC BY-SA 2.5


答: The best way to improve quality is to offer incentive. The carrot always works better than the stick for motivation. Give the programmers an incentive to improve their quality, find their own bugs, produce elegant code. You have 3 teams, make it a competition. Get them to code swap and debug each others code, then have some sort of awards for most bugs squashed, least bugs produced, etc. Make it something they want to do.</p>


问:
Distributed SCRUM team issues: The work environment
One interesting issue appeared for me today. In a distributed SCRUM team when do you start enforcing an unitary work environment in terms of code format, IDE plugins (checkstyle & co), VCS, CI? The team is in an exploratory phase and thegoal is not production quality code but rather proof-of-concept. Isn't it an overhead to enforce some common coding rules "a priori" - before the team members decide which are really relevant for their future work? Using this kind of tools is for sure a huge benefit because they act as an heuristic to minimize the technical debt but enforcing rules as "no trailng spaces" that really break the Jenkins build seems for me an overkill for a phase that should be focused rather on ice-beaking than on creating production code.

Mention 1: the prototypes create will be thrown away

Mention 2: although I wish that everything should be done right from the beginning - I m totally aware that it is not 100% possible.

答:
Any IDE that doesn't make you develop faster isn't a tool, it's a
boat anchor.  Throw it overboard and never look back.

If you already have a CI infrastructure, use it from day 1.  You'll thank yourself later, even if you really succeed in throwing out your prototype code.

Conversely, do not waste time setting up a CI system if you don't have one.  The cost is too high, and you really do hope to start over from scratch.

Start with a VCS on day 1.  Period.


问:
In agile development, should I try persistence in flat file before database?
Somebody explained to me that since in agile development, policy and the application logic should be more important than details such as persistence method, persistence decision should be taken at the end. So it might be a good idea to start with simpler persistence such as flat files, until we reach the point the weakness of this method become apparent, and only then we change the persistence, e.g. by using relational database.

Is this true, or did I misunderstood the concept? Is this how agile team usually build application? What are the rationales for it and when I should not take this approach?

答:
Flat files are not simple!

They allow storage and that is all. The structure of the data, access paths etc. are all up to you, and, there are numerous ways to get this wrong.

There are reasons databases exist and one of them is to make things simpler for developers.

Most of my development is done for large systems within large companies. We always have a complete and well thought out data model before we procede with any further design or development. A data model helps you understand your problem and allows for a clean implementation.

Forgotten data items, mismatched data structures and other nightmares can all be avoided by producing a data model up front.

You can leave your actual choice of database technology till after the data model. But most "persistence" technologies are closely bound programming and even design styles. If you code for a relational database, and later decide to switch to a cloudy key value thingy you will need to completely re-write half your code.

If you start with flat files and switch to a relational DB you will probably end up throwing away half your code as your developers will have wasted their time implementing a piss poor database.


答: You know the answer. You've used mentoring in the past, mentoring has worked well. Strategic meetings are preventing you from doing mentoring. Cut down on the strategic meetings to do mentoring well. If you can't cut them, or delay them, or delegate them then you need to decide how to balance your time. What matters more?</p>


问:
Write tests for unit tests in TDD?
In an answer to another question, I suggested creating a randomized value for input to a specific method.  In my experience this has been useful for making tests more readable and it lets you skip the "trivial phase" where you hardcode specific results in a method.

Here's the unit test code pasted from the other answer, for quick reference:

```<code>[Test]
public void FullHouseReturnsTrue()
{
    var roll = AnyFullHouse();

    Assert.That(sut.IsFullHouse(roll));
}
[Test]
public void StraightReturnsFalse()
{
    var roll = AnyStraight();

    Assert.That(sut.IsFullHouse(roll), Is.False);
}
</code>```

A couple of comments in response suggested that this strategy would not work well, because the
helper method would need to be tested also.  In my experience, I've never had a need to test methods like this, since creating the corresponding production code also tests my test code.

Do AnyStraight() and AnyFullHouse() need to have their own unit tests?  If so, how do you solve the chicken-and-egg problem that presents?

EDIT

Would I still want to create dedicated unit tests for the AnyFullHouse algorithm if I inlined the method?

```<code>[Test]
public void FullHouseReturnsTrue()
{
    var roll = listOfHardCodedFullHouseRolls[_random.Next(0, listOfHardCodedFullHouseRolls.Length)];

    Assert.That(sut.IsFullHouse(roll));
}
</code>```

答:
Test suites like PHPUnit and JUnit, etc, are developed using the same TDD principles (and are usually tested against themselves).

Of course, this means that there is a minimal bootstrap suite required, but by taking an axiomatic approach means you can easily build up from simple assertions like "true === true" and "0 !== false".

In your case, you simply need to isolate the helpers and test them - it's not really a chicken and egg, more of an inception: you need to go deeper.

Alternatively, you could assume that the helpers are correct - but then that limits your assumed confidence in your tests, and therefore limits the value of them.

Title: Write tests for unit tests in TDD?


答:
Why randomize the values? Having helper fields of AnyStraight or AnyFullHouse with hardcoded values is just as readable, still provides the reduction in magic values, and reduces the chance of error in your randomization (as well as guaranteeing that your tests are repeatable).

In my experience, as soon as your tests are not repeatable, people make excuses as to why they fail. Actual bugs are ignored and your tests are quickly ignored for not catching the bugs. Don't start down that slope.

Title: Write tests for unit tests in TDD?

Body:
In an answer to another question, I suggested creating a randomized value for input to a specific method.  In my experience this has been useful for making tests more readable and it lets you skip the "trivial phase" where you hardcode specific results in a method.

Here's the unit test code pasted from the other answer, for quick reference:

```<code>[Test]
public void FullHouseReturnsTrue()
{
    var roll = AnyFullHouse();

    Assert.That(sut.IsFullHouse(roll));
}
[Test]
public void StraightReturnsFalse()
{
    var roll = AnyStraight();

    Assert.That(sut.IsFullHouse(roll), Is.False);
}
</code>```

A couple of comments in response suggested that this strategy would not work well, because the
helper method would need to be tested also.  In my experience, I've never had a need to test methods like this, since creating the corresponding production code also tests my test code.

Do AnyStraight() and AnyFullHouse() need to have their own unit tests?  If so, how do you solve the chicken-and-egg problem that presents?

EDIT

Would I still want to create dedicated unit tests for the AnyFullHouse algorithm if I inlined the method?

```<code>[Test]
public void FullHouseReturnsTrue()
{
    var roll = listOfHardCodedFullHouseRolls[_random.Next(0, listOfHardCodedFullHouseRolls.Length)];

    Assert.That(sut.IsFullHouse(roll));
}
</code>```


问:
Why don't we use a class and its static members to do what a singleton does?
In Java,C++,Objective C, C#, and all other similar OOP languages,

Why don't we use a class with static methods and vars instead of going through a singleton syntax having to deal with various scenarios ?

答:
This question has already be answered here

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.


问:
How have you made unit testing more enjoyable?
If you've always loved unit testing, good for you! But for the unfortunate ones who weren't born with a liking for it, how have you managed to make this task more enjoyable ?

This is not a "what is the right way to unit test" question. I simply want to know little personal tricks that reduce the boredom (dare I say) of writing unit tests.

答:
For one, I almost never just sit there and write unit tests. Unit tests are a means to an end, not an end in themselves. They are a way of answering "does this code do the basic task that it is supposed to."

For instance, some people will write a function, and then open an interactive session to test it out on a few values and make sure it's working:

```<code>def fact x
  if x == 0
    1
  else
    x * fact(x-1)
  end
end

>> fact 10
=> 3628800
>> fact 7
=> 5040
</code>```

But now you discover a bug:

```<code>>> fact -1
SystemStackError: stack level too deep
    from (irb):2:in `fact'
    from (irb):5:in `fact'
    from (irb):10
</code>```

So you fix it:

```<code>def fact x
  if x < 0
    raise "Can't take the factorial of a negative number"
  elsif x == 0
    1
  else
    x * fact(x-1)
  end
end

>> fact -1
RuntimeError: Can't take the factorial of a negative number
    from (irb):3:in `fact'
    from (irb):10
</code>```

But now you really ought to test to make sure it still works:

```<code>>> fact 10
=> 3628800
>> fact 7
=> 5040
</code>```

As you can see, you keep on repeating the same tests... and you have to compare the results visually. Unit testing is a way of avoiding the repetition in this case; it reduces how much work you need to do. And while this is a silly little example, in the real world, it becomes more and more important, and more and more difficult to test manually. What this means, of course, is that people simply don't test the individual components; they just test the whole program. But then bugs crop up, and they're much harder to find. Or bugs happen, and they're fixed, but someone introduces the same bug all over again, because no one added a test case to make sure that didn't happen. Or someone looks at a big piece of code, and says "I have no idea what this is supposed to do, since it's not documented and has no tests... if I fix this bug, I have no idea if I'll break something else depending on it; maybe I'll just rewrite this from scratch."

Unit tests reduce all of the extra work in these cases. The best way to make them fun is to make sure that people understand all of the work that they are replacing, and the extra flexibility that comes from knowing what each piece of code is supposed to do. To some degree, people need to have a bit more experience with writing and maintaining a large code base to understand how important unit testing can be; if all of their code is something they write once and throw away, they'll never quite get it.

And unit tests shouldn't be written after the fact, as an extra chore once you have code that you "know" already works. Unit tests should be written first, or at the very least (since you sometimes forget to write them first) right after writing the code in question. This is called test-driven development, and it can help make your APIs better; if you write the tests that exercise the APIs first, you will learn where the APIs are a pain to use before you even write the code, and can redesign much more easily than if you only add the tests afterwards.

Body:
For one, I almost never just sit there and write unit tests. Unit tests are a means to an end, not an end in themselves. They are a way of answering "does this code do the basic task that it is supposed to."

For instance, some people will write a function, and then open an interactive session to test it out on a few values and make sure it's working:

def fact x
  if x == 0
    1
  else
    x * fact(x-1)
  end
end

>> fact 10
=> 3628800
>> fact 7
=> 5040

But now you discover a bug:

>> fact -1
SystemStackError: stack level too deep
    from (irb):2:in `fact'
    from (irb):5:in `fact'
    from (irb):10

So you fix it:

def fact x
  if x < 0
    raise "Can't take the factorial of a negative number"
  elsif x == 0
    1
  else
    x * fact(x-1)
  end
end

>> fact -1
RuntimeError: Can't take the factorial of a negative number
    from (irb):3:in `fact'
    from (irb):10

But now you really ought to test to make sure it still works:

>> fact 10
=> 3628800
>> fact 7
=> 5040

As you can see, you keep on repeating the same tests... and you have to compare the results visually. Unit testing is a way of avoiding the repetition in this case; it reduces how much work you need to do. And while this is a silly little example, in the real world, it becomes more and more important, and more and more difficult to test manually. What this means, of course, is that people simply don't test the individual components; they just test the whole program. But then bugs crop up, and they're much harder to find. Or bugs happen, and they're fixed, but someone introduces the same bug all over again, because no one added a test case to make sure that didn't happen. Or someone looks at a big piece of code, and says "I have no idea what this is supposed to do, since it's not documented and has no tests... if I fix this bug, I have no idea if I'll break something else depending on it; maybe I'll just rewrite this from scratch."

Unit tests reduce all of the extra work in these cases. The best way to make them fun is to make sure that people understand all of the work that they are replacing, and the extra flexibility that comes from knowing what each piece of code is supposed to do. To some degree, people need to have a bit more experience with writing and maintaining a large code base to understand how important unit testing can be; if all of their code is something they write once and throw away, they'll never quite get it.

And unit tests shouldn't be written after the fact, as an extra chore once you have code that you "know" already works. Unit tests should be written first, or at the very least (since you sometimes forget to write them first) right after writing the code in question. This is called test-driven development, and it can help make your APIs better; if you write the tests that exercise the APIs first, you will learn where the APIs are a pain to use before you even write the code, and can redesign much more easily than if you only add the tests afterwards.


答:
I would suggest start implementing the concept of a unitary work environment once the team's velocity starts to stabilize. This may cause some technical dept at the start of the project, but there is always technical dept at the start of any project. :)

I usually have success in allowing the self-organizational aspect of a team to come up with something which is appropriate for them and their requirements. Basically present the team with a description of a problem, like Jenkin Builds failing, and providing them with the opportunity to 'fix' it.

This usually results in a bare minimum implementation of a solution, just like Zachary Yates mentioned in his answer.

I would note it would count in your favor if you have someone of a senior technical skill level / position providing some subtle guidance, just to help the team to not get weird with what they decide to go with. :)

Title: Distributed SCRUM team issues: The work environment

Body:
One interesting issue appeared for me today. In a distributed SCRUM team when do you start enforcing an unitary work environment in terms of code format, IDE plugins (checkstyle & co), VCS, CI? The team is in an exploratory phase and thegoal is not production quality code but rather proof-of-concept. Isn't it an overhead to enforce some common coding rules "a priori" - before the team members decide which are really relevant for their future work? Using this kind of tools is for sure a huge benefit because they act as an heuristic to minimize the technical debt but enforcing rules as "no trailng spaces" that really break the Jenkins build seems for me an overkill for a phase that should be focused rather on ice-beaking than on creating production code.

Mention 1: the prototypes create will be thrown away

Mention 2: although I wish that everything should be done right from the beginning - I m totally aware that it is not 100% possible.


答:
First of all, let me say that I'm not a fan of either of these ideas -- global variables create a bevvy of problems regardless of whether they come in design pattern packaging or not.

That said, a singleton is (generally) externally instance based with the exception of its static Instance() method, meaning that you can participate to some degree in runtime polymorphism.  In other words, a singleton can implement an interface, inherit from some other class, or have another class inherit from it (I seriously don't recommend this last one).  Static methods are entirely procedural in nature so you can't do any of these object-oriented things with them.

The main advantage of singleton, as far as I'm concerned, is that it's somewhat easier to factor toward a better design if you're starting with a singleton than if you're starting with pure static classes that house state.  With the latter approach, your application architecture is about as flexible as a diamond and with singletons, its as flexible as, say, steel.  The singleton is slightly less bad, from a flexibility standpoint, and also slightly easier to fix.

There is another pattern, called monostate, in which all instances share internal static state but expose only instance methods.  If you've just gotta have your global variables, this is a nice way to prevent them from creating the hidden dependencies between your classes that tend to make singletons and static classes with state such a maintenance headache.

Title: Why don't we use a class and its static members to do what a singleton does?

Body:
In Java,C++,Objective C, C#, and all other similar OOP languages,

Why don't we use a class with static methods and vars instead of going through a singleton syntax having to deal with various scenarios ?


问:
If I hire you for "a day", how many hours are expected?
I've seen a lot of advice for freelance programmers which advocates quoting your rates in periods of a minimum of one day. That means that when someone asks your rate, you would say "$500 per day" rather than giving the equivalent hourly rate.

If I agree to do 10 days of programming work for a client at a particular daily rate, how many hours are expected of me per day? What happens if I do 6 hours of actual programming on Monday and then do 8 on Tuesday.. is that two "days" or "1.75 eight hour days" or what?

What's the standard?

答: I would say that if you do not work for a fixed price, than you just charge the amount of time you spend, including fractions of days (maybe 1/4 day increments?). The 10 days is then an estimate. If you work fixed price, where the 10 days is an estimate, you charge the 10 days however long it takes. I would say that 1 day is 8 hours, but this is from a European standpoint. </p>


问:
What is a good algorithm for priority allocation of work duties?
I am currently doing a project (in PHP) that has the following requirements:

There is a list of people, sorted in a certain priority. Work should be allocated to them by this priority. e.g. If the list is T1, T2, T3, T1 should be allocated work, before T2. And T2 is allocated work before T3. In the event that are only 2 pieces of work, only T1 and T2 are allocated.

Each piece of work has certain time requirements. So even if it is T1's turn to be allocated work, if none of the work is suitable for T1, T1 will be skipped and no work will be assigned to T1.

Some work is more suitable for some people. E.g. There are two work, W1 and W2. If T1 is more suitable for W2, W2 will be assigned to T1.

My current idea is to allocate work based on the people list, and use a A* Search to identify what is the best way to allocate the work to each person. But I thought that my reqt 1 and reqt 3 seems to have some conflicts.

Is this a sensible algorithm or are there problems with it that I don't see at this point?

答:
The problem you have here in general is called the Scheduling Problem and in its general form is NP-complete. In other words, it is a well-known problem for which there exists no efficient algorithm (yet, or maybe never).

The linked page (already mentioned in a comment before) refers to one specific variant called job shop scheduling. There are many different scheduling problems, which all come down to be NP-complete in some way.

In your case, however, I would seriously rethink about the need to have priorities. Job scheduling problems usually have hard dependencies (like job A needs to be finished for job B to be able to start). Priorities are a whole different problem dimension and will complicate your task tremendously - something which may not be worth it. It is hard enough, if you simply say that task T1 can only be performed by workers W1 or W2 - without the need to prefer W1.

One note if you check the literature: what in your case are workers are typically machines in the literature - think automation factories where T1,...,Tn tiles are produced by M1,...,Mm machines.

Also one of the first things to check is if you need to find the perfect solution at all. Generally, NP-completeness stems from the requirement that the best solution has to be found. In your description you write things like T1 will be skipped, which is normally not possible in the theoretical scheduling problem formulations. Given that you have no need to schedule all tasks, you may also not have a requirement to solve the problem optimally. In that case, you can either try to write a Greedy-like algorithm yourself or look at the research being done on approximation algorithms for scheduling. These algorithms have the advantage of being fast, but the disadvantage of not necessarily finding an optimal solution.


答:
If I quoted someone a rate by day, I would intend that cover however much (or little) work I did that day, which is to say it's so many dollars for 8 hours or any fraction of 8 hours.

I'd be really hesitant to quote by day, because mismatched expectations are likely.

Be clear about what your rate covers, and make sure both sides agree how to handle the example you gave.

Title: If I hire you for "a day", how many hours are expected?

Body:
I've seen a lot of advice for freelance programmers which advocates quoting your rates in periods of a minimum of one day. That means that when someone asks your rate, you would say "$500 per day" rather than giving the equivalent hourly rate.

If I agree to do 10 days of programming work for a client at a particular daily rate, how many hours are expected of me per day? What happens if I do 6 hours of actual programming on Monday and then do 8 on Tuesday.. is that two "days" or "1.75 eight hour days" or what?

What's the standard?


答:
In France, there are laws regulating the number of hours per day.

So it is common to quote by day and expect at least 7 hours.

Except for this, quoting by hour is not always the right solution because you're expected to prove what you did each hour, which looks like hyper micro management. It's ok for simple 2-days contracts, but definitely not for longer contracts.

By quoting per day, you expect some work every day, not every hour. And as we all know, we don't have the same productivity at every hour. Charging by day means we have an estimation of our productivity for every day. Not for every hour where it varies.


答:
For me the big difference is that a singleton is far more flexible.

I can use the getInstance() method as a factory. So if I want I can change the class to return a new instance every time instead of a single instance all the time if I find out that it is needed by my application.

If I want to do this with a class that only has static methods I have to refactor the whole application.

Also the getInstance() method can return another implementation (a subclass of the singleton) so I can change the implementation without changing my application.

BTW I also use sometimes classes with static methods if I'm sure that I don't need the above features.


答:
To answer the question "What's the standard?":
Based on what experience i have gained through partnerships with freelance workers (one being my fiance') the standard is influenced by the industry, the client base and geo-locations (country, state etc). According to them the best way to determine the standard would be to see what is the general norm of other programmers using your languages and tools doing similar work in a similar area.

What other freelancers have suggested is to either quote per hour or per effort-day - a days worth of work (not a days worth of hours). But i don't think many clients would go for the latter.


答:
First of all, this is a difficult question to answer because each country has different laws/work habits.

Secondly, I don't think paying for a days of work makes sense for programmers.

Imagine, you hire a photographer. That job would perhaps take an hour or two, maybe more. But because the photographer has travel time to the client, he/she can at most do one or two jobs pr. day. Therefore it would make sense for a photographer to bill for half a day, or a full day. In that case it makes sense to talk about how much it costs to hire a photographer for a day.

The majority of work I perform as a freelance programmer don't follow this pattern, as is the pattern of most of the freelance programmers people I know. The jobs I get hired to do takes from a week to many months, and I sit regularly at the client's office (and I do not charge for travel time). Therefore it makes much more sense to bill by the hour. That way, it is much easier for you to work extra (and get compensated) if you are pressed for time, and you can leave early (and the client doesn't get ripped off) if there is little work to do.

Sometimes the client could ask you to take part in a meeting at different location, but that is in my experience not that common.

Generally, the contracts I have been presented with, would state that I should get the client's approval if the amount of work would exceed some monthly threshold (about 160 hours of work).


问:
How do you deal with discovering bad and false code in your team?
Every year in january we process a big task with our system. While the performance during the task was above average the maintaince follow up is currently having a lot of trouble with jobs running too long and out of their respective time schedule. Therefore I am tasked with the optimization of those maintaince jobs and I am doing thusly the most thorough code review the system has ever seen. As I am good with analysing code I am also doing a lot of bug fixes.

This means I see lots and lots of bad or completely wrong code and implementations. My question is: How can I deal with that in front of my coworkers?

I hate it if I cause a bug (which I guess happens to everyone sometimes) and someone else fixes it without telling me about it. Because then I cannot learn from my mistake. On the other hand I do not want to be the guy on the team who is constantly nagging about how everyone else has to do his or her work. Also I am a bit wary of my own hubris. I do not want to find myself in the position that I start looking down on coworkers just because my biased mind thinks my code is superior. Currently I am not checking who has caused a bug I just fix it. I am not sure whether this is the best way to go.

I am a Junior level developer and English is not my mother tongue. Any advice (and grammar edits) are highly appreciated. The team follows the Rational Unified Process framework.

答:
This will depend on your company culture and processes. But personally I wouldn't just fix it for a number of reasons.

It may actually be correxct and my understanding might be wrong

It may be the lesser of two evils, it might be wrong but may prevent some other part failing altogether

It may not be worth the businesses time and money to fix it, there may be more important things for me to work on.

The preferable thing to do in this situation is raise a bug report. Note for some work this is necessary anyway e.g. for safety related work all faults probably need to be formally raised so that they can be safety assessed.


答:
On some projects, a process exists when you discover a potential problem in the code:

First tell the author or your project leader,

Report it in the issue tracker,

Wait for assignment of issue resolution to you or to another team member.

The general rule is to NOT fix a bug if not explicitely asked for. Some reasons for that are:

It costs time and you are not the best person in the project to decide how to balance between that time cost and the criticity of the bug.

If you don't know the code base enough, it may introduce bugs in parts that you didn't imagine

It is not a bug, it's a feature.

Title: How do you deal with discovering bad and false code in your team?

Body:
Every year in january we process a big task with our system. While the performance during the task was above average the maintaince follow up is currently having a lot of trouble with jobs running too long and out of their respective time schedule. Therefore I am tasked with the optimization of those maintaince jobs and I am doing thusly the most thorough code review the system has ever seen. As I am good with analysing code I am also doing a lot of bug fixes.

This means I see lots and lots of bad or completely wrong code and implementations. My question is: How can I deal with that in front of my coworkers?

I hate it if I cause a bug (which I guess happens to everyone sometimes) and someone else fixes it without telling me about it. Because then I cannot learn from my mistake. On the other hand I do not want to be the guy on the team who is constantly nagging about how everyone else has to do his or her work. Also I am a bit wary of my own hubris. I do not want to find myself in the position that I start looking down on coworkers just because my biased mind thinks my code is superior. Currently I am not checking who has caused a bug I just fix it. I am not sure whether this is the best way to go.

I am a Junior level developer and English is not my mother tongue. Any advice (and grammar edits) are highly appreciated. The team follows the Rational Unified Process framework.


答:
You may be in the perfect situation with this do-it-once-and-thoroughly code reviewing. As you are fixing bugs left and right, what you should do is keep note of the bug patterns/types. Do not tell individual developers (unless being asked) and also do not care about who wrote the code - just fix it and keep track of it.

Once you're done with your work walk up to your manager and tell him about the situation:

We have a lot of developers doing bad things in the code and they are
  probably not aware of how to do it better. During my review work in the recent weeks, I have kept track of the
  typical mistakes that have been made. Would it be possible to arrange
  a meeting with the developers in which we could discuss the most
  blatant problems in order to educate the whole team and dramatically
  reduce our error potential in the future?

That kind of win-situation will almost never be rejected by a manager and as you will present the error patterns you avoid offending or singling out any specific developer. You also reduce the amount of time you spent talking to others about their bugs and you ensure that everyone in the team is aware of such pitfalls afterwards.


问:
@Deprecated as of version x.y in JavaDoc
This question & its answers are useful but not sufficient for my problem.

My Question is if I want to add a javadoc as @Deprecated As of version x.y, replaced by {@link SomeClass} in my current file's javadoc then what should be the version no. in place of x.y ??

Let my current version is 1.2 & after CVS checkin it will be 1.3

答:
Nobody except you cares about the CVS revision numbers; they're an internal artifact of the mechanism you use (if you used Git instead, the revision IDs would be entirely different and without obvious sequence).

Instead, you should define versions in terms of releases where you say “this is a configuration of the code that it makes sense to use as a whole”, and it is those versions that you should refer to in documentation, especially for things like deprecation notices. After all, it is those versions that consumers of the API — the people who will be the consumers of the deprecation notices, and the software they create — will see. In terms of your revision control system, release versions are the sort of thing that it is usually best to model with a tag or label.

If you've not yet done a release, you don't need to deprecate anything. If you've got a release in the past, the deprecation notice should mention the next release version. (It shouldn't mention the version that's just released though; that should be regarded as a static artifact.)


问:
Helper static methods in TDD
I am creating an application which will be testable(unit + integration). In this application I have a FileHelper static class,

```<code>public static class FileHelper
{
    public static void ExtractZipFile(Stream zipStream, string location)
    {
        ..................................
    }
    public static void CreatePageFolderIfNotExist(string directory)
    {
        .................................................
    }

    .......................................................
    .......................................................
}
</code>```

But due to static I think it is not testable. How to make this class testable?

答:
To say that they're not testable is inaccurate. They're very testable, but they're not mockable and thus they are not test-friendly. That is, every time you test a unit of code that calls this method, you have to test the method. If the method is ever broken, many tests will fail and it won't be obvious why.

With that in mind, the solution is fairly obvious. Make it a non-static class, extract an interface with all the methods in and pass your helper into every class that needs it, preferably through the constructor, and preferably using an IOC Container.

```<code>public class FileHelper : IFileHelper
{
    public void ExtractZipFile(Stream zipStream, string location)
    {
        ..................................
    }

    public void CreatePageFolderIfNotExist(string directory)
    {
        .................................................
    }

    .......................................................
    .......................................................
}

public interface IFileHelper
{
    void ExtractZipFile(Stream zipStream, string location);
    void CreatePageFolderIfNotExist(string directory);

    .......................................................
    .......................................................
}

public class MyClass
{
     private readonly IFileHelper _fileHelper;

     public MyClass(IFileHelper fileHelper)
     {
         _fileHelper = fileHelper;
     }
}
</code>```

Title: Helper static methods in TDD

Body:
To say that they're not testable is inaccurate. They're very testable, but they're not mockable and thus they are not test-friendly. That is, every time you test a unit of code that calls this method, you have to test the method. If the method is ever broken, many tests will fail and it won't be obvious why.

With that in mind, the solution is fairly obvious. Make it a non-static class, extract an interface with all the methods in and pass your helper into every class that needs it, preferably through the constructor, and preferably using an IOC Container.

public class FileHelper : IFileHelper
{
    public void ExtractZipFile(Stream zipStream, string location)
    {
        ..................................
    }

    public void CreatePageFolderIfNotExist(string directory)
    {
        .................................................
    }

    .......................................................
    .......................................................
}

public interface IFileHelper
{
    void ExtractZipFile(Stream zipStream, string location);
    void CreatePageFolderIfNotExist(string directory);

    .......................................................
    .......................................................
}

public class MyClass
{
     private readonly IFileHelper _fileHelper;

     public MyClass(IFileHelper fileHelper)
     {
         _fileHelper = fileHelper;
     }
}


问:
What do I need to know re. Javascript frameworks?
I recently asked this question on SO, which quickly became downvoted and closed. Clearly I lack a deeper understanding of JS, which I'm hoping you'll help me fill here.

I'm a perfectly capable web developer and have built plenty of visually and functionally pleasing websites but am struggling to get to grips with how I should be handling JS.

Up until now, I've only really used jQuery for form validation or providing AJAX functionality to forms/other page elements.

There seems to be a lot of hype around JS frameworks - backbonejs, emberjs, etc, but when I look into them, it looks like they're just good for if you intend to build full applications in them. I'm happy using PHP/Symfony and just want to use JS to give my web applications a nice interactive/responsive 'feel'.

Are the aforementioned frameworks any use to me, or am I right in just sticking with jQuery?

答:
If you don't feel like you're doing stuff with Symphony/jQuery, that wasn't intended to do with those frameworks, stick to them.

If you feel like you have to bend time and space to make them do what you wan't they're probably the wrong tools.

I, for example, build GUIs for reporting tools (creating, editing, viewing) so I stick to ExtJS. But I wouldn't build a Company website with it.


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
Bloated development teams and terrible productivity in software companies.

This is a consequence of the common pattern in the business world: the importance of a manager is measured by the number of subordinates, therefore a manager's number one concern is not productivity but quite the opposite: poorer productivity is the best justification to hire more people.


答:
An alternative to pdr's solution is to pass the static function into the class that uses it as a delegate. This allows it to still be mocked out but slightly reduces the amount of boilerplate code</p>

```<code>//warning! code not tested
static public class FileHelper
{
    public static void ExtractZipFile(Stream zipStream, string location)
    {
         //do stuff
    }
}

public class MyClass
{
    public Action<Stream, string> ExtractZipFile = FileHelper.ExtractZipFile
    public void DoThing()
    {
         //stuff
         ExtractZipFile(mystream, mystring);
         //more stuff
     }
}

MyClassTest()
{
     var target = new MyClass()
     target.ExtractZipFile = (stream, loc) => MaybeVerifSomething(loc);
     target.DoThing();
     //Assert stuff
}
</code>```

Title: Helper static methods in TDD

Body:
I am creating an application which will be testable(unit + integration). In this application I have a FileHelper static class,

```<code>public static class FileHelper
{
    public static void ExtractZipFile(Stream zipStream, string location)
    {
        ..................................
    }
    public static void CreatePageFolderIfNotExist(string directory)
    {
        .................................................
    }

    .......................................................
    .......................................................
}
</code>```

But due to static I think it is not testable. How to make this class testable?

Body:
An alternative to pdr's solution is to pass the static function into the class that uses it as a delegate. This allows it to still be mocked out but slightly reduces the amount of boilerplate code

//warning! code not tested
static public class FileHelper
{
    public static void ExtractZipFile(Stream zipStream, string location)
    {
         //do stuff
    }
}

public class MyClass
{
    public Action<Stream, string> ExtractZipFile = FileHelper.ExtractZipFile
    public void DoThing()
    {
         //stuff
         ExtractZipFile(mystream, mystring);
         //more stuff
     }
}

MyClassTest()
{
     var target = new MyClass()
     target.ExtractZipFile = (stream, loc) => MaybeVerifSomething(loc);
     target.DoThing();
     //Assert stuff
}


答: Code review is never a one-person task. Code review happens with both the reviewer and the author present and looking at the code togehter (ideally), or communicating via tools (e.g., Review Board).  If you're not involving the author, you're not reviewing code, you're fixing bugs.  If you're fixing bugs, don't worry about the review aspects.


答:
It sounds like you're using the version control revision as part of your version number. As long as your VCS revision number increments (CVS's does) this isn't a terrible idea.

That said, you should have at least a couple of higher-order numbers in your revision number.

e.g. <major version>.<sprint number>.<CVS revision number>

Instead of <major version>.<CVS revision number>

That way, you can just give the <major version>.<sprint number> part in the javadoc comments - they supercede the CVS revision number anyway. If you don't use sprints, you can just use some arbitrary number that increments whenever you change the API, or for each new feature.

Title: @Deprecated as of version x.y in JavaDoc

Body:
This question & its answers are useful but not sufficient for my problem.

My Question is if I want to add a javadoc as @Deprecated As of version x.y, replaced by {@link SomeClass} in my current file's javadoc then what should be the version no. in place of x.y ??

Let my current version is 1.2 & after CVS checkin it will be 1.3


问:
Should we validate a state transition before attempting it in the State Pattern?
When applying the State Pattern illegal transitions should result in an exception being thrown (or at least that's what I understood from the pattern)

I know exceptions are for "unexpected behavior" where an action isn't supposed to happen. Errors would be more appropriate if the required action is common (ex: user enters a wrong password)

Now picture this, I have an admin panel where a list of orders are shown and each order has 3 buttons (Refund, Cancel, Reorder) where each one of them changes the state of the order if the operation is allowed.

The 3 buttons are enabled by default (I'm simplifying my case here as my real system is much more complex than that). Now a user can for example push the cancel button for an order with state (Cancelled) which is an invalid state transition.

Since I expected that this illegal transition action to occur would a validation before attempting to Cancel the line be more appropriate?

If I validate before transition do I still need exceptions in the model?

Is there a better approach to the whole problem (ignoring disabling the buttons and client side validation)

答:
Client-side measures can never solve such a problem. Even if you disable smth and/or place validation, it is still possible to send invalid requests.

In this case I would disable the Cancel button in the UI. When the server receives a request to change state, I would validate it at server-side, ignore the request if the state is invalid and send an error status back to client. depending on the situation, I would also show an error message like The order has already been canceled.


答:
It seems you can validate whether a transition is valid before attempting it. I think you should validate all possible transitions when showing the UI and disable the buttons that correspond to invalid transitions. Letting the user know what they can and can't do is a good thing.

Now, if you can't or don't want to do that, and so you expect invalid transitions to happen often, then I think you shouldn't use exceptions. Instead, you might want to use pattern similar to the various TryParse() methods in .Net, where the returned value indicates success or failure.

If you decide to have separate methods for validation and actually performing the transition (this is called Tester-Doer pattern), then you should still use exceptions if invalid transition is attempted, because you can't guarantee that the programmer that uses this code calls the Tester method. This pattern is also dangerous in multi-threaded environments, because the situation can actually change after the call to the Tester method, but before the call to the Doer method.

Title: Should we validate a state transition before attempting it in the State Pattern?

Body:
When applying the State Pattern illegal transitions should result in an exception being thrown (or at least that's what I understood from the pattern)

I know exceptions are for "unexpected behavior" where an action isn't supposed to happen. Errors would be more appropriate if the required action is common (ex: user enters a wrong password)

Now picture this, I have an admin panel where a list of orders are shown and each order has 3 buttons (Refund, Cancel, Reorder) where each one of them changes the state of the order if the operation is allowed.

The 3 buttons are enabled by default (I'm simplifying my case here as my real system is much more complex than that). Now a user can for example push the cancel button for an order with state (Cancelled) which is an invalid state transition.

Since I expected that this illegal transition action to occur would a validation before attempting to Cancel the line be more appropriate?

If I validate before transition do I still need exceptions in the model?

Is there a better approach to the whole problem (ignoring disabling the buttons and client side validation)


问:
How to write tasks in Jira when using Scrum?
I am going to start a new project using Scrum and Jira and I have some questions regarding how to write proper tasks in Jira.

From what I understand user stories are small non-technical descriptions written by the stakeholders (ideally) that can have the form: As a user I want to order monkies so I can earn money.

However these tasks must be elaborated with requirements, technical requirements etc. My question is: How do you write such tasks in Jira properly, and do I have the right understanding of user stories.

Should I create user stories as super tasks and then create subtasks with the actual tasks/requirements?

Should I estimate super tasks/user stories, or only the sub tasks?

答:
```<code>Should I create user stories as super tasks and then create subtasks with the actual
tasks/requirements?
</code>```

Yes. It is very convenient because you can easily see why a certain task was performed. Besides, this approaches lets you to track the progress of every user story.

```<code>Should I estimate super tasks/user stories, or only the sub tasks?
</code>```

From my experience, the smaller a task is the easier is to estimate it. Small estimations also tend to be more accurate. The estimation of a user story  is the sum of its subtasks' estimations. Thus the story estimation is more fair, accurate and sensible.

P.S. Here are some useful links on scrum and Jira:

With agile, what do when a user story doesn't get completed in an iteration?

How do you keep track of a requirements document on an agile team?

Body:
Should I create user stories as super tasks and then create subtasks with the actual
tasks/requirements?

Yes. It is very convenient because you can easily see why a certain task was performed. Besides, this approaches lets you to track the progress of every user story.

Should I estimate super tasks/user stories, or only the sub tasks?

From my experience, the smaller a task is the easier is to estimate it. Small estimations also tend to be more accurate. The estimation of a user story  is the sum of its subtasks' estimations. Thus the story estimation is more fair, accurate and sensible.

P.S. Here are some useful links on scrum and Jira:

With agile, what do when a user story doesn't get completed in an iteration?

How do you keep track of a requirements document on an agile team?


问:
Choosing a open source licence for embedded system library
I'm writing a few libraries that I want to release as open source projects, but I want to find a licence that means I'll receive the credit when it is used in a project. Im not fussed about anything else, if people want to profit off of it then thats fine. So what licence is most appropriate? The only factor for me is that I receive the credit for producing the library if it is ever used. </p>

答:
The original four-clause BSD license is most probably what you are looking for. It allows (not forbids) commercial use, but both source and binary distributions have to show your copyright. In contrast to other variants of this license (e.g. the three-clause variant), it contains an "advertising clause" requiring users of this code to name you as a contributor.
However, this four-clause BSD license is considered not compatible to the GPL due to the advertising clause, so you may want to use the three-clause variant (which still requires acknowledging your copyright).</p>


问:
I have a previous invention (software / framework) that I plan to use on my new job. What happens to my copyright if I improve it during the job?
I have filled that standard form where you list your previous inventions before starting your new job so the employer is legally aware you have the copyright over them. But if I want to use this invention (software code / framework) in my new job, would they have any copyright claims on it if for example I change / improve something on my code while working for them?

I have heard something like a shared ownership. Something like: you would own what was done before and employer would own any improvements you did on it while employed. That kind of sucks and take away any incentive you would have to do improvements on your product since once improved, the improvement is gone. :(

Has anyone gone through this situation before and could share some ideas so I can protect my code?

答:
It really depends on what is in your employment contract.

I had to ask to have a specific clause added to my contract that allows me to work on open-source projects in my spare time. The original contract claimed all copyrighted material that I produced during the period of my employment, whether I was at work or not.

If it is not explicitly stated in your contract, local labour laws would likely apply, and you'd need to consult a lawyer. You might need to anyway - there are certain rights that you simply can't sign away, no matter what a contract says.


答:
If you're in a client/server scenario, then the server should always update any requests (in this case, state transition requests) that it receives from the client.

Your server-side implementation needs to be robust enough to handle invalid requests without getting into an invalid state or corrupting data. There are various ways to handle this - e.g. the memento pattern.

Although the consequences of invalid transitions are less severe, your client-side implementation ought to prevent users from even trying invalid transitions. Disabling the buttons for invalid transitions is typical, or you might even want to remove them completely.

Showing an error message is the final fallback option when something goes wrong. In this case, that would be either the client/server state getting out of sync, or a bug in the client code where it thinks a transition is valid when it isn't.

As far as working out which transitions are valid on the client-side, you could just have each state hold a list of which states it can transition to.


答:
Have a look at this Wikipedia article regarding Free and OSS licenses and that should get you started in the right direction.

Creative Commons has a number of licenses you may be interested in since attribution seems to be your biggest concern.

Title: Choosing a open source licence for embedded system library

Body: I'm writing a few libraries that I want to release as open source projects, but I want to find a licence that means I'll receive the credit when it is used in a project. Im not fussed about anything else, if people want to profit off of it then thats fine. So what licence is most appropriate? The only factor for me is that I receive the credit for producing the library if it is ever used. </p>


答:
Maybe the best thing to do is to open source it first, with maybe an MIT license. Then, use it  at your new job. The new employer wouldn't be able to claim ownership of an open source project that was created\released before your employment began.

Shared ownership sounds messy. I can't imagine that scenario being best for you, but I can see the company getting the better end of that arrangement.

Title: I have a previous invention (software / framework) that I plan to use on my new job. What happens to my copyright if I improve it during the job?

Body:
I have filled that standard form where you list your previous inventions before starting your new job so the employer is legally aware you have the copyright over them. But if I want to use this invention (software code / framework) in my new job, would they have any copyright claims on it if for example I change / improve something on my code while working for them?

I have heard something like a shared ownership. Something like: you would own what was done before and employer would own any improvements you did on it while employed. That kind of sucks and take away any incentive you would have to do improvements on your product since once improved, the improvement is gone. :(

Has anyone gone through this situation before and could share some ideas so I can protect my code?


答:
Apparently, you want to retain ownership of that software.

If this is so, simply do not sign a contract that takes it away from you.

The normal case, however, is, that what you produce during your working hours is owned by your employer. Your renumeration should be compensation for that.

Maybe you can reach an agreement, where the hours you work on imporvement of that invention are not counted (and paid) as working hours. Instead, your employer agrees to buy (a license for) the improved version for approximately the same amount as you woulod make in those hours.


答:
I would model this as a Constraint Satisfaction Problem where your goal is to find a configuration of assignments that fulfills your requirements.  This is generally an NP-complete problem, but depending on the size of your data set it could be possible to find a solution.

Here's a description of how to go about solving that problem with a Backtracking-style algorithm

Let W be a set of work assignments such as { W1, W2, ..., Wn }

For every assignment, assign the worker most suitable to it (as per
requirement 2)

For all remaining assignments, attempt to schedule it
to the highest priority available worker

Continue to the next unassigned assignment until they are all assigned or until no workers are available at that time

If no solution was found, go back one step and try again with the next available worker

It's very similar to how Sudoku grids are solved, which are often modeled as CSPs themselves.  This is only possible because assignments are not prerequisites to each other according to your description, which makes it less relevant to model the problem as a scheduling problem.

Good luck!

Title: What is a good algorithm for priority allocation of work duties?

Body:
I am currently doing a project (in PHP) that has the following requirements:

There is a list of people, sorted in a certain priority. Work should be allocated to them by this priority. e.g. If the list is T1, T2, T3, T1 should be allocated work, before T2. And T2 is allocated work before T3. In the event that are only 2 pieces of work, only T1 and T2 are allocated.

Each piece of work has certain time requirements. So even if it is T1's turn to be allocated work, if none of the work is suitable for T1, T1 will be skipped and no work will be assigned to T1.

Some work is more suitable for some people. E.g. There are two work, W1 and W2. If T1 is more suitable for W2, W2 will be assigned to T1.

My current idea is to allocate work based on the people list, and use a A* Search to identify what is the best way to allocate the work to each person. But I thought that my reqt 1 and reqt 3 seems to have some conflicts.

Is this a sensible algorithm or are there problems with it that I don't see at this point?


问:
normal order evaluation -vs- applicative order evaluation
I am going through Abelson and Sussman (Structure and Interpretation
of Computer Programs) and I am a little confused about when normal order evaluation is used and when applicative order evaluation is used.

This sentence throws me off:

Lisp uses applicative-order evaluation partly because of the additional efficiency obtained from avoiding multiple evaluations of expressions suich as those illustrated with (+5 1) and (*5 2) above and, more significantly, because normal-order evaluation becomes much more complicated to deal with when we leave the realm of procedures that can be modeled by substitution. [emphasis added]

on page 17 paragraph 1.

However, in exercise 1.6, the implication is that Lisp uses normal order evaluation for primitives but applicative order evaluation for complex procedures.

Could someone clarify?

答:
because normal-order evaluation becomes much more complicated to deal
  with when we leave the realm of procedures that can be modeled by
  substitution.

To put this differently, consider

```<code>let x = (print "ha", print "ho") in x
</code>```

The question is, does this print a) nothing, b) ha c) ho d) haho?

Does it do this only the first time, or every time x is used?

With normal order evaluation, it would depend on how much of the expression was demanded, like:

```<code>y = fst x
</code>```

This is one reason why non-strict languages (i.e. using a form of normal order evaluation that can be modeled by substitution) tend to be pure, i.e. side effects in expressions are not allowed.

Body:
because normal-order evaluation becomes much more complicated to deal
  with when we leave the realm of procedures that can be modeled by
  substitution.

To put this differently, consider

let x = (print "ha", print "ho") in x

The question is, does this print a) nothing, b) ha c) ho d) haho?

Does it do this only the first time, or every time x is used?

With normal order evaluation, it would depend on how much of the expression was demanded, like:

y = fst x

This is one reason why non-strict languages (i.e. using a form of normal order evaluation that can be modeled by substitution) tend to be pure, i.e. side effects in expressions are not allowed.


问:
Good serialization solution for communication between Python AND Haskell programs?
I found this:

http://msgpack.org/

But.. I've never used it, so I don't know what whether it is much good. Anybody has proposals?

Basic requirements:

serialize as many data structures used typically in both languages as possible, have no problem with nesting

as reliable/unbuggy as possible

high performance is nice to have, but not critical

as simple as possible to use, but not simpler

答:
I can't speak for that msgpack you linked, but the haskell usage looks quite simple and it sounds performant, I would definitely give it a shot until I found it inadequate.

Also there is protobuff which is a great protocol and haskell has a lib for it here:
http://hackage.haskell.org/package/hprotoc

Alternatively you can always just use a more common serialization format: JSON is well supported on both sides.

If you are familiar with Attoparsec, and have a limited object structure you want to send back and forth, you could write your own Attoparsec parser in very quickly on the haskell side, but if it needs to go the other way too you would then have to do similar on Python which would take a lot more work.

I would generally avoid hand-writing this though if it were me, JSON is well supported and protobuff is a good standard as well (though I've not used it in Haskell so I can't vouch for the quality of it's APIs in Haskell)


问:
How many lines per class is too many in Java?
In your experience, what is a useful rule of thumb for how many lines of code are too many for one class in Java?

To be clear, I know that number of lines is not even close to the real standard to use for what should be in a particular class and what shouldn't.  Classes should be designed according to proper OOP philosophies (encapsulation, etc.) in mind.  That said, a rule of thumb could provide a useful starting point for refactoring considerations (i.e. "Hmmm, this class has >n lines of code; it's probably unreadable and doing a lousy job of encapsulation, so I might want to see if it should be refactored at some point").

On the flip side, perhaps have you encountered examples of very large classes that still obeyed OOP design well and were readable and maintainable despite their length?

Here's a related, non-duplicate question about lines per function.

答:
I'm sorry but I'm very surprised that many answers state that it "doesn't really matter".  It very MUCH matters how many lines are in a class.  Why?  Consider these principles in writing good Java code...

Testability

Cohesion

Coupling

Understandability

Classes with lots of lines in them will most likely violate all of those principles.

For those who have stated it "doesn't really matter"...how much fun has it been for you to try and understand a class that has 5000+ lines in it?  Or, to modify it?  If you say that's fun, you've got a strange affinity towards pain...

My comments are based off of reading and studying such authors as Martin Fowler, Joshua Bloch and Misko Hevery.  They are excellent resources to consult for writing good Java code.

Do the next guy (which could be you in a couple of years) a favor and strive to write classes that have fewer rather than more lines in them.

ContentLicense: CC BY-SA 4.0


问:
Should a programmer always be able to do everything a user could do?
Should a programmer be able to perform all operations programmatically on a object that a user could do?

By way of example, I'm working with a list selection object. To populate the list List.AddItem(itemData) is repeatedly called until it is built. A user can then:

View the entire list

Select a single item from the list

However there is no programmatic way to list all of the items. Nor is there an easy way to set an item as selected. You can if you keep track of what was added to the list and call List.SelectItem(itemData). This means you'd have to maintain an independent list of the items separate from the object, which could cause it's own problem (This bit of ugliness isn't necessary to the question, but part of the motivation).

In general if a user can get information about an object or perform an action on an object should this same functionality be available to the programmer and not hidden? I suspect the answer is "yes" but recognized I may be overgeneralizing from this one case that I'm unhappy with.

答:
What you're asking is really "Should the programmer have access to the applications state?".  I would argue yes.  The situation you're describing lacks a clear separation between the model and view of your application.  Specifically the state of the model seems to be wrapped up in view code.

With better separation of concerns you would have a model that held a list object, and a view that then reflected that list.  You could then manipulate the list as you chose.

So to answer your original question, I would say YES the programmer should be able to do anything the user could do, because the full state of the application should be held in the model where the programmer has access.  The user should simply be interacting with a view that exposes ways to interact with the model to which a developer has full access.


问:
How to make an ASP.NET MVC site modular
I'm in the planning stage for an employee intranet system to be built with ASP.NET MVC 4. We'd like the site to consist of separate "modules", each of which provides a different feature: messaging, payroll changes, etc. I'd like these modules to be able to be enabled or disabled at compile time. The homepage will display some kind of navigation that will link to each module that is loaded.

That's easy so far, but I don't want the navigation feature to have to know about the modules beforehand. In other words, I want the modules to be dynamically discoverable; I want to be able to write the code for a new module and then have a link added to the navigation bar with no code changes anywhere else in the source. Each module should have some way of registering itself with the navigation bar, and--more importantly--this should be done for each module as it's loaded.

I believe that this precludes using MVC's Areas, since those are designed for the case when the layout of the site is known beforehand. MEF seems like it might be appropriate, although people seem to have had mixed success in combining MEF with MVC. Is MEF actually the way to go here, or is there a better way to accomplish what I need?

答: You may want to look at using MEF with MVC. This would give you the ability to Add - Take Away  as needed without recompiling or deploying. As usual, Scott is a good place to start: http://www.hanselman.com/blog/ExtendingNerdDinnerAddingMEFAndPluginsToASPNETMVC.aspx</p>

Title: How to make an ASP.NET MVC site modular


问:
Why are some languages (e.g Visual Basic) considered more enterprise ready than others (Python)
Reading about various techie sites, there is often a feeling that Microsoft Languages / Oracle etc. are considered "enterprise ready", while there seems to be more doubt about languages such as Python or Ruby.

Why is this?

Do Microsoft languages actually have less security holes or not?

答:
Some languages are designed to limit the programmer's ability to shoot himself in the foot.  Traditional language concepts perceived (in my experience) to reduce risk are:

Strong, static type systems

Object-Orientation

Compilation

There's also the fact that Microsoft/Oracle/etc often provide services other than the programming language.  For example, if the company uses an Oracle database, then Java might appear as a less risky solution.

Last but not least, these companies offer corporate support not necessarily available for other technology.  Buying into the whole Azure thing as a company guarantees you support and you'll probably be using a .NET language to build on top of the platform.

Then again, it might just be because managers and other non-techies perceive other companies as more "serious", just like companies prefer to pay for products that have free, superior alternatives (think Perforce vs Git).


问:
When to write Unit Tests : Is there any or list of terms to take right decision
To write Unit Tests we have to write extra bits of code.
For several projects we do Unit Tests and for several projects we do not.

As a Team Leader I face trouble to make the right decision.

Is there any or list of terms by which I can take the right decision whether we will do Unit tests or not?

EDIT: Please provide a comment while down voting the question. It will help me to improve my question.

答:
As a rule of thumb I would argue that you should write unit tests for all code you write. There may be cases where you don't need to unit test something, but I would have thought these would be unusual and unlikely.

The advantage to having tests for your code is you know when some functionality changes, of course you need to have good coverage and well written tests that you have confidence in. Just having a test cover some code isn't a guarantee that your code is correct / flawless. In fact a bad test can be worse than no test at all. But that's really a different question.

I pity the fool who doesn't write unit tests

any tests are better than zero tests. And isn't unit testing just a barely more formal way of doing the ad-hoc testing we've been doing all along? I think Fowler said it best:

Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead.
I encourage developers to see the value of unit testing; I urge them to get into the habit of writing structured tests alongside their code. That small change in mindset could eventually lead to bigger shifts like test-first development-- but you have to crawl before you can sprint.


答:
Mostly it's because they cost money.  When you build a product to make money, you have a tendency to respond to the needs of the people with the money.  Enterprises like being able to throw money at a problem to get it solved.

Conversely, if you are a large business and wanted to get a feature put into free software, you can't just pay a company like Microsoft to put it in.  You generally must hire in-house expertise to implement it, or convince the community on the merits.  That provides more flexibility at the expense of requiring more of a partner relationship than a client relationship with your software provider.

In other words, the business factors are larger than the technical factors, but that doesn't mean the technical factors aren't influenced.  Enterprise software tends to be delivered as integrated turnkey solutions from tools through deployment.  Free software tends to follow a some assembly required approach.

Title: Why are some languages (e.g Visual Basic) considered more enterprise ready than others (Python)

Body:
Reading about various techie sites, there is often a feeling that Microsoft Languages / Oracle etc. are considered "enterprise ready", while there seems to be more doubt about languages such as Python or Ruby.

Why is this?

Do Microsoft languages actually have less security holes or not?


答:
Well, I worked in an enterprise that used Python for a lot of thing, and one of my friend wrote Ruby in a gool-ol Insurance companies, so I don't know how much you can really say that they are not enterprise ready, but it's true that Java/C# are more used for the "big stuff".

What it mostly come down to is support. When you choose Microsoft and Oracle, you can call them at midnight on Christmas Eve and yell at them because its doesn't work, and they will fix your problem. For those mission critical applications, its very, very important to be able to do that.

They also sell more integrated solutions that are pretty much guaranteed to work together. If you take C# with SQL Server and Windows Server, they integrate pretty tightly. Same thing with Java/Oracle or IBM on Power with DB2. Those solution have complete tool to manage them that fit with what is existing (user are managed trough Active Directory, it can work accross continents, completely localised in swhahili, etc). If the organization grow and need to integrate a new component, its usually pretty easy to do so with those big enterprise solutions.

In the end, its not really the language itself, it's wether their is a big company behing that can sell tool, solution and support.


问:
What should junior developer expect from their senior team lead
Disclaimer: Opinions expressed are solely my own and do not express the views or opinions of my employer.

I work for a small company, in which few people are  developers, others are QA/Test and 1 is a Manager. I joined this company 1.5 years ago. 3 senior developers have 8+ years of experience.

These are the observations which I made about the team lead. (considering me as a fresher with less experience compared to them in all aspects )

They never discuss 1:1 or they never consider the junior suggestion (I agree that it's up to them, whether they accept it or not, at least they should consider an opinion).

As senior team leader they can try to refactor the codebase with new technologies ( including the factor of rolling out new technologies is possible and other developer and infrastructure also ready), but these team leader feel less in-secure to work with new technologies, as they are not up to date. (reason I am telling, they don't know what current programming trend, *(such as popular open source projects like modernizr, bootstrap and many others).

In our codebase more than 10000+ lines are repeated, so I told them  about DRY: Don't Repeat yourself.  Their reply was : "It is a fascinating article, but never works in practice".  I just told them if we do not make it 100% DRY, we can at least use interfaces, but that also was not considered. *(interfaces can be added for new features, not touching the previous codebase, if they are not ready to refactor)

All senior developers do maintenance and hot fixing of patches. The rest of the time they just spend on entertainment sites. They are just happy to finish the task.

Introducing new technology is bad? *(including factor of feasibility can be done).

Manager also least concerned about the things which I am talking about.

Junior expects they can learn many things from team lead. *(not by asking help or senior coding for them).

My questions are:

Am I too aggressive about the changes which I am proposing?

What should I expect from senior dev leads who have 8+ years experience?

Am I wrong to expect to learn and gain experience from a company?

Update :

Why they feel DRY is impractical: because they don't want get involved with OOP concepts. They are happy with repeating tasks.

New technologies I am proposing:

Usage of Minification of CSS, JS, SPrite images

Usage of Interfaces and .net framework 4, generics and many others.

Client side libraries such as modernizr, knockout js, bootstrap for responsive,

答:
Am I too aggressive about the changes which i am proposing ?

Without specifics (what new techs you're proposing, why they're rejecting them, where they feel that DRY is impractical and why, etc), it's hard to evaluate the amount of merit to your proposals and that's important for your aggressiveness.  If you want them to use a new framework because you think it's new and cool, then pushing more than lightly is too aggressive.  If they're really slamming thousands of lines of copy/paste into the codebase (i.e. they're writing crap) then I'd say more aggressiveness is warranted.

But this also depends on the interpersonal dynamics too between you and them.  My advice would be to ask yourself "could I demonstrate that my suggestions would benefit the company?"  If the answer is yes, then I'd say you have some license to try to push.

What should i expect from senior dev lead who have 8+yr ?

This will run the gamut.  You'll sometimes get some really sharp people that you can learn a lot from, both in terms of office politics navigation and technical considerations.  Unfortunately, you also get a lot of this.  You'll find no shortage of people whose 8+ years of experience basically just amounts to doing the bare minimum not to get fired.   If you find a mentor or someone who is really sharp, hold onto that as much as you can because it's less common than it ought to be.

Am I wrong to expect good learning from a company?

People to learn from are out there and they're at some companies.  You seem to be faced with a common dilemma and, to paraphrase the .NET Rocks guys, this is worth considering:  "Change your company... or change your company."

Meaning, if you believe in certain core approaches and principles and you're finding yourself consistently unable to sell them and gain the freedom to do and learn things that you want to do and learn, it's worth considering a search for a company that's a better fit for you.


问:
Why does flask use Jinja2 and not xpath?
I'm just starting out with python and since I'm coming from a PHP background (thus have to adjust my mind to wrap around new concepts) one major question still stands without answer - why does Flask need a template engine?

The way I was used to go about things, was to have a template.html that contained valid html without any logic and then, when needed, just load the file into a DOMDocument object and navigate it using DOMXpath. This made perfect sense to me - leave the UI part separate from the LOGIC part.

But now since I'm starting to learn a new language, it kinda forces me to get back to mixing in logic with the UI. So it boils down to this - is it me, is the DOM and xpath route just something I do to make my life "harder", or is Flask wrong to use a template engine?

答:
There's absolutely nothing wrong with using a template engine as long as it's completely focused on display logic.  Looping over lists, printing fields from records, formatting strings - all of this is fine.  You still have a clearly defined boundary between where you're "doing things" and where you are simply formatting it for display.  What you shouldn't do is actually be modifying or, even worse, generating the data in your display code.  The point is to make it simple to find where any piece of data comes from or is modified & make it simple to modify one part without the other.

With an ideal separation of concerns, the same application logic could be used, unmodified, to generate your site, do a total redesign of your HTML, generate a mobile version, XML/JSON exports or any other possible representation.  What you were doing before seems to directly tie your application logic to the structure of your template - the exact opposite of "don't mix logic and UI" is trying to accomplish - an absurdly literal and dogmatic application of a general rule.


问:
Should the variable be named Id or ID?
This is a bit pedantic, but I've seen some people use Id as in:

private int userId;
public int getUserId();
```

<p>and others use:</p>

<pre class="lang-cs prettyprint-override"><code>private int userID;
public int getUserID();
</code>```

Is one of these a better name than the other? Why? I've seen this done very inconsistently in large projects. If I were to set a standard which would most people be familiar with? Which is the conventional standard?

答:
Consistency is king; pick one or the other, but do it consistently everywhere.

That said, I prefer the first variation, because it doesn't violate camelCase (doing so means you have two style rules to remember, not just one).

Two capital letters is sometimes used because of this, but an ID is really just a form of Id-entification.

Title: Should the variable be named Id or ID?