答:
Put the innermost loops into functions.  This also aids readability.

Rearrange your code to short circuit instead of nest.  For example, instead of if (condition) {big long nested code}, use if (!condition) return;

Preprocess data into an intermediate form that doesn't require as much nesting.  For example, if you copy a linked list into an array at the start, you might be able to avoid a nested loop later that traverses the linked list.

Use recursion instead of nested loops.  Recursion often greatly simplifies deeply nested code.

Use exceptions to exit nesting during error conditions instead of checking at every level.

Try to find algorithms that are more efficient than O(n3).

Title: Keep indentation level low


问:
Should Software Engineering and Computer Science be separate majors?
For decades, the accepted degree to get to become a software developer was "Compter Science."

We've had a few questions already about whether that degree really prepares students to develop software.

Some schools have, in the last 8 years or so, started offering multiple distinct majors in programming.  Using the curriculum from my school:

Computer Science, which starts out with some intro programming courses in the first year, and then focuses on theoretical computer science, algorithms, and a bit of OS stuff.  Most classes involve several smaller projects and homeworks, done solo or in pairs.

Software Engineering, which starts out with the same intro programming courses, does a few classes of theory, and then goes into software development practices (testing, process methodologies, sofware metrics, requirements gathering) and software design (distributed system design, info system design, real-time/embedded design, subsystem design, etc)

Different schools do it differently, so the above is just a real-world example I'm familiar with.  What I ask is: Is there a need for distinct majors in programming?

答:
They should be different disciplines, but not at the undergraduate level. I just don't see how they can cramp up all that is needed for Software Engineering on an undergraduate degree. Just in the same way we do not see undergraduate degrees in Systems Engineering (where people get a MS in after getting a degree in EE, CE, Mechanical Eng or CS), it is a similar case with Software Engineering.

It is a multidisciplinary approach based heavily on computer science and/or MIS. People truly become software engineers in practice (and not just in title) after pursuing advanced course work and/or work experience in the field, provided that the later is done in environments conductive of software engineering.

Most people have titles of software engineering but have not really advanced beyond coding. This is not a dis on them, but an observation - they have not been sufficiently exposed to the type of work that would help them accumulate work experience beyond coding. Worse yet, most jobs and organizations are atrociously run, and are not conductive of doing proper software engineering.

Furthermore, without some work or scholastic maturity, software engineering material will simply fly over the heads of most undergrad students.

ContentLicense: CC BY-SA 2.5


问:
Should I write an interface API before an implementation?
I've been delving into more "organized" programming recently and I've been learning that I should be programming to an interface, not an implementation. With that in mind, would it be better to "sketch" out a project in interfaces before writing the implementation for it where possible?

And if this is the case, in the case of using 3rd party libraries (ie Lidgren), should I be wrapping those in interfaces as well and resolve them through IOC containers, or is it OK to expose them to the interfaces?

答:
I think it is overkill. If the user of your API does not need to be forced to implement/use something a certain way then I would leave it out. Interfaces are contracts, if I don't need it then why give me one?

I think people overuse interfaces. You are adding a layer of complexity that is not needed in most cases.

ContentLicense: CC BY-SA 3.0


问:
Keep indentation level low
I hear a lot that you should not write functions larger than one screen size, that you should extract things into functions if you call things very often and all these coding guidelines. One of them is also keep your indentation level low. Some people told me even I should max indent 4 times.

But in every day programming it keeps happening that I need O(n^2) or O(n^3) loops with some flow control, which creates out of nowhere 7 or 8 layers of indentation...

Are there any good ways to avoid that? One problem is, if you try to avoid complex if/else statement nesting I tend to do this in one row which can look very terrible and be unreadable and not very easy to maintain.

答:
Inverted If

Most developers think in terms of nested logic. It's difficult for them to invert their logic to reduce nesting. Deeply nested code is more difficult to read, and to reduce nesting you often have to invert your logic.

When a programmer writes code they write in a logical tree structure like this.

 bool function publish(Document doc)
 {
    if(doc != null)
    {
        if(doc.status == "finished")
        {
            doc.print();
            if(doc.locked)
            {
                doc.unlock();
            }

            return true;
        }

        return false;
    }

    return false;
 }
```

<p>The above is logically correct, but it introduces indents that make it difficult to maintain in the future. It's difficult, because additional logic will require deeper blocks. The deeper it gets the more likely a bug will be introduced.</p>

<p>By inverting your if statements and combining them you can reduce the nesting.</p>

<pre class="lang-cs prettyprint-override"><code> bool function publish(Document doc)
 {
    if(doc == null || doc.status != "finished")
    {
        return false
    }

    doc.print();

    if(!doc.locked)
    {
        return true;
    }

    doc.unlock();

    return true;
 }
</code>```

This inverted kind of logic keeps all the function operations within the first indented block and if statements are only used to terminate the function.

Split Loop And Work

Don't perform your work operations inside a loop block. Separate iteration from the task itself. This creates functions of single purpose.

Take this example

function void PrintDocuments(List<Document> pDocuments)
{
    for(int doc=0; doc < pDocuments.Count; doc++)
    {
        for(int page=0; page < pDocuments[doc].Pages.Count; page++)
        {
            pDocuments[doc].Pages[page].Print();
        }
    }
}
```

<p>While that isn't very complex it does create 3 levels of nesting, and the function is performing three different tasks.</p>

<p>Split the work and loops makes it easier to maintain.</p>

<pre class="lang-cs prettyprint-override"><code>function void PrintDocuments(List<Document> pDocuments)
{
    for(int doc=0; doc < pDocuments.Count; doc++)
    {
        PrintPages(pDocuments[doc].Pages);
    }
}

private function void PrintPages(Document pDocument)
{
    for(int page=0; page < pDocument.Pages.Count; page++)
    {
        PrintPage(Pages[page]);
    }
}

private function void PrintPage(Page pPage)
{
    pPage.Print();
}
</code>```

One could argue that the above is extra work, but the time spend to split the tasks and create functions of single purpose will reduce effort later when maintaining the code. The reduced indention makes it easier to read. The work to be completed by a loop is never performed inside a loop, but is handled by a dedicated function for that work PrintPage.

Conclusion

Single purpose and inverted logic are the keys to reducing indentations.

Title: Keep indentation level low

Body:
Inverted If

Most developers think in terms of nested logic. It's difficult for them to invert their logic to reduce nesting. Deeply nested code is more difficult to read, and to reduce nesting you often have to invert your logic.

When a programmer writes code they write in a logical tree structure like this.

 bool function publish(Document doc)
 {
    if(doc != null)
    {
        if(doc.status == "finished")
        {
            doc.print();
            if(doc.locked)
            {
                doc.unlock();
            }

            return true;
        }

        return false;
    }

    return false;
 }

The above is logically correct, but it introduces indents that make it difficult to maintain in the future. It's difficult, because additional logic will require deeper blocks. The deeper it gets the more likely a bug will be introduced.

By inverting your if statements and combining them you can reduce the nesting.

 bool function publish(Document doc)
 {
    if(doc == null || doc.status != "finished")
    {
        return false
    }

    doc.print();

    if(!doc.locked)
    {
        return true;
    }

    doc.unlock();

    return true;
 }

This inverted kind of logic keeps all the function operations within the first indented block and if statements are only used to terminate the function.

Split Loop And Work

Don't perform your work operations inside a loop block. Separate iteration from the task itself. This creates functions of single purpose.

Take this example

function void PrintDocuments(List<Document> pDocuments)
{
    for(int doc=0; doc < pDocuments.Count; doc++)
    {
        for(int page=0; page < pDocuments[doc].Pages.Count; page++)
        {
            pDocuments[doc].Pages[page].Print();
        }
    }
}

While that isn't very complex it does create 3 levels of nesting, and the function is performing three different tasks.

Split the work and loops makes it easier to maintain.

function void PrintDocuments(List<Document> pDocuments)
{
    for(int doc=0; doc < pDocuments.Count; doc++)
    {
        PrintPages(pDocuments[doc].Pages);
    }
}

private function void PrintPages(Document pDocument)
{
    for(int page=0; page < pDocument.Pages.Count; page++)
    {
        PrintPage(Pages[page]);
    }
}

private function void PrintPage(Page pPage)
{
    pPage.Print();
}

One could argue that the above is extra work, but the time spend to split the tasks and create functions of single purpose will reduce effort later when maintaining the code. The reduced indention makes it easier to read. The work to be completed by a loop is never performed inside a loop, but is handled by a dedicated function for that work PrintPage.

Conclusion

Single purpose and inverted logic are the keys to reducing indentations.


问:
How many bugs to expect
At a previous job (circa 2010), my manager mentioned that he's doing some research into quality metrics. The bottom line is to answer the question how many bugs should I expect? The goal is to try and predict how many bugs are incoming, and more importantly, how many bugs we probably haven't yet found.

There are some problems around this metric. Historically, we tend to look at "lines of code," which is a horrible way of measuring functionality. Functional points seem better, but I don't have an easy way to describe and measure how many function points a piece of software has.

The other issue is that quality will obviously vary (widely) depending on if you have really horrible QA/developers, or really awesome, or somewhere in the middle.

Another issue is, obviously, what you define as a bug. Some teams look at any feature change as a bug; others try to divide (eg. new functionality vs. broken but "works as expected" functionality).

Is there any research, or body of work, on helping software teams identify and predict how many bugs they should be finding?

答:
Yes: http://www.net-security.org/secworld.php?id=14871

"Over the past seven years, the Coverity Scan service has analyzed
  nearly 850 million lines of code from more than 300 open source
  projects including Linux, PHP and Apache. ... The analysis found an
  average defect density of .69"

And that's just bugs findable by Coverity's formal methods.

https://stackoverflow.com/questions/625344/how-many-bugs-is-too-many has more info in answers, suggesting anything up to 10 bugs per KLOC.

Title: How many bugs to expect


问:
How can I automate production deployments without experiencing extreme anxiety?
At our shop we use SVN for source control and CruiseControl for CI on handling automatic builds and deployments to our development, test, and integration environments.

This all works smoothly however due to hardware and resource constraints our integration environment is not a 2 server load balanced environment like our production environment.  While everything else is equal that would be the only difference between our integration and production environments (although a big one!)

Theoretically the difference is a slightly different configuration of our app servers and the deploy script merely would have to drop the build artifacts into two servers instead of just the one, but why am I so nervous to automate our production deployments?!

I am generally not a control freak but I always feel the insatiable need to deploy production to production manually.  I have heard from colleagues that this is generally a Really BAD Thing™ but they failed to make a case against it.

I know that when I do it manually I can SEE that I am physically copying the correct files, I am physically shutting down the app servers and ensuring they closed successfully, I am physically starting the servers back up and then physically inspecting the logs to make sure it started up okay and the deployment was successful.  It gives me a peace of mind.

What are arguments against this OR arguments for automatic scripted production deployment?

答:
It is entirely possible to use automation scripts to deploy to production environments.  However to do so reliably you need to be able to do several things.

Reliably roll back to the previous version.

Obtain positive confirmation that the deployment has been successfully applied, and is responding to valid traffic.

Have comparable environments for development and QA which also use the same scripts.

There are some advantages to scripts, such as they will never miss out a command because its 2am, and its tired.

However, scripts can and will still fail. Sometimes the failure is in the design of the script, but it could also be caused by a network or power failure, corrupt file system, running out of memory.....

That is why it is important that after the script has run, that a defined test phase is also followed that verifies that the new deployment is up, running and handling requests, before live traffic is enabled.


答:
Bug Estimation is an academic field of software engineering, and has quite a bit of research devoted to it. Most of the work I know of though, focuses on predicting future bugs rather than pure quality metrics.

Make sure everyone's on the same page as to what qualifies as a bug. This will largely depend on what you are trying to measure. For example, if you want to find the number of bugs found after a new feature is deployed, you would search for issues created for features a few days after the deployment.

Unfortunately, your estimation is only as good as the data you collect. If the dev team files multiple issues for the same bug, or if If you put low levels of effort into finding bugs, your estimate will reflect that. One possible mitigation techniques is to test your estimation against an estimate similar project but with a different dev/QA team. This, unfortunatley has its own pitfalls as well.

The most important aspect is to treat an estimate for what it is: an estimate. Know what your estimate means, and how it was made. Know when your estimate is relevant to the problem, and when it is not. Throw it out if it doesn't match your data. Never use one single metric as a standin for the quality of your code.

Here are some papers that you may find useful. Number 2. is a direct analysis of bugs in eclipse, which can provide an example of how to do your own estimate:

https://dl.dropboxusercontent.com/u/18500843/01702038.pdf

https://dl.dropboxusercontent.com/u/18500843/04228670.pdf

https://dl.dropboxusercontent.com/u/18500843/chp%253A10.1007%252F978-1-4020-8741-7_20.pdf

Title: How many bugs to expect

Body:
At a previous job (circa 2010), my manager mentioned that he's doing some research into quality metrics. The bottom line is to answer the question how many bugs should I expect? The goal is to try and predict how many bugs are incoming, and more importantly, how many bugs we probably haven't yet found.

There are some problems around this metric. Historically, we tend to look at "lines of code," which is a horrible way of measuring functionality. Functional points seem better, but I don't have an easy way to describe and measure how many function points a piece of software has.

The other issue is that quality will obviously vary (widely) depending on if you have really horrible QA/developers, or really awesome, or somewhere in the middle.

Another issue is, obviously, what you define as a bug. Some teams look at any feature change as a bug; others try to divide (eg. new functionality vs. broken but "works as expected" functionality).

Is there any research, or body of work, on helping software teams identify and predict how many bugs they should be finding?


答:
how many bugs should I expect? [...] how many bugs we probably haven't yet found.

To answer that, define the words "bugs", "expect" and "found" :)

For one of my recent projects, we had initially added positive unit tests for our APIs. We found a set of bugs with a measurable "density" (i.e. measurable xx/1KLOC).

Then, we started adding negative test cases. We discovered another wave of bugs, that would have increased our density to an yy/1KLOC (with yy > xx).

Then we added testing with simulated low memory conditions (i.e. we tweaked our memory allocation APIs to fail on first allocation and called an API, then to fail on the second allocation and called the API and so on, until the API had enough successful allocation to succeed). We found a third wave of bugs, with most of them being "library left in invalid state when memory allocation fails".

Then we moved to fuzz testing, and full scenario testing (a particular sequence of API calls for achieving a given result) and got a new measurement of bugs.

TLDR: How many bugs you find depends on what you consider a "bug" (for us it wa only a bug if found after the end of the iteration), what you are testing for, your testing methodology and what resources you can put into testing (people, time, hardware, etc). If KLOC as a measurement is in there somewhere, it's a secondary measurement (i.e. after "what is a bug", "what you are testing for" and so on).

Title: How many bugs to expect


问:
Is a senior programmers advice about always using books a good idea?
I am a junior developer and have only been in the industry for 5 years. At my current company there is a senior let's call him Infestus. Occasionally I am being given opportunity to shine and do something completely brand new from scratch.

One of the most recent examples was that I had to make a singleton in the multithreaded application. I have decided to use this method. As soon as Infestus saw it, he quickly proceeded to call me stupid and told me to use this approach. Upon asking him why he just brushed it off as this is better and that's how this and this book about Java says it is better.

And it is a common pattern: whenever I get a chance to do something new, I quickly get shot down by Infestus and the only reasoning why his method is better is because those books were written by famous programmers. He is always trying to give me books to read so that I may "learn" which ways to program.

I have only been programming for money for 5 years, but is it always a good idea to just blindly follow the book on best ways for solving a problem, or should I try experimenting every now and then? The constant barrage of complaints from the Infestus is starting to cause me to never try anything new and follow examples in books.

EDIT: I am utterly lost. Yes I know that following anything blindly is a bad idea. But this godlike programmer Infestus who seems to know a lot, tells me that the only way to program properly is by reading books and following everything down to a T. All the rules he imposes are the ones written in books, so I am just wondering if books are the only correct way.

EDIT2: Infestus is not my boss. He is just one of senior developers in charge of reviewing the code. And most of his comments after reviews consist of book names where such and such method is wrong.

答:
The thing about books is that they - mostly - pass through revisions, which have a better chance to spot bad practices and misconceptions. Also, the "big names" are experienced people who rely on being good to earn extra money selling books, thus, there are some minimal quality assurances about what they say.

That said, reading books, papers, and other sources is a good way to grow as a professional, of course, when confirmed by practice. So, it's good for you to read those books (even those recommended by Infestus). However, the books must mainly enlarge your comprehension on the subject, since there will almost always be other ways to solve the same problem.

About your "go by myself" approach, the point is: can you sustain your point of view? How do you prove your solution to be better than any other? Some times you can devise bright solutions by your own, but, when compared to other known solutions, you must to be able to argue the reason why yours is better, since the others have at their favor, at least, the use cases. Then, be creative and thoughtful, but most importantly, be effective.

If I were, you I'd read those books. That will help you by giving you more arguments, and, at the same time, you may find that Infestus - maybe - is wrongly taking those books as arguments, and he wasn't spotted yet because nobody knows the content of those books. Or you may find that he actually k


问:
How does the Scrum Master participate in Daily Stand-Ups?
We have a professional Scrum Master consultant [*] who recently joined our project. Unfortunately, we don't know her name (she never introduced herself to us, she just came in one day and said "we are having a daily stand-up"), and she doesn't seem to do much else except chair a daily stand up meeting  - when I half-jokingly asked her to also give daily feedback in the meeting, she was quite affronted, saying it's the Scrum Master's job to "facilitate, not participate".

This seems fairly anti-Agile (having worked on other agile projects, where the teams were self directed), which is supposed to be egalitarian, but I am not sure about how it works in the Scrum Methodology. I suspect she doesn't do much all day, and that's the reason for her defensiveness on this issue.

Does the Scrum Master take part in the "yesterday, today, impediments" spiel during the stand-up meeting, or is their role to just chair ("facilitate") the meeting?

[*] We weren't actually told what her job is, we just assume, since she calls herself the Scrum Master

答:
In stand-ups, she should give status on impediments and then in retrospectives she should give her opinion on how stand-ups could be made more meaningful or efficient.

If one expects SM to give status of her daily activities then IMHO one has wrong expectations. Purpose of status is so that team can align their activities and i don't know why a team member would want to know what she (SM) was doing yesterday to plan today.  At least one book even suggest that SM are not even required to be in stand-ups on daily basis.


问:
"Enterprise" version of GPL'd code?
I know that there are a number of discussions about the GPL on this site but I just ran in to an interesting case of apparent misuse that I (surprisingly) haven’t seen discussed anywhere.

The CFEngine configuration management program is apparently distributed under the GPL (it even appears to be an FSF project) but the original author also distributes an “Enterprise edition” which is blatantly non-free. This appears to be an obvious violation of the GPL.

The official response to this question (from the CFEngine FAQ) is:

As copyright holders we are free to license CFEngine under any terms we choose. The files that belong to both the community edition and enterprise editions are consequently licensed under both sets of terms. The licensee of the Enterprise edition is therefore free to choose the terms that are deemed most desirable.

Which, as I understand the issue, is just not true. As copyright holders they are of course free to change the license (for future releases), but distributing code with both licenses is contradictory at best and illegal at worst.

Am I missing something here or does this seem wildly hypocritical?

答:
"This appears to be an obvious violation of the GPL."

They are not subject to the terms of the GPL in any way. The software was never distributed to them under the GPL, only by them to others.

If you write some code and then distribute it to me under GPL, then I would have to follow GPL, but you wouldn't.

The voilation occurs when someone gets someone else's software under GPL and redistributes it as closed-source.

Title: "Enterprise" version of GPL'd code?


问:
How to handle when one user deletes the object while the other has it opened in edit mode in a webapp?
I am developing a CRUD type web application. It is a project management system having projects, milestones, tasks, employees etc. Each employee has his/her own account to login and view the system. The problems come here:

If one user deletes a task while the second has it opened at the same time, the second user will get a null pointer exception if he tries edit and save, because the object doesn't exist.

The same problem in a bit different situation. One user has a task window opened. The second user deletes one employee. The first user tries to assign a task to deleted employee (because it is already in the list in a combobox) and gets null pointer exception.

If someone deletes the object and the other user tries to open it at the same time (will be a null pointer exception when trying to get an item)

I am trying to leave technical details of the project because it is up to that. But if it helps, I'm using Vaadin framework based on Java. The database is MySQL.

I thought two possible solutions but not sure about them:

Catch null pointer exception and print a general warning to the screen ("Some objects are missing...). But it wouldn't be clear for the users that exactly has happened.

Check every commit of the object and if it was deleted catch the exception and give more detailed explanation. But it won't help in the 3rd situation.

I am really looking for any guiding points, advice, or tips you can provide on how to properly deal with these situations. Thank you in advance!

答:
The proper way to handle this is to lock the object when the first user starts editing it, and have the application check for locks on an object before deleting it.

For example, you could have a tasks_locks table that looks like this:

```
task_locks
----------
  task_id
  user_id
  lock_timestamp
```

When a user goes to edit a task, the application should insert a row into this table, with the Id of the task , the ID of the user, and the current time. This way, when another use tries to delete that task, the application will see a lock record indicating that the task cannot be modified and should inform the user that the task cannot be deleted. When the first users saves their edit, this row can be removed from the task_locks table. Only then can the other user delete the task.

Of course, you'll want to handle situations where a lock never gets released (maybe the client was disconnected before they could complete their edit) so you'll need some procedure to purge locks. It could be manual, it could be automatic (i.e. delete all locks that are more than 60 minutes old), but it's something that should be considered.

With the first solution you propose, the user could spend a lot of time entering data, only to get a NullPointerException. Then they have to re-enter all the data and hope that no one messes around with their dependencies while they're working.

Your second solution just seems to catch the error in a different place so that the user gets a better message, but it won't solve the problem of them having to re-do all of their work when a record they are dependent on is deleted.

Body:
The proper way to handle this is to lock the object when the first user starts editing it, and have the application check for locks on an object before deleting it.

For example, you could have a tasks_locks table that looks like this:

task_locks
----------
  task_id
  user_id
  lock_timestamp

When a user goes to edit a task, the application should insert a row into this table, with the Id of the task , the ID of the user, and the current time. This way, when another use tries to delete that task, the application will see a lock record indicating that the task cannot be modified and should inform the user that the task cannot be deleted. When the first users saves their edit, this row can be removed from the task_locks table. Only then can the other user delete the task.

Of course, you'll want to handle situations where a lock never gets released (maybe the client was disconnected before they could complete their edit) so you'll need some procedure to purge locks. It could be manual, it could be automatic (i.e. delete all locks that are more than 60 minutes old), but it's something that should be considered.

With the first solution you propose, the user could spend a lot of time entering data, only to get a NullPointerException. Then they have to re-enter all the data and hope that no one messes around with their dependencies while they're working.

Your second solution just seems to catch the error in a different place so that the user gets a better message, but it won't solve the problem of them having to re-do all of their work when a record they are dependent on is deleted.


问:
Coding styles when using several disparate libraries
I am working on some C++ code that uses several libraries, including some C libraries, that all have different coding styles.  It will be open sourced once it reaches a usable stage.  Which would cause the least confusion for a short-term contributor who checks out the code to fix one bug or add one feature?

Have one consistent coding style throughout the entire application, even if it occasionally doesn't match the typical coding style of the libraries used.

When a library is heavily used in a certain module, conform to the typical coding style of that library (i.e. the coding style used in the library's own code and documentation) in that module.

My thought is that the latter will make it easier for experts in that particular library to make one-off contributions, and make it easier to incorporate tutorial/example code during development.  However, it also makes the coding style inconsistent throughout the application.  What are the pros and cons of each approach?

答:
I think it kind of depends upon how big the overall project will end up being.

At one extreme, let's say you have a 1 Mloc project.  For that large of a project, it's unlikely that a single individual would be an "expert" in all of the areas involved.  So in this case, I would stick with existing code styles for each major component.  New developers will pick an area, learn that, and it's unlikely they'll see many other components that may have different code styles.

If the project is a lot smaller, where it is likely to have individuals understand the entire code base, then I would pick a dominant code style and stick with that.  In this case, I think consistency across the entire project makes more sense because new developers will be likely to work in all areas of the project.

Medium sized projects are perhaps the hardest to make this decision for.  In this case, you have to weigh out the costs for each approach and decide upon the one you think will be least expensive long term.  The challenge is that medium sized projects have usually grown just enough to where a complete style refactoring looks prohibitively expensive.  You may want to have a second look at the code tree structure to see if things can be arranged to group particular code styles together.

Either way, the final decision should rest with the team you're on that's putting this package together.

Some of the outliers that might shift my reasoning from above:

If one or more of the modules has an atrocious style, then there's no sense in keeping that around, even on a larger project.  Yes, style is subjective, but if you and your fellow project participants really, really don't like the way particular areas flow then nuke the old style and give it a better one.

If all of the styles are reasonably close to each other, it might be just as easy to declare "here's the new way" and use that for all new code and significant refactorings.  This can make reviews a bit of a pain, but in my experience most folk are pretty capable at adapting to this approach.  It also provides a telltale sign where the old code is.

Sometimes style is shifted based upon new functionality added to the language.  C++ has picked up a number of features over the years.  It may make sense to refactor as needed the older style to a newer style that takes advantage of those features.

Some libraries may have a particularly idiomatic approach or style.  If so, I would stick with that style for that library even if it may conflict with the rest of the project.  The intent here is to increase the odds that someone who works on frobnosticators on other projects will also work on your project.

Some of the comments mentioned imperative and object-oriented styles as being a consideration.

Modules that are "heavy" in a particular style probably ought to stay that way if the module is medium sized or larger.  I have worked with the three major styles (imperative, objective, and functional), and I have refactored heavy imperative styles into an OO style.  With a medium or larger amount of code, the refactoring can be (exceptionally) difficult.  My experience was confounded because I didn't have any tooling support to assist in the refactoring.

I would imagine there is a high correlation between the heavily imperatively styled modules and those modules being idiomatic for particular development niches, which goes back to the last point I raised with outliers.  So any module you would find for that functionality is going to look like that, and you want the experts of that domain to easily be able to work on your project as well.  But if there are options and your team doesn't like the style of that module, then I would investigate the options.

Likewise, I have worked with a heavy-OO styled module where the OO principles were taken too far and used incorrectly.  As an example, interfaces were being used as a substitute for multiple inheritance.  And as you might expect, it was a crude implementation.  I was able to make reasonable progress in refactoring that module, but I ultimately abandoned that approach as I found better packages to use instead.


问:
What are the disadvantages of using stored procedures, SSIS, and SSRS to implement business applications?
Recently, it was suggested that many projects (where I work) should be implemented using some combination of stored procedures (on SQL Sever / T-SQL), SSIS, and SSRS.

In one specific project, SSIS would get a file from a SFTP server. The file contains the daily price of ten stocks. A data warehouse will store the daily price of each stock since inception. As of now, the prices go back twenty-five years. Stored procedures will have the business logic to calculate various performance numbers (i.e. return %) during arbitrary time periods such as the 5 year return at 31 December 2012.

These stored procedures would be used by SSRS to create reports for the end users.

What are the problems/issues using this approach? I feel that vendor (Microsoft) lock is an issue but I don't see that (unfortunately) being enough to change direction. Also, I have a concern about all the business logic being stored procedures. What are the arguments against/for putting this business logic (i.e. calculation of performance numbers) in stored procedures versus using Java (or some other OO programming language) with ORM (such as myBatis)?

答:
I think it depends on how many reports you are running. If just a few then it makes sense to just use embedded queries because it will be alot faster and cheaper to complete the work. If your building many reports than stored procedures can be argued for as it reduces the need to write sql code over and over again and just use procs. Also if database structure is likely to change it is much easier to change it in one stored proc over combing through all your reports looking for references.

Another alternative that should be noted as well is using shared datasets.  This could be a compromise between the two choices you are looking to compare and contrast that could possibly solve your problem. Shared datasets are reusable making them an optimal choice. Only problem with shared datasets are that are only realistic for reports without parameters. If using a report that has search parameters it is best to use stored procedures as these can be passed in.

I would suggest a hybrid approach based upon need. Always start with an embedded query to do the first report of its kind. If other reports are needed based upon the same query using a shared dataset or stored procedure based upon the parameters that the report needs.


问:
Java or C++ for university CS courses?
I'm in the throes of getting myself enrolled in school to get a CS degree. The school I am looking at actually offers both Java- and C++-based for the introductory software development courses (object-oriented programming, design patterns, that sort of thing). It is student's choice which track to follow, but there is only time to follow one.

Knowing what you know now, if you had the choice, would you lay down your CS curriculum foundation in Java or C++?

My current debate currently looks like this:

A good friend (who has a PhD in AI) is touting Java as the better choice regardless of what I do, if only to open up more job opportunities later, though he might be biased since all of his work has been in Java (he loves it). I live in the Boston, MA, USA area and I see an equal amount of Java and C work.

On the flip side, although I haven't entirely yet settled on what I want to do with the degree when I'm done, my preference would be to develop for the Mac, which I am doing now albeit in a limited capacity. To that end, I'm getting some limited exposure to C++ already, but I've had none with Java, and looking at my projects at my day job I don't see a need to use it anytime soon, "soon" measured by at least two years.

I probably should note that I'm an adult going back to school after 20 years (I currently have no degree of any kind) so I'm looking to maximize the opportunity and time spent as best I can. I'm kind of leaning towards C++ but I'm still ambivalent, and some outside, objective advice would help here.

Or I could just be thinking too hard about it.

UPDATE: It turns out the language selection wasn't so clear cut as I originally surmised. While a couple of core courses focused on Java, some of the other core courses work in primarily C and Java, but also a few others thrown in for good measure. In fact, my rest of my semester is going to be in Objective-C after spending time in Java and Javascript. Last semester was C, Javascript, and PHP, plus a few others thrown in as assignments required. Since things were pretty much split down the middle overall, and I am still getting answers to this, I am now trying to work my curriculum such that I meet all of the requirements for the degree but to absorb as many languages as I can reasonably handle. So far, my grades have not suffered trying to do this.

答:
Schools and scholars who advocate Java as the first choice should have their heads examined (or simply get a real job out there.) I'm saying this as a person who has done both application and system development in Java for the last 12 years. Java is an atrocious language for teaching.

The reason is the following: barring the gifted, most students can (and will most likely never) grasp object orientation without understanding modular programming. And they cannot understand modular programming without first understanding structured programming in a procedural language. Plain and simple. Testament of this (among other things) is that even though we have known OO for 3-4 decades now, people still write hyper-spaghetti in practice.

Furthermore, a person solely relying on a gc-based language (be it Java or .NET) can never really get close to the hardware. Unless your entire ambition is to make dynamic web pages, guess what? You need to be comfortable with getting close to the language.

You go to a CS school to become a well-rounded computer scientist and programmer (hopefully with quite a few credit hours of hands-on programming practice in many programming languages.) If you all you know is Java (or .NET or C or Python whatever) then you are a "Java programmer" (not a programmer that can work on Java, but a "Java programmer"). And that makes as much sense as saying you are a "hammer carpenter" or a "Phillip screw driver mechanic", doesn't it.

A good school will expose you to C (or some other procedural language like Pascal or Ada), then C++ and a assembly, leaving you to learn Java on your own as you pursue project capstone courses on your junior/senior year. Also, it should provide you with exposure to functional languages so that you understand the concept of passing computational blocks as arguments, side-effect free computations, location transparency and the like (which have real practical applications, even on the web.)

You need to know what a segfault is. You need to know what paging, virtual memory and all that crap mean. You need to know how to decompose problems in modules (be them procedural and OO-based). You need to know how OO systems are truly implemented under the hood (so that you know the cost.) You need to know where OO abstraction breaks (and they do because the world and complex problems are not necessarily object-oriented.)

You need to know all that stuff so that you become a well-rounded computer scientist capable of working either on the enterprise or at the very low level implementing system-level stuff, either for the commercial or the public sector, both large scale and small scale.

Academics who have been pushing for Java as the-one-and-only language to rule them all are completely clueless as to what the industry really need. Clueless. Unforgivable clueless. That's what happen when they work on ivory towers looking at the industry at a distance.

They have turned Computer Science departments into expensive 4-year vocational schools churning one-programming-language-trick ponies. And that could be forgivable if they could at least teach students basic business/enterprise/organizational skills (that is, abandon the CS facade and adopt a MIS curriculum.) But they don't even do that, which I think it's a great disservice to the industry, the economy and ultimately the students.

I would suggest you read Joel Spolsky' piece on "Java Schools".

http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html

In summary, if they don't teach you a procedural programming language (be it an industrial one like C or Ada or one good enough for teaching like Pascal), and they give you if C++ (if you are lucky) or Java/C# (if you are unlucky), I would look for another school. Plain and simple, from a guy who has been using Java for a living in the real world for quite a while.

Title: Java or C++ for university CS courses?


问:
How do you build debugging messages into your programs/scripts?
General, high-level question for people who work with code regularly.

I was repurposing some old, outdated Javascript code into a Chrome extension, and to help me understand it, I wrote some quick code to help (see below). I regularly put messages in my code such as dbmsg('Begin function loadDefaults()'); or dbmsg('Settings saved to storage'); and the message is sent to the console. Whenever I need to debug something where the standard console messages aren't helping, I just turn on debugging. I figure this method is pretty simple and can be ported to other languages.

What other ways do you build debugging into your programs? I'm self-taught, so I don't know the standard practices, but I'm more interested in unique ways you've found to do this sort of thing.

```<code>/** Debugging Tools
 *
 * Set debugMode to 1 to show error messages, 0 to hide messages.
 */
var debugMode = 1;
function dbmsg(message) {
    if ( debugMode == 1 ) {
        var date = new Date();
        var time = date.getHours() + ':'
            + date.getMinutes() + ':'
            + date.getSeconds();
        console.log('DBM - ' + time + ': ' + message);
        if ( chrome.runtime.lastError ) {
            console.log('DBM lastError - ' + chrome.runtime.lastError);
        }
    } else if ( debugMode == 0 ) {
        return;
    }
}
if ( debugMode == 1 ) {
    console.log('Debug mode is currently ON. Each debug message is preceeded with "DBM" and the time the message was generated.');

    // Listen for changes in storage
    chrome.storage.onChanged.addListener(function(changes, namespace) {
        for (key in changes) {
            var storageChange = changes[key];
            dbmsg('Storage key "%s" in namespace "%s" changed. ' +
                  'Old value was "%s", new value is "%s".',
                  key,
                  namespace,
                  storageChange.oldValue,
                  storageChange.newValue);
        }
    });
}
</code>```

答:
I have a random bias against enabling or disabling "debug state" by way of a runtime variable or constant.  At best, you could have a global "log level" setting that says how SEVERE messages have to be in order to log, but even that's an implementation detail.

My actual preference is to have each entry-point or major method report its existence to some part of the application specialized for logging, and do so again on errors, warnings, or significant results.  What that part is and how it works will vary based on the specific stack you're using.

When I was writing T-SQL scripts, I made liberal use of the PRINT command.

```<code>CREATE PROCEDURE doStuff(@arg1 int, @arg2 char)
  PRINT 'doStuff(' + @arg1 + ', ' + @arg2 + ')'
  ...
ENDPROC
</code>```

For JavaScript, I made a habit of a simple wrapper as you did, but I just tested for the presence or absence of console and let the browser decide if it had to actually keep the log or not.

```<code>function log() {
  if(console && console.log) {
    var msg = "";
    for(var a in arguments) {
      if(msg != "") {
        msg += " "
      }
      msg += a;
    }
    console.log(msg)
  }
}

function doStuff(arg1, arg2) {
  log('doStuff(', arg1, ', ', arg2, ')');
}
</code>```

With the work I'm doing now, one of the additions I made to our next major release was a new reporting class, for all of this sort of thing.  But that's a client-side project in a largely dead language, and wouldn't be entirely useful.

Body:
I have a random bias against enabling or disabling "debug state" by way of a runtime variable or constant.  At best, you could have a global "log level" setting that says how SEVERE messages have to be in order to log, but even that's an implementation detail.

My actual preference is to have each entry-point or major method report its existence to some part of the application specialized for logging, and do so again on errors, warnings, or significant results.  What that part is and how it works will vary based on the specific stack you're using.

When I was writing T-SQL scripts, I made liberal use of the PRINT command.

CREATE PROCEDURE doStuff(@arg1 int, @arg2 char)
  PRINT 'doStuff(' + @arg1 + ', ' + @arg2 + ')'
  ...
ENDPROC

For JavaScript, I made a habit of a simple wrapper as you did, but I just tested for the presence or absence of console and let the browser decide if it had to actually keep the log or not.

function log() {
  if(console && console.log) {
    var msg = "";
    for(var a in arguments) {
      if(msg != "") {
        msg += " "
      }
      msg += a;
    }
    console.log(msg)
  }
}

function doStuff(arg1, arg2) {
  log('doStuff(', arg1, ', ', arg2, ')');
}

With the work I'm doing now, one of the additions I made to our next major release was a new reporting class, for all of this sort of thing.  But that's a client-side project in a largely dead language, and wouldn't be entirely useful.


答:
Setting aside workplace manners, setting aside the reality of a mentor role that senior developers have, setting aside your own desire to explore, setting aside insulting behavior, and setting aside fetishes for books ...

The purposes of a code review in a team are 1) to validate code and 2) to ensure the person writing the code understands the meaning behind code improvement. It's not the place to say "change this because Martin Fowler said so in the GoF book". However, it is the place to say "change this because [brief explanation]; there is more detail discussing this in the GoF book".

If your senior developer is not, at least simply and subtly, providing an explanation for a change, and insisting on using the verbiage of "because of [book]", he is being a bit of a smartass and a jerk. How do you deal with it? Mention it in a team meeting, verbally, and ask for your teammates to provide a statement or two briefly explaining the advantage or necessity of the change, along with that helpful book reference. Be sure to thank him for the book reference.

Face it, your goal is to appreciate the change suggestion and to not be demotivated for your task or your job. Tell him that. "I would appreciate the change suggestion more if you could briefly describe the advantage or necessity of the change when you review my code; as it is I am finding your book references alone to be a bit demotivating."

If he continues to refuse to provide a simple explanation with his book references, if you can provide another book or resource of equally or greater notoriety in the industry with a different opinion and it matches your scenario, you might be able to add your own book reference in your review comment in consideration of retaining the original code. Do this enough times, he might back down. Be very careful that the counter-argument is right and significantly more important; it's okay to let a senior developer be wrong and still have his way, this is something I've learned and keep having to learn.

Title: Is a senior programmers advice about always using books a good idea?

Body:
I am a junior developer and have only been in the industry for 5 years. At my current company there is a senior let's call him Infestus. Occasionally I am being given opportunity to shine and do something completely brand new from scratch.

One of the most recent examples was that I had to make a singleton in the multithreaded application. I have decided to use this method. As soon as Infestus saw it, he quickly proceeded to call me stupid and told me to use this approach. Upon asking him why he just brushed it off as this is better and that's how this and this book about Java says it is better.

And it is a common pattern: whenever I get a chance to do something new, I quickly get shot down by Infestus and the only reasoning why his method is better is because those books were written by famous programmers. He is always trying to give me books to read so that I may "learn" which ways to program.

I have only been programming for money for 5 years, but is it always a good idea to just blindly follow the book on best ways for solving a problem, or should I try experimenting every now and then? The constant barrage of complaints from the Infestus is starting to cause me to never try anything new and follow examples in books.

EDIT: I am utterly lost. Yes I know that following anything blindly is a bad idea. But this godlike programmer Infestus who seems to know a lot, tells me that the only way to program properly is by reading books and following everything down to a T. All the rules he imposes are the ones written in books, so I am just wondering if books are the only correct way.

EDIT2: Infestus is not my boss. He is just one of senior developers in charge of reviewing the code. And most of his comments after reviews consist of book names where such and such method is wrong.


问:
Should timeout be a public static property or a parameter to every function?
TLDR: Should TIMEOUT be a public property on my static class, or a parameter to every function?

Background:
I am releasing a c# client-api library that facilitates communicating with our REST api.

The client-api consists of an object model and one large static class with a bunch of request extension methods for various types. 10 or so .Get() variations, a few .Post(), .Put(), etc.

This static class full of extension methods is preconfigured with our server URL, and some other static configuration constants related to the connection. Because all the functionality is exposed via extension methods, there's no need to create an instance of this class. Any configuration is done via static properties and affects all requests made by the application.

Problem:

Right now, all requests use a default timeout of 3 seconds (which seems generous to us, as our API is meant to be very responsive.) Some users with a bad connection though might want to wait longer for a response.

Our quick-fix solution is to expose the DEFAULT_TIMEOUT at a public static property on the class which can be set once on initialization, but is the proper thing to do to add a new optional parameter to every single one of our dozens of methods?

```<code>.Get(int timeout = DEFAULT_TIMEOUT) { ... }
.Get(..., int timeout = DEFAULT_TIMEOUT) { ... }
.Get(..., ..., int timeout = DEFAULT_TIMEOUT) { ... }
.Get(..., ..., ..., int timeout = DEFAULT_TIMEOUT) { ... }
...
.Post(..., int timeout = DEFAULT_TIMEOUT) { ... }
.Put(..., int timeout = DEFAULT_TIMEOUT) { ... }
.Save(..., int timeout = DEFAULT_TIMEOUT) { ... }
...
</code>```

On the one hand, we want to be flexible to whatever the consumer of our client-api library might need, but on the other hand, I won't want to get in the habit of polluting every method with every optional parameter that might impact a request (server url, authorization tokens, etc.)

What I don't want, is for the user to feel the need to do this:

```<code>ClientAPI.DEFAULT_TIMEOUT = 5000;
Thing found = new Thing(){ id = "19473" }.Get();
found.count += 1;
ClientAPI.DEFAULT_TIMEOUT = 20000;
found.Put();
ClientAPI.DEFAULT_TIMEOUT = 8000;
List<Widgets> widgets = found.GetSubresource("widgets");
...etc
</code>```

Is it reasonable to assume users won't be micromanaging timeouts for individual requests like that?

答:
Well, if you insist on managing the timeout functionality for your API, I think the static setting makes the most sense.

But, personally, I feel like the better thing to do is allow the users of you API determine the best way to handle timeouts. You have no way of knowing how many different ways users will want to define how timeouts should be handled. Same with caching, for example. API consumers should be responsible for that kind of thing.

Take the load off your shoulders and move on to your next feature. :)


答:
Is it reasonable to assume users won't be micromanaging timeouts for individual requests like that?

Well it really depends on the services being provided. Some operations might be very slow and he client might be able to anticipate that (for example, requesting all transactions on some account for the last 5 years) and the user is willing to wait. Other operations might not be so slow, or the user might prefer to fail/abort/skip them if they are too slow. I would think it's better to give them the option: maybe set a "global" default when they first create the client object, and allow them to override with an optional parameter, as in your example.

Title: Should timeout be a public static property or a parameter to every function?

Body:
TLDR: Should TIMEOUT be a public property on my static class, or a parameter to every function?

Background:
I am releasing a c# client-api library that facilitates communicating with our REST api.

The client-api consists of an object model and one large static class with a bunch of request extension methods for various types. 10 or so .Get() variations, a few .Post(), .Put(), etc.

This static class full of extension methods is preconfigured with our server URL, and some other static configuration constants related to the connection. Because all the functionality is exposed via extension methods, there's no need to create an instance of this class. Any configuration is done via static properties and affects all requests made by the application.

Problem:

Right now, all requests use a default timeout of 3 seconds (which seems generous to us, as our API is meant to be very responsive.) Some users with a bad connection though might want to wait longer for a response.

Our quick-fix solution is to expose the DEFAULT_TIMEOUT at a public static property on the class which can be set once on initialization, but is the proper thing to do to add a new optional parameter to every single one of our dozens of methods?

```<code>.Get(int timeout = DEFAULT_TIMEOUT) { ... }
.Get(..., int timeout = DEFAULT_TIMEOUT) { ... }
.Get(..., ..., int timeout = DEFAULT_TIMEOUT) { ... }
.Get(..., ..., ..., int timeout = DEFAULT_TIMEOUT) { ... }
...
.Post(..., int timeout = DEFAULT_TIMEOUT) { ... }
.Put(..., int timeout = DEFAULT_TIMEOUT) { ... }
.Save(..., int timeout = DEFAULT_TIMEOUT) { ... }
...
</code>```

On the one hand, we want to be flexible to whatever the consumer of our client-api library might need, but on the other hand, I won't want to get in the habit of polluting every method with every optional parameter that might impact a request (server url, authorization tokens, etc.)

What I don't want, is for the user to feel the need to do this:

```<code>ClientAPI.DEFAULT_TIMEOUT = 5000;
Thing found = new Thing(){ id = "19473" }.Get();
found.count += 1;
ClientAPI.DEFAULT_TIMEOUT = 20000;
found.Put();
ClientAPI.DEFAULT_TIMEOUT = 8000;
List<Widgets> widgets = found.GetSubresource("widgets");
...etc
</code>```

Is it reasonable to assume users won't be micromanaging timeouts for individual requests like that?


答:
I would hate to have only a global static setting because then you can have but a single timeout setting in an app and there might be times where you want to make that highly variable throughout the app. This is one reason I tend to prefer to avoid static API client implementations in favor if instance-based implementations.

One way to handle this would be to add a little fluent configuration. So your consumers can insert something. IE you could do:

```<code>var r = ClientAPI.WithTimeout(30).GetResource()
</code>```

And have pretty decent semantics without cluttering every method call with a bunch of optional parameters.

Body:
I would hate to have only a global static setting because then you can have but a single timeout setting in an app and there might be times where you want to make that highly variable throughout the app. This is one reason I tend to prefer to avoid static API client implementations in favor if instance-based implementations.

One way to handle this would be to add a little fluent configuration. So your consumers can insert something. IE you could do:

var r = ClientAPI.WithTimeout(30).GetResource()

And have pretty decent semantics without cluttering every method call with a bunch of optional parameters.


问:
Custom directive or ng-show/hide
On my form I have an icon which represents whether my entity is locked (shown by a locked padlock) or unlocked (an open padlock). At the model level, this is represented by a boolean property (isLocked). The user can toggle the entity between locked and unlocked by clicking the icon. This also updates the icon tool-tip text. This calls a controller method that toggles the entity.isLocked property. It is like a fancy kind of checkbox.

I can implement this in one of (at least) two ways:

1) Create a custom angular directive that changes the class of the icon element to show the correct icon and also sets the tool-tip text. The icon will then be a single DOM element in my view, decorated with the custom directive.

2) Put both the locked and unlocked icon elements in the DOM and show/hide each one using the custom ng-show directive.

Option 1 involves writing custom code which feels like the wrong thing to do, whereas option 2 makes maximum use of the built in Angular features, but leaves the HTML more cluttered.

In general, should I prefer the custom directive method (option 1) or the HTML method (option 2) or some other method? Which would be considered more idiomatic for Angular do you think? And, more importantly, why?

I did consider putting this on StackOverflow, but it feels like it would be considered off-topic there because it is a matter of opinion in the end...

答:
I like Option 1 better. I feel like when you are showing and hiding things by change classes thus through the CSS it is faster and easier to mange.

This also reduces the amount of elements on the DOM

Title: Custom directive or ng-show/hide


答:
You can actually use angular builtins here AND only have a single DOM element!

```<code><img ng-src="{{isLocked ? 'closed-padlock.png' : 'open-padlock.png'}}"
    alt="{{isLocked ? 'locked-text' : 'open-text'}}">
</code>```

This will conditionally change the image's src and alt properties based on whether or not isLocked is set. Admittedly the ternary expression is a touch messy but it's all presentation logic so I feel it belongs in the DOM like that.

Title: Custom directive or ng-show/hide

Body:
On my form I have an icon which represents whether my entity is locked (shown by a locked padlock) or unlocked (an open padlock). At the model level, this is represented by a boolean property (isLocked). The user can toggle the entity between locked and unlocked by clicking the icon. This also updates the icon tool-tip text. This calls a controller method that toggles the entity.isLocked property. It is like a fancy kind of checkbox.

I can implement this in one of (at least) two ways:

1) Create a custom angular directive that changes the class of the icon element to show the correct icon and also sets the tool-tip text. The icon will then be a single DOM element in my view, decorated with the custom directive.

2) Put both the locked and unlocked icon elements in the DOM and show/hide each one using the custom ng-show directive.

Option 1 involves writing custom code which feels like the wrong thing to do, whereas option 2 makes maximum use of the built in Angular features, but leaves the HTML more cluttered.

In general, should I prefer the custom directive method (option 1) or the HTML method (option 2) or some other method? Which would be considered more idiomatic for Angular do you think? And, more importantly, why?

I did consider putting this on StackOverflow, but it feels like it would be considered off-topic there because it is a matter of opinion in the end...

Body:
You can actually use angular builtins here AND only have a single DOM element!

<img ng-src="{{isLocked ? 'closed-padlock.png' : 'open-padlock.png'}}"
    alt="{{isLocked ? 'locked-text' : 'open-text'}}">

This will conditionally change the image's src and alt properties based on whether or not isLocked is set. Admittedly the ternary expression is a touch messy but it's all presentation logic so I feel it belongs in the DOM like that.


问:
DTOs matter on ASP.NET MVC JSON Action?
I recently came across an internal project where they were using DTOs throughout the solution, and when I sat down to implement a new MVC controller with a JSON REST endpoint I decided to use an anonymous object convention instead of declaring a discrete DTO class solely for the purpose of this API endpoint.

```<code>public JsonResult GetSomeSuch()
{
    // .. do work

    return Json(new {
        PropA = domainObj1.PropA,
        PropB = domainObj2.PropB
    });
}
</code>```

.. as opposed to the team convention, ..

```<code>public JsonResult GetSomeSuch()
{
    // do work ..

    return Json(new SomeSuchDTO2 {
        PropA = domainObj1.PropA,
        PropB = domainObj2.PropB
    }
}

// in some other file off in some other project and folder
public class SomeSuchDTO2 {
    public int PropA { get; set; }
    public string PropB { get; set; }
}
</code>```

Setting aside that I should have used a DTO here purely because it was already a team convention, team conventions trump best practices until team conventions change by team leadership, of which I was not yet a part. I'm not concerned about the social / team dynamic and consistency aspects so much as the technical value of details in specifically that point at which an action in C# becomes serialized to Javascript, as I have since moved on from that company.

The team convention was to return only DTOs and the DTOs were managed in a completely different project (among about 50 projects in the solution), I felt that in this case perpetuating that pattern was excessive and difficult to maintain. Further, my belief is that DRY must correlate with YAGNI; only refactor when you're repeating the same thing twice, as such you would only refactor to use a DTO if that same return object structure reflecting the same context is in fact needed elsewhere, not just possibly but actually, but since this is being serialized to Javascript where it will be consumed anyway there is really no point anyway.

I suppose a case can be made for DTOs as specification documentation, but when it becomes more of a maintenance chore to declare them and to look them up in their special folder in a project I would argue that there are more appropriate places and means to document the interface; indeed the anonymous object declaration seems to be documentation enough. I should also add that in our case everything was internal, this was a standalone project, so it's not like this was an externally exposed API.

I was wondering if there are other angles to this that I didn't consider as to why I should use DTOs, something reasonably convincing?

答:
A strong type system is supposed to help you

Using a strongly typed language is meant to prevent errors during runtime by catching them at compile time. Using an anonymous object (or dictionary for example) defeats this purpose and allows bugs to be compiled into the program that will only surface during runtime.

As an example take a look at the code below:

```<code>public object GetUsers() {
    var users = MyRepo.GetAll<User>();
    return new {
        count: users.Count(),
        items: users
    }
}

public object GetNewUsers() {
    var users = MyRepo.GetNewest<User>();
    return new {
        Count: users.Count(),
        items: users
    }
}
</code>```

The first response uses a lowercase count parameter where the second response contains an uppercase Count parameter. In a class where these methods may be separated by a few blocks of code it is very easy to miss this typo. Even worse this will happily compile and run. If we were to use a typed DTO instead this situation would not be possible (in fact it wouldn't even compile).

Or how about this example:

```<code>public object GetSystemInstallDate(){
    var date = AppHost.GetInstallDate();
    return new {
        date
    };
}
</code>```

What happens if we refactor to change the GetInstallDate method to return a DateTimeOffset instead of a DateTime object? The code will happily compile but the output to the client will have changed. This is a weak example but there's many other instances were things like this can happen. Numerical types, refactoring enums, etc...

Refactoring

If your anonymous response is used in more than one location you won't be able to refactor using the fancy tools like resharper. You will have to manually refactor which is never a fun task. If it is used in a single location the refactoring is easier but still more work than defining the class in the first place.

DRY

I would argue that by using anonymous types you are not protecting yourself against violating DRY; rather, you are making yourself more likely to violate it. An anonymous type can only be used in one place; however, if what that type represents is ever required elsewhere the entire type will have to be recreated.

By using a strongly typed object you only have to define the type in a single place and you then use that type where it is needed. This prevents you from having to repeat writing out all the property names, formatting values, etc...

```<code>public object GetTop10Movies() {
    return new { lastmodified = DateTime.Now, items }
}

public object GetNewest10Movies() {
    // We now have to repeat the previous anonymous object
}
</code>```

YAGNI

This is a guideline and not a rule. If it was a rule it would boil down to "ignore the future" which is always a recipe for disaster. At the same time trying to cover all possible future scenarios is a horrible idea and will lead to overly abstract and complicated codebase. The trick it to strike the right balance between thinking ahead and solving the problems at hand.

Another way of thinking about YAGNI in this situation is: Do you need compile time type safety?

I would argue that the work involved in creating a class to represent your response is only slightly more than the work involved in typing out an anonymous object. The complexity difference is essentially none (in fact with the C# world an anonymous object would most likely be considered a more complex route to take).

For a rather minimal time investment you get quite a few benefits that are real and usable to the developer. They may not be needed in the sense that without them the application won't function, but if you didn't need a strongly typed language I would question the use of C# in the first place.

Maintenance

The team convention was to return only DTOs and the DTOs were managed in a completely different project (among about 50 projects in the solution), I felt that in this case perpetuating that pattern was excessive and difficult to maintain.

I'm not sure where the difficulty in maintaining this pattern would come from except for the idea of having 50 projects all bundled into a single solution. You will have one of two situations:

A new response type is needed.

Add a new file to the DTO project representing your type and then use it in your application (a reference should already exist between the projects).

An existing response type is needed.

Start typing the namespace of the DTO assembly and select the type that you need.

I suppose a case can be made for DTOs as specification documentation, but when it becomes more of a maintenance chore to declare them and to look them up in their special folder in a project I would argue that there are more appropriate places and means to document the interface; indeed the anonymous object declaration seems to be documentation enough.

There's no better place to document your code than to have your code document itself. The name of your response DTO should describe what it is. Your anonymous declaration says nothing about what it represents, it only tells you what it contains. Having to look up external documentation (ala a website or help file) is even more cumbersome.

A box that consists of two bolts, two washers, and a nut doesn't describe what it is for at all. A box with the sticker "monitor wall mount" lets you know exactly what it is simply by looking at the packaging.

```<code>new { id, model }
// What is this? A vehicle? An economic model? Representation of DNA?

new Vehicle { id = id, model = model }
// Oh! A vehicle!
</code>```

Title: DTOs matter on ASP.NET MVC JSON Action?

Body:
A strong type system is supposed to help you

Using a strongly typed language is meant to prevent errors during runtime by catching them at compile time. Using an anonymous object (or dictionary for example) defeats this purpose and allows bugs to be compiled into the program that will only surface during runtime.

As an example take a look at the code below:

public object GetUsers() {
    var users = MyRepo.GetAll<User>();
    return new {
        count: users.Count(),
        items: users
    }
}

public object GetNewUsers() {
    var users = MyRepo.GetNewest<User>();
    return new {
        Count: users.Count(),
        items: users
    }
}

The first response uses a lowercase count parameter where the second response contains an uppercase Count parameter. In a class where these methods may be separated by a few blocks of code it is very easy to miss this typo. Even worse this will happily compile and run. If we were to use a typed DTO instead this situation would not be possible (in fact it wouldn't even compile).

Or how about this example:

public object GetSystemInstallDate(){
    var date = AppHost.GetInstallDate();
    return new {
        date
    };
}

What happens if we refactor to change the GetInstallDate method to return a DateTimeOffset instead of a DateTime object? The code will happily compile but the output to the client will have changed. This is a weak example but there's many other instances were things like this can happen. Numerical types, refactoring enums, etc...

Refactoring

If your anonymous response is used in more than one location you won't be able to refactor using the fancy tools like resharper. You will have to manually refactor which is never a fun task. If it is used in a single location the refactoring is easier but still more work than defining the class in the first place.

DRY

I would argue that by using anonymous types you are not protecting yourself against violating DRY; rather, you are making yourself more likely to violate it. An anonymous type can only be used in one place; however, if what that type represents is ever required elsewhere the entire type will have to be recreated.

By using a strongly typed object you only have to define the type in a single place and you then use that type where it is needed. This prevents you from having to repeat writing out all the property names, formatting values, etc...

public object GetTop10Movies() {
    return new { lastmodified = DateTime.Now, items }
}

public object GetNewest10Movies() {
    // We now have to repeat the previous anonymous object
}

YAGNI

This is a guideline and not a rule. If it was a rule it would boil down to "ignore the future" which is always a recipe for disaster. At the same time trying to cover all possible future scenarios is a horrible idea and will lead to overly abstract and complicated codebase. The trick it to strike the right balance between thinking ahead and solving the problems at hand.

Another way of thinking about YAGNI in this situation is: Do you need compile time type safety?

I would argue that the work involved in creating a class to represent your response is only slightly more than the work involved in typing out an anonymous object. The complexity difference is essentially none (in fact with the C# world an anonymous object would most likely be considered a more complex route to take).

For a rather minimal time investment you get quite a few benefits that are real and usable to the developer. They may not be needed in the sense that without them the application won't function, but if you didn't need a strongly typed language I would question the use of C# in the first place.

Maintenance

The team convention was to return only DTOs and the DTOs were managed in a completely different project (among about 50 projects in the solution), I felt that in this case perpetuating that pattern was excessive and difficult to maintain.

I'm not sure where the difficulty in maintaining this pattern would come from except for the idea of having 50 projects all bundled into a single solution. You will have one of two situations:

A new response type is needed.

Add a new file to the DTO project representing your type and then use it in your application (a reference should already exist between the projects).

An existing response type is needed.

Start typing the namespace of the DTO assembly and select the type that you need.

I suppose a case can be made for DTOs as specification documentation, but when it becomes more of a maintenance chore to declare them and to look them up in their special folder in a project I would argue that there are more appropriate places and means to document the interface; indeed the anonymous object declaration seems to be documentation enough.

There's no better place to document your code than to have your code document itself. The name of your response DTO should describe what it is. Your anonymous declaration says nothing about what it represents, it only tells you what it contains. Having to look up external documentation (ala a website or help file) is even more cumbersome.

A box that consists of two bolts, two washers, and a nut doesn't describe what it is for at all. A box with the sticker "monitor wall mount" lets you know exactly what it is simply by looking at the packaging.

new { id, model }
// What is this? A vehicle? An economic model? Representation of DNA?

new Vehicle { id = id, model = model }
// Oh! A vehicle!


问:
Storing a mailing address in a database: What structure should I use for International apps?
I will have international users use my database, but I don't know how the mailing system operates outside of the US.

Are the concepts "City", "State, Country and possibly "Zip" sufficient to capture any hierarchy (even if it was only 2 levels deep: (city/country)

答:
Like with everything, there is an international standard. In this case it's the ISO/IEC 19773 Part 08: Data structure for UPU postal data. But as usual with international standards, they are really complex. This one has 30 pages and defines about 50 possible elements which can be part of a complete postal address to cover any possible addressing scheme used somewhere in the world.

While this might be the correct way to store an address, it might not be the practicable one.

For an overview of how addresses in different countries look, you might want to take a look at the Wikipedia article about post addresses. As you see almost all countries use person, house-number, street and city (but there are a few odd cases, like Iran, where buildings have names instead of numbers or Japan, where some cities use coordinate systems). Additionally, some countries are divided into regions and a few divide them further into sub-regions. Most countries use zip-codes of different length, and you can usually expect them to carry the same information as region, subregion and city, but this information is usually still expected to verify that the zip-code is correct.

So what does that mean for the developer of a truly international address database? Be flexible. Make no field required and allow some optional general-purpose fields which can be used to represent regional quirks.


问:
Will loop constructs become obsolete?
By loop constructs I mean for… and while… constructs with nested statements.

Currently I am coding a tool in Python and decided out of curiosity not to use the regular loops - and rely on filter/map/reduce instead. E.g. now I have code like:

```<code>fields = filter(None, map(parse_field, struct_decl.get_children()))
</code>```

So far it works out fairly well and I like the way I am now designing the code - I have a clean-cut functions (though sometimes I need to use a lambda) and I do think that the resulting code might be more efficient (e.g. the iterations are more naturally independent making them more parallelizable). And I only have to increase indentation for conditionals (though I am thinking about avoiding them as well)

These new functions are not unique to Python - e.g. C++ had std::foreach for ages.

I wonder if traditional loops will eventually be frown upon in mainstream languages, similar to goto?

答:
I would say your assumption is correct. Mainstream languages pick up more and more functional features, and if you have constructs like higher order functions and lambdas/closures, the tasks concerning "looping" become just ordinary functions.

A good example for this development is Scala: It has while (mainly used for implementing fast library functions), but its foris not the "traditional" C-style one, but actually a for-comprehension similar to Haskell's, which can filter, map and "flatMap". Additionally collection classes have a bunch of methods like filter, map, foreach and more difficult stuff like flatMap or several versions of folding. Java 8 will introduce some similar features for collections (but of course not as much as Scala did).

While its not clear if traditional imperative loops will really disappear, their importance will drop considerably. The advantages are clear:

You can think on a "higher level" in terms of collections and their transformations, not about something like loop variables

Functions like foreachor map are less error-prone, as they encapsulate behavior, preventing e.g. one-off errors completely

Formerly awkward operations like looping simultaneously though collections become easier  (zip, zipWith), following the same functional style

Lazy collections (e.g. streams), which are potentially infinite data structures, don't work too well with traditional loops; the paradigm of "transformation" is much more natural for them than "looping"

You already mentioned parallelization

Title: Will loop constructs become obsolete?


问:
Should I write an interface API before an implementation?
I've been delving into more "organized" programming recently and I've been learning that I should be programming to an interface, not an implementation. With that in mind, would it be better to "sketch" out a project in interfaces before writing the implementation for it where possible?

And if this is the case, in the case of using 3rd party libraries (ie Lidgren), should I be wrapping those in interfaces as well and resolve them through IOC containers, or is it OK to expose them to the interfaces?

答:
Programming against a contract is almost always a good idea.  That contract need not be an interface, it can be fulfilled by a class instead.  In my opinion, interfaces have become somewhat overused along with DI due to unit testing concerns and mocking frameworks.

I personally prefer to only bring in interfaces when I very likely could have or do have more than 1 implementation of a contract.  Interfaces are great for repositories where I wish to abstract away data access, but probably less so for my standard business logic which is likely to be relatively inflexible.

Now not having an interface can cause problems with unit testing, especially for purists. But I'm interested in mocking the external dependencies of my programs, not its internal dependencies.  I want my tests to perform validation of the code, not echo the code structure.


答:
I would suggest having your wrapper class be non-static, with timeout being implemented as an instance field.  That's how, for example, HttpClient.TimeOut works.  Users can create a static instance of the service class if they wish.  If needed for backwards compatibility, it would be easy for you to create a static class which behaves identically to the current class (i.e., the static class would have a static instance of your new class, and would call into it for everything).

This approach has numerous advantages:

1.  Avoids polluting the method signature.

2.  Makes testing and dependency injection easier.

3.  Reduces coupling.


问:
How exactly can I check for new rows in sql with ajax?
How do certain services, just like google plus and facebook, check for new content without reloading the page? Whenever you are on any of those websites a new notification of a post related content just pops up without the need to refresh the page. Can someone give me some tips on how this works? :)</p>

答:
You use ajax with php. You get the rows from php and use ajax post to get the results.
Let me show you:
Include this in the page you want to do the reloading.

Link to ajax
this will call the ajax version 1.7.2.
I got this little code from the internet :( but it will suffice to show you.

```<code><script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('/path/to/your/php/file/load.php');
}, 3000); // the "3000" here refers to the time to refresh the div.  it is in milliseconds.
});
// ]]></script>
</code>```

And here is the div that will be refreshed

Loading .....

and finally the load.php

```<code>//get some content from the database
//I just ordered by time so you can get the latest  items and limit by 10 if they overflow
$sql = "SELECT * FROM `your_table` ORDER BY time DESC LIMIT 10";
//get them or show an error if something went wrong
$rows = mysq_query($sql) or die(mysql_error());
while($r = mysql_fetch_assoc($rows)){
$content = $r['content'];
echo $content;

}
</code>```

Body:
You use ajax with php. You get the rows from php and use ajax post to get the results.
Let me show you:
Include this in the page you want to do the reloading.

Link to ajax
this will call the ajax version 1.7.2.
I got this little code from the internet :( but it will suffice to show you.

<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('/path/to/your/php/file/load.php');
}, 3000); // the "3000" here refers to the time to refresh the div.  it is in milliseconds.
});
// ]]></script>

And here is the div that will be refreshed

Loading .....

and finally the load.php

//get some content from the database
//I just ordered by time so you can get the latest  items and limit by 10 if they overflow
$sql = "SELECT * FROM `your_table` ORDER BY time DESC LIMIT 10";
//get them or show an error if something went wrong
$rows = mysq_query($sql) or die(mysql_error());
while($r = mysql_fetch_assoc($rows)){
$content = $r['content'];
echo $content;

}


答:
Use a single plain text field!

Unless you're constructing a database for delivery optimization or other highly-local use, you should just go ahead and store the complete address as a text field with standard line breaks.

If there is additional information that you need, such as a zip code or street for sorting and grouping so you get a bulk mail discount, you can either store that in an additional field, or just determine it at mail-time by way of some fairly simple logic.  (Or you could give each address a permanent key, and have for-discount information provided by way of other tables.)

Now, I'm not saying that you shouldn't provide some multi-part address form with city and state lists and perhaps an automatic reference to a country's postal service address API, but you didn't ask about how to construct a form for user input, you asked how to store the address in a database.

Of course, if you do that form you might want to store a JSON or XML blob so the fields can be re-populated, but that's not data that your database itself necessarily needs to care about...

Title: Storing a mailing address in a database: What structure should I use for International apps?

Body:
I will have international users use my database, but I don't know how the mailing system operates outside of the US.

Are the concepts "City", "State, Country and possibly "Zip" sufficient to capture any hierarchy (even if it was only 2 levels deep: (city/country)


问:
What is the real responsibility of a class?
I keep wondering if it is legitimate to use verbs that are based on nouns in OOP.

I came across this brilliant article, though I still disagree with the point it makes.

To explain the problem a bit more, the article states that there shouldn't be, for instance, a FileWriter class, but since writing is an action it should be a method of the class File. You'll get to realize that it's often language dependent since a Ruby programmer would likely be against the use of a FileWriter class (Ruby uses method File.open to access a file), whereas a Java programmer wouldn't.

My personal (and yes, very humble) point of view is that doing so would break the Single Responsibility principle. When I programmed in PHP (because PHP is obviously the best language for OOP, right?), I would often use this kind of framework:

```<code><?php

// This is just an example that I just made on the fly, may contain errors

class User extends Record {

    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

}

class UserDataHandler extends DataHandler /* knows the pdo object */ {

    public function find($id) {
         $query = $this->db->prepare('SELECT ' . $this->getFields . ' FROM users WHERE id = :id');
         $query->bindParam(':id', $id, PDO::PARAM_INT);
         $query->setFetchMode( PDO::FETCH_CLASS, 'user');
         $query->execute();
         return $query->fetch( PDO::FETCH_CLASS );
    }

}

?>
</code>```

It is my understanding that the suffix DataHandler doesn't add anything relevant; but the point is that the single responsibility principle dictates us that an object used as a model containing data (may it be called a Record) shouldn't also have the responsibility of doing SQL queries and DataBase access. This somehow invalidates the ActionRecord pattern used for instance by Ruby on Rails.

I came across this C# code (yay, fourth object language used in this post) just the other day:

```<code>byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
</code>```

And I gotta say that it doesn't make much sense to me that an Encoding or Charset class actually encodes strings. It should merely be a representation of what an encoding really is.

Thus, I would tend to think that:

It is not a File class responsibility to open, read or save files.

It is not a Xml class responsibility to serialize itself.

It is not a User class responsibility to query a database.

etc.

However, if we extrapolate these ideas, why would Object have a toString class? It's not a Car's or a Dog's responsibility to convert itself to a string, now is it?

I understand that from a pragmatic point of view, getting rid of the toString method for the beauty of following a strict SOLID form, that makes code more maintainable by making it useless, is not an acceptable option.

I also understand that there may not be an exact answer (which would more be an essay than a serious answer) to this, or that it may be opinion-based. Nevertheless I would still like to know if my approach actually follows what the single-responsibility principle really is.

What's a class's responsibility?

答:
All too often the Single Responsibility Principle becomes a Zero Responsibility Principle, and you end up with Anemic Classes that do nothing (except setters and getters), which leads to a Kingdom of the Nouns disaster.

You'll never get it perfect, but better for a class to do a bit too much than too little.

In you example with Encoding, IMO, it definitely should be able to encode.  What do you thing it should do instead?  Just having a name "utf" is zero responsibility.  Now, maybe the name should be Encoder.  But,as Konrad said, data (which encoding) and behavior (doing it) belong together.


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
Code Formatting

```<code>Don't     get    me   wrong             ,
code      should be   consistent        &
readable                                ,
but       some   take it         too far.
</code>```

Body:
Code Formatting

Don't     get    me   wrong             ,
code      should be   consistent        &
readable                                ,
but       some   take it         too far.


答:
Your company started wrong. The scrum master should be part of the team.

By hiring a full time scrum master, all you did is add another layer between the team and management/stake holders. Totally not Agile.

One person from the team, normally the manager, who is also part of the team, takes the role of scrum master. But it really is not a 'title'. it is a role that anyone can fill as needed. In one team we used to rotate it every month.

Now, this answers all the questions. The SM being part of the team, he takes part in all the team does. easy.

being a SM is just a menial job of following up things externally to the team. So the SM usually takes a little less work because he will be the one being interrupted all the time by external communication and sending emails like "any updates on this ask?". nothing more.

Snake oil salesman that saw the opportunity of selling themselves as full time scrum masters are the scum of the earth and goes completely against Agile, as you noted.

Title: How does the Scrum Master participate in Daily Stand-Ups?

Body:
We have a professional Scrum Master consultant [*] who recently joined our project. Unfortunately, we don't know her name (she never introduced herself to us, she just came in one day and said "we are having a daily stand-up"), and she doesn't seem to do much else except chair a daily stand up meeting  - when I half-jokingly asked her to also give daily feedback in the meeting, she was quite affronted, saying it's the Scrum Master's job to "facilitate, not participate".

This seems fairly anti-Agile (having worked on other agile projects, where the teams were self directed), which is supposed to be egalitarian, but I am not sure about how it works in the Scrum Methodology. I suspect she doesn't do much all day, and that's the reason for her defensiveness on this issue.

Does the Scrum Master take part in the "yesterday, today, impediments" spiel during the stand-up meeting, or is their role to just chair ("facilitate") the meeting?

[*] We weren't actually told what her job is, we just assume, since she calls herself the Scrum Master