答:
There are several ways to optimize for what you are doing:

Query for many, don't do a select * from teams where id = ?, do a select * from teams where id in (?). Your default method's implementation receives a List and does the later, the overloaded method for a single id turns the id into a List of size 1 and calls the method that takes the List as parameter. From the way I see it, you are doing the inverse.

You might never need ALL of it, you said it yourself, you use pagination, so the max possible is defined by whatever max page size you have.

But... if you need to request for that many consider taking a look a the Flyweight pattern, where you can store the data in a random data structure of your choosing, and use a single object to access the data with the same interface as you would with N objects.

Use a model, remember that Model in MVC (if you are using MVC at all) doesn't stand for database, but just data. A model can act as a facade for your most complex queries and avoid you unnecessary pain in the Controllers (see "fat model skinny controller" principle)


问:
Where does Java get its SOA reputation from?
I see lots of SOA books surrounding Java and have always had the subliminal notion that Java is the "right" language for robust/enterprisey SOA, even though I know what SOA involves and  that it is perfectly possible using other languages & frameworks.

What exclusive traits Java has that other languages/platforms don't, that makes it so popular for SOAs?

答:
Simply because many of the first systems that were being connected using SOA techniques were in already built in Java. There's nothing inherit in Java that makes it a superior language for SOA solutions.

Some might argue that it's rich ecosystem of BDD/TDD frameworks and community around that helped build more robust SOA solutions, but then again I've seen plenty of terrible ones :-).

In short SOA is an architectural design pattern that is language agnostic.

ContentLicense: CC BY-SA 3.0


问:
Should a programmer take writing lessons to enhance code expressiveness?
Given that programmers are authors and write code to express abstract thoughts and concepts, and good code should be read by other programmers without difficulties and misunderstandings, should a programmer take writing lessons to write better code?

Abstracting concepts and real world problems/entities is an important part of writing good code, and a good mastery of the language used for coding should allow the programmer to express his thoughts more easily, or in a better way. Besides, when trying to write or rewrite some code to make it better, much time can be spent in deciding the names for functions, variables or data structures.

I think this could also help to avoid writing code with more than one meaning, often cause of misunderstanding between different programmers. Code should always express clearly its function unambiguously.

答:
I don't think that will help; creative writing is about plots and character development and dialog, not about expressing technical concepts with clarity. Technical writing might help, but I doubt it - they're just very different kinds of writing!

and note that "readable" code is subjective, and primarily a matter of syntactic style and common idioms (which vary among languages and even among teams)

choosing good names for variables and classes and methods, however, is important. Every developer becomes, to some degree, a subject-matter expert in certain aspects of the domain under development, so correct usage of domain terminology is critical.

peer reviews can help you build vocabulary and confidence


问:
Why do we have to use break in switch?
Who decided (and based on what concepts) that switch construction (in many languages) has to use break in each statement?

Why do we have to write something like this:

```<code>switch(a)
{
    case 1:
        result = 'one';
        break;
    case 2:
        result = 'two';
        break;
    default:
        result = 'not determined';
        break;
}
</code>```

(noticed this in PHP and JS; there are probably many other languages using this)

If switch is an alternative of if, why we can't use the same construction as for if? I.e.:

```<code>switch(a)
{
    case 1:
    {
        result = 'one';
    }
    case 2:
    {
        result = 'two';
    }
    default:
    {
        result = 'not determined';
    }
}
</code>```

It is said that break prevents the execution of the block following the current one. But, does someone really run into the situation, where there was any need for execution of the current block and following ones? I didn't. For me, break is always there. In every block. In every code.

答:
Because switch is not an alternative of if ... else statements in those languages.

By using switch, we can match more than one condition at a time, which is highly appreciated in some cases.

Example:

```<code>public Season SeasonFromMonth(Month month)
{
    Season season;
    switch (month)
    {
        case Month.December:
        case Month.January:
        case Month.February:
            season = Season.Winter;
            break;

        case Month.March:
        case Month.April:
        case Month.May:
            season = Season.Spring;
            break;

        case Month.June:
        case Month.July:
        case Month.August:
            season = Season.Summer;
            break;

        default:
            season = Season.Autumn;
            break;
    }

    return season;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Why do we have to use break in switch?

Body:
Because switch is not an alternative of if ... else statements in those languages.

By using switch, we can match more than one condition at a time, which is highly appreciated in some cases.

Example:

public Season SeasonFromMonth(Month month)
{
    Season season;
    switch (month)
    {
        case Month.December:
        case Month.January:
        case Month.February:
            season = Season.Winter;
            break;

        case Month.March:
        case Month.April:
        case Month.May:
            season = Season.Spring;
            break;

        case Month.June:
        case Month.July:
        case Month.August:
            season = Season.Summer;
            break;

        default:
            season = Season.Autumn;
            break;
    }

    return season;
}


答:
1. Writing lessons? Not really.

Writing source code is different enough from writing a book.

While both pursue the same goals: being as unambiguous as possible and being easy to understand, they are doing it in a very different manner, and things a writer should learn are not the same as things a software developer should learn.

Example 1: figures of speech

Figures of speech are valuable when writing novels, poetry, etc., since they increase the expressiveness of the writing.

What is the last time you've seen an oxymoron or a litotes in source code? Would it help to have them, or would it rather be extremely harmful for any developer who will have to maintain such source code later?

Example 2: vocabulary

Rich vocabulary is highly appreciated in literature. Vocabulary of William Shakespeare, for example, is twenty thousand to twenty-five thousand words. Richer vocabulary makes it more interesting to read a novel or a poem.

When you write source code, you expect it to be read by people who don't speak English very well. Showing how well you know English would be extremely harmful for your code. If you know a fancy word which means exactly what you need but you know that lots of people don't know the meaning of this word, you should rather find a less expressive synonym or a set of words which explain the meaning. A vocabulary of a few thousands of words is often largely enough for a given project.

Note an important aspect: while Google Translate could be of a great help for a non-native speaker, there are two issues with any translator:

A pair of languages don't necessarily have a 1:1 match between the words. Some words have either no translation in other languages whatsoever, or multiple words could translate into a single word in a foreign language. For instance, in Russian, there is a huge amount of words which target specific states of snow and cold weather, and translating them in French or Spanish is usually impossible without losing their specificity.

A word sometimes has multiple meanings, and the meaning is deduced from the context. Google Translate, despite its high quality, is usually unable to indicate the meaning for any but the most basic situations.

Example 3: expressions

Expressions make prose richer as well. An author expects a reader to have a given amount of general culture, and uses this opportunity to make the text more expressive.

Similarly to the previous example, such expressions could be very problematic when read by people who are not native speakers. But if general vocabulary can usually be translated, expressions are much more problematic.

For instance, English is not my first language, and on daily basis, I encounter expressions, including here on StackExchange, that I don't know. I try to guess their meaning, and sometimes I'm right. But sometimes I'm wrong, and Googling those expressions doesn't help.

A user in her/his comment reminded me of an example which made me suffer for a long time when I just started programming: PHP's needle and haystack. I was unaware of the corresponding figure of speech, so every time when I was reading the documentation, I was wondering what is this all about. Needless to say that C#'s sequence.Contains(element) or the excellent Python's element in sequence are a much better alternative. Well, at least, developers who don't know Hebrew had to suffer from PHP too, but this is a different story.

Example 4: cultural references

Cultural references. In literature, it is tempting to include elements from a given culture, and this too makes the book richer and sometimes more interesting to read.

However, code is addressed to developers from all around the world. Therefore, what is an obvious reference for an Italian developer may not be that obvious for a Russian one, and what every Indian boy or girl knows may not necessarily be known by an American programmer.

The same user who talked about the needle and the haystack gave an excellent example of such cultural reference too: the Grail. Who doesn't know what Grail is? Well, I mean, it's “Graal” in French, “Grial” in Spanish and... “Kutsal Kâse” in Turkish, but still. However, how much American or European developers know the medieval history of China or India? Why would anyone assume that every Chinese and Indian programmer has to know the Holy Grail reference?

2. Lessons to write expressive source code? Sure.

Any developer should learn how to write expressive source code.

Any developer should explain why the comment in:

```<code>int j = i + 1; // Creating i and adding 1 to it.
</code>```

is bad, even aside the fact that it's totally wrong.

Any developer should be able to understand the basic refactoring and how it helps making the source code more expressive.

Any developer should remember that 20% of the time is spent developing code, and 80% of the time maintaining it. For some projects, it's more like 5% - 95%.

etc.

In essence, programming is close to technical documentation. Does a person who writes a spec sheet for a bolt need to take writing lessons? Not really. The same applies for developers. Anyone should write without making spelling mistakes in every word, and anyone should be able to communicate her ideas clearly enough. Aside that, I'm not sure how writing lessons would be more useful than, let's say, a course in Computer science or in IT security or whatsoever.

The expressiveness of the source code can be learnt by other means. superM mentioned one of them in his answer: reading good code. I can mention a few others:

Reading books like Beautiful Code or Code Complete,

Asking for a more experienced developer to review your code,

Understanding patterns and how and when to use them.

Title: Should a programmer take writing lessons to enhance code expressiveness?

Body:
Given that programmers are authors and write code to express abstract thoughts and concepts, and good code should be read by other programmers without difficulties and misunderstandings, should a programmer take writing lessons to write better code?

Abstracting concepts and real world problems/entities is an important part of writing good code, and a good mastery of the language used for coding should allow the programmer to express his thoughts more easily, or in a better way. Besides, when trying to write or rewrite some code to make it better, much time can be spent in deciding the names for functions, variables or data structures.

I think this could also help to avoid writing code with more than one meaning, often cause of misunderstanding between different programmers. Code should always express clearly its function unambiguously.

Body:
1. Writing lessons? Not really.

Writing source code is different enough from writing a book.

While both pursue the same goals: being as unambiguous as possible and being easy to understand, they are doing it in a very different manner, and things a writer should learn are not the same as things a software developer should learn.

Example 1: figures of speech

Figures of speech are valuable when writing novels, poetry, etc., since they increase the expressiveness of the writing.

What is the last time you've seen an oxymoron or a litotes in source code? Would it help to have them, or would it rather be extremely harmful for any developer who will have to maintain such source code later?

Example 2: vocabulary

Rich vocabulary is highly appreciated in literature. Vocabulary of William Shakespeare, for example, is twenty thousand to twenty-five thousand words. Richer vocabulary makes it more interesting to read a novel or a poem.

When you write source code, you expect it to be read by people who don't speak English very well. Showing how well you know English would be extremely harmful for your code. If you know a fancy word which means exactly what you need but you know that lots of people don't know the meaning of this word, you should rather find a less expressive synonym or a set of words which explain the meaning. A vocabulary of a few thousands of words is often largely enough for a given project.

Note an important aspect: while Google Translate could be of a great help for a non-native speaker, there are two issues with any translator:

A pair of languages don't necessarily have a 1:1 match between the words. Some words have either no translation in other languages whatsoever, or multiple words could translate into a single word in a foreign language. For instance, in Russian, there is a huge amount of words which target specific states of snow and cold weather, and translating them in French or Spanish is usually impossible without losing their specificity.

A word sometimes has multiple meanings, and the meaning is deduced from the context. Google Translate, despite its high quality, is usually unable to indicate the meaning for any but the most basic situations.

Example 3: expressions

Expressions make prose richer as well. An author expects a reader to have a given amount of general culture, and uses this opportunity to make the text more expressive.

Similarly to the previous example, such expressions could be very problematic when read by people who are not native speakers. But if general vocabulary can usually be translated, expressions are much more problematic.

For instance, English is not my first language, and on daily basis, I encounter expressions, including here on StackExchange, that I don't know. I try to guess their meaning, and sometimes I'm right. But sometimes I'm wrong, and Googling those expressions doesn't help.

A user in her/his comment reminded me of an example which made me suffer for a long time when I just started programming: PHP's needle and haystack. I was unaware of the corresponding figure of speech, so every time when I was reading the documentation, I was wondering what is this all about. Needless to say that C#'s sequence.Contains(element) or the excellent Python's element in sequence are a much better alternative. Well, at least, developers who don't know Hebrew had to suffer from PHP too, but this is a different story.

Example 4: cultural references

Cultural references. In literature, it is tempting to include elements from a given culture, and this too makes the book richer and sometimes more interesting to read.

However, code is addressed to developers from all around the world. Therefore, what is an obvious reference for an Italian developer may not be that obvious for a Russian one, and what every Indian boy or girl knows may not necessarily be known by an American programmer.

The same user who talked about the needle and the haystack gave an excellent example of such cultural reference too: the Grail. Who doesn't know what Grail is? Well, I mean, it's “Graal” in French, “Grial” in Spanish and... “Kutsal Kâse” in Turkish, but still. However, how much American or European developers know the medieval history of China or India? Why would anyone assume that every Chinese and Indian programmer has to know the Holy Grail reference?

2. Lessons to write expressive source code? Sure.

Any developer should learn how to write expressive source code.

Any developer should explain why the comment in:

int j = i + 1; // Creating i and adding 1 to it.

is bad, even aside the fact that it's totally wrong.

Any developer should be able to understand the basic refactoring and how it helps making the source code more expressive.

Any developer should remember that 20% of the time is spent developing code, and 80% of the time maintaining it. For some projects, it's more like 5% - 95%.

etc.

In essence, programming is close to technical documentation. Does a person who writes a spec sheet for a bolt need to take writing lessons? Not really. The same applies for developers. Anyone should write without making spelling mistakes in every word, and anyone should be able to communicate her ideas clearly enough. Aside that, I'm not sure how writing lessons would be more useful than, let's say, a course in Computer science or in IT security or whatsoever.

The expressiveness of the source code can be learnt by other means. superM mentioned one of them in his answer: reading good code. I can mention a few others:

Reading books like Beautiful Code or Code Complete,

Asking for a more experienced developer to review your code,

Understanding patterns and how and when to use them.


答:
This has been asked on Stack Overflow in the context of C: Why was the switch statement designed to need a break?

To summarize the accepted answer, it was probably a mistake. Most other languages have probably just followed C. However, some languages such as C# seem to have fixed this by allowing fall-through – but only when the programmer explicitly tells so (source: the link above, I don't speak C# myself).

Title: Why do we have to use break in switch?

Body:
Who decided (and based on what concepts) that switch construction (in many languages) has to use break in each statement?

Why do we have to write something like this:

```<code>switch(a)
{
    case 1:
        result = 'one';
        break;
    case 2:
        result = 'two';
        break;
    default:
        result = 'not determined';
        break;
}
</code>```

(noticed this in PHP and JS; there are probably many other languages using this)

If switch is an alternative of if, why we can't use the same construction as for if? I.e.:

```<code>switch(a)
{
    case 1:
    {
        result = 'one';
    }
    case 2:
    {
        result = 'two';
    }
    default:
    {
        result = 'not determined';
    }
}
</code>```

It is said that break prevents the execution of the block following the current one. But, does someone really run into the situation, where there was any need for execution of the current block and following ones? I didn't. For me, break is always there. In every block. In every code.


问:
What are the most impressive tricks an IDE could pull off with the code?
Modern IDEs have a lot of tricks up their sleeves to help with code writing, refactoring,  searching. All those are very helpful, but rarely any of them looks like a real "magic" and makes me think "Wow! How did it figure that out?"

Can you name any impressive IDE code automation (or other) features that blew your mind first time you saw them?

答:
Whyline

Whyline for Java really impressed me when I saw it. It's a dynamic analysis tool that lets you ask questions about the program's output, and not just text, but graphics too. For example, you can ask "why was that line red?" or "why didn't the paint method get called?"

It works by instrumenting your program and recording a run. For example, suppose there's a bug you can reproduce. You instrument your program with Whyline, run your program in Whyline to reproduce the bug, and then when you quit the program, you can use Whyline to inspect the execution history.

This recording and playback isn't new, but how Whyline implements it is pretty slick. You can view the history according to specific events (e.g. focusing on only mouse drag events, or only keydown events). It also associates output with what part of the program printed it, so you can navigate from the output to the code.

To work, it uses program slicing, so that you can focus on the parts of the code that are actually relevant. CMU now has a patent on it, and I don't know what their plans are, but I hope we can see more of it in production. It's a memory hog, but that's likely because it's a prototype and it can improve.

You should see the demo online, but you should also try it out for yourself to get the full experience. If anything, the online demos undersell the idea.

ContentLicense: CC BY-SA 2.5


问:
Project frozen - what should I leave to the people after me?
So the project I've been working on is now going to be frozen indefinitely. It is possible that if and when the project unfreezes again, it won't be assigned to me or anybody from the current team. Actually, we inherited the project after it had been frozen before, but there was nothing left by the prior team to help us understand even the basic needs of the project, so we wasted a lot of time getting to know the project well. My question is what do you think we should do to help the people after us to best understand the needs of the project, what we have done, why we've done it, etc. I am open to other ideas of why should we leave some tracks to the others that will work on this project also.

Some steps we already have taken:

technical documentation (not full but at least there is some);

source-control system history;

estimations on which parts of the project need improvement and why we think so;

bunch of unit tests.

issue tracker with all the tickets we've done (EDIT)

What do you think of what we've already prepared and what else can we do?

答:
Some more things to consider

Is the project directory structure sane?  Have you revised the code comments? Is the commit     log someway presentable?

Gerneral purpose overview (as opposed to technical, which you have
started), Advised reading on the project, project history ( its
development cycle, previous project managers, list of staff,
requirements/feature specification)

UML diagrams, class diagrams, work flow diagrams!

Reasons the project has been frozen is always nice.

Development environment, IDEs that have been used, build tools, these are covered in the technical docs right?

I just thought of some of the things I would have liked to see on a project I recently inherited. What you have already provided is a hell of a lot more than what I got. You will receive major karma points for helping the next team out :)


答:
I will answer with an example. If you wanted to list the number of days for each month of a year, it is obvious that some months have 31, some 30, and 1 28/29. It would look like this,

```<code>switch(month) {
    case 4:
    case 6:
    case 9:
    case 11;
        days = 30;
        break;
    case 2:
        //Find out if is leap year( divisible by 4 and all that other stuff)
        days = 28 or 29;
        break;
    default:
        days = 31;
}
</code>```

This is an example where multiple cases have the same effect and are all grouped together. There was obviously a reason for the choice of the break keyword and not the
if ... else if construct.

The main thing to take note here is that a switch statement with many similar cases is not an if ... else if ... else if ... else for each of the cases,  but rather if(1, 2, 3) ... else if(4,5,6) else ...

Title: Why do we have to use break in switch?

Body:
I will answer with an example. If you wanted to list the number of days for each month of a year, it is obvious that some months have 31, some 30, and 1 28/29. It would look like this,

switch(month) {
    case 4:
    case 6:
    case 9:
    case 11;
        days = 30;
        break;
    case 2:
        //Find out if is leap year( divisible by 4 and all that other stuff)
        days = 28 or 29;
        break;
    default:
        days = 31;
}

This is an example where multiple cases have the same effect and are all grouped together. There was obviously a reason for the choice of the break keyword and not the
if ... else if construct.

The main thing to take note here is that a switch statement with many similar cases is not an if ... else if ... else if ... else for each of the cases,  but rather if(1, 2, 3) ... else if(4,5,6) else ...


答:
There are two situations where “fall through” from one case to another can happen - the empty case:

```<code>switch ( ... )
{
  case 1:
  case 2:
    do_something_for_1_and_2();
    break;
  ...
}
</code>```

and the non-empty case

```<code>switch ( ... )
{
  case 1:
    do_something_for_1();
    /* Deliberately fall through */
  case 2:
    do_something_for_1_and_2();
    break;
...
}
</code>```

Notwithstanding the reference to Duff's Device, legitimate instances for the second case are few and far between, and generally prohibited by coding standards and flagged during static analysis.  And where it is found, it is more often than not due to the omission of a break.

The former is perfectly sensible and common.

To be honest, I can see no reason for needing the break and the language parser knowing that an empty case-body is a fall through, while a non-empty case is standalone.

It is a pity that the ISO C panel seem more preoccupied with adding new (unwanted) and badly defined features to the language, rather than fixing the undefined, unspecified or implementation-defined features, not to mention the illogical.

Title: Why do we have to use break in switch?

Body:
There are two situations where “fall through” from one case to another can happen - the empty case:

switch ( ... )
{
  case 1:
  case 2:
    do_something_for_1_and_2();
    break;
  ...
}

and the non-empty case

switch ( ... )
{
  case 1:
    do_something_for_1();
    /* Deliberately fall through */
  case 2:
    do_something_for_1_and_2();
    break;
...
}

Notwithstanding the reference to Duff's Device, legitimate instances for the second case are few and far between, and generally prohibited by coding standards and flagged during static analysis.  And where it is found, it is more often than not due to the omission of a break.

The former is perfectly sensible and common.

To be honest, I can see no reason for needing the break and the language parser knowing that an empty case-body is a fall through, while a non-empty case is standalone.

It is a pity that the ISO C panel seem more preoccupied with adding new (unwanted) and badly defined features to the language, rather than fixing the undefined, unspecified or implementation-defined features, not to mention the illogical.


答:
A virtualmachine image (i.e. vm-ware) of a running-stand-alone developping system might be quite valuable.

Last year i was asked to fix some vb3 code. It was quite difficuilt to re create a running system with vb3, windows95 and a lot of installed ole-controlls. After a week I gave up :-(

[Update]

Has anybody experince with converting old virtual-machine images so that it can be played in a newer virtual-machine-player?

You also have to consider that it might not be possible any more to run a very old image on a modern hardware/guest os.

Title: Project frozen - what should I leave to the people after me?

Body:
So the project I've been working on is now going to be frozen indefinitely. It is possible that if and when the project unfreezes again, it won't be assigned to me or anybody from the current team. Actually, we inherited the project after it had been frozen before, but there was nothing left by the prior team to help us understand even the basic needs of the project, so we wasted a lot of time getting to know the project well. My question is what do you think we should do to help the people after us to best understand the needs of the project, what we have done, why we've done it, etc. I am open to other ideas of why should we leave some tracks to the others that will work on this project also.

Some steps we already have taken:

technical documentation (not full but at least there is some);

source-control system history;

estimations on which parts of the project need improvement and why we think so;

bunch of unit tests.

issue tracker with all the tickets we've done (EDIT)

What do you think of what we've already prepared and what else can we do?


问:
Why is the rec keyword needed in F#?
In F# it is necessary to use the rec keyword. In Haskell  there is no need to explicitly tell if a given function is recursive or not.

Given the role of recursion in functional programming, the F# design seems rather odd to me.  Is it a good language design decision or does it only exist for historical reason or because of an implementation constraint?

答:
A recursive let defines a significantly more complicated semantics than a normal one. Therefore, for a sake of simplicity and clean language design, there is a good reason to have both, just the same as having separate let, let* and letrec in Scheme.

Simple let x = y in z is equivalent to ((fun x -> z) y). A recursive let is much more complicated and may involve using a fixed point combinator.

Title: Why is the rec keyword needed in F#?


问:
What's a good model for continuous manager <-> programmer feedback?
Is it important for managers to give devs regular feedback on how they're doing and vice versa? I say vice versa because I consider employees to be responsible to their manager, and managers to be responsible to their employees. Everyone seems to think this is a good idea but in practice I rarely see it happen because so many shops are "agile" now and that usually means a daily standup plus a weekly kickoff, etc. So one-on-ones just don't happen.

In my last position I had my first one-on-one w/ my manager 6 months after I'd been w/ the company. It turned out there was lots of misunderstanding, misalignment and confusion built up and snowballed. Not really surprising when there's no direct personal communication for that long.

答:
Yes, one-to-ones are very important, above and beyond the meetings Scrum dictates.

Daily standups give daily feedback on the state of the project. Iteration planning meetings are specifically for planning the next iteration. Even retrospectives concern what we as a team are doing well or can do better.

Nothing in Scrum encourages a manager to sit down, preferably out of the office environment, with each individual and talk to them. This should be a regular opportunity for stopping small problems from snowballing (because no one likes surprises at review time), but MUCH more importantly it should be a way to get feedback on how you are doing as a manager, what you can do to improve individuals' lives, and what you aren't aware of in the team (perhaps a team member who isn't performing).

The experience you had is not unique, not by any stretch of the imagination.

Rands in Repose did a good article on healthy 1-to-1 cultures a couple of years ago.

The sound that surrounds successful regimen of 1:1s is silence. All of the listening, questioning, and discussion that happens during a 1:1 is managerial preventative maintenance. You’ll see when interest in a project begins to wane and take action before it becomes job dissatisfaction. You’ll hear about tension between two employees and moderate a discussion before it becomes a yelling match in a meeting. Your reward for a culture of healthy 1:1s is a distinct lack of drama.


答:
It's just everyone else is doing SOA without explicitly naming it so, without strict formalizing etc. People build RESTful services and back-end using message queues without mentioning "SOA" even once. The keywords are rather "loose coupling" or "web services".

On the other hand it seems, that in Java world there's a need for buzzword (or rather buzz-acronym) for everything, every design pattern, every architecture etc. Thus so many books where Java and SOA are mentioned together.

Title: Where does Java get its SOA reputation from?

Body:
I see lots of SOA books surrounding Java and have always had the subliminal notion that Java is the "right" language for robust/enterprisey SOA, even though I know what SOA involves and  that it is perfectly possible using other languages & frameworks.

What exclusive traits Java has that other languages/platforms don't, that makes it so popular for SOAs?


答:
basic English and grammar is sufficient for a programmer from my point of view.
But then any thing to break a monotonous programming routine will always be rejuvenating and so the writing lessons will be relaxing for the programmers. </p>


答:
C was one of the first languages to have the switch statement in this form, and all other major languages inherited it from there, mostly choosing to keep the C semantics per default - they either didn't think of the advantages of changing it, or judged them less important than keeping the behaviour everyone was used to.

As for why C was designed that way, it probably stems from the concept of C as "portable assembly". The switch statement is basically an abstraction of a branch table, and a branch table also has an implicit fall-through and requires an additional jump instruction to avoid it.

So basically, the designers of C also chose to keep the assembler semantics per default.

Title: Why do we have to use break in switch?


答: There is an inherent difference in Haskell and F# semantics. In Haskell, a function call does not perform any real calculation, but allocates a heap object known as a 'thunk'. It is perfectly okay for a thunk to have a link to itself or another thunk. However, in F#, a function call is an actual call, making expressions like let x = 1 : 2 : x in x invalid - as it requires x to be constructed before 1 : 2 : x is constructed. However, it is still more or less reasonable definition for infinite list, some way to define it should exist. Here lies roots for rec. If you want more, search and read for operational semantics for SML and Haskell - it is different.

Title: Why is the rec keyword needed in F#?

Body:
In F# it is necessary to use the rec keyword. In Haskell  there is no need to explicitly tell if a given function is recursive or not.

Given the role of recursion in functional programming, the F# design seems rather odd to me.  Is it a good language design decision or does it only exist for historical reason or because of an implementation constraint?


答:
The things I would like to have when picking up a project someone else has put down are:

Build instructions, including the last known working versions of all the tools in the toolchain. Compilers, IDEs, etc change over time, and it's a lot easier to work with if the previous devs leave me instructions on how to get up and running.

Run environment instructions - what needs to be in place to run this thing? A mention of what versions is again helpful. I recently picked up something that required a certain set of files to be in a certain place, and I had to go quizzing the other devs to figure it out. Not a big deal since the other dev was available, but if he hadn't been, then it would have been problematic.

Some assurance that the code committed to the repository actually does checkout and build. I once picked up a project where the previous devs (fortunately still around) had done some truly odd things with the Makefiles such that you could not build the project from a clean checkout. Needless to say, I first had to rectify THAT before I could actually do any work. Had the previous devs not been available, it might have taken a lot longer to get past that hurdle.

A general statement of the intent of the project. What's this piece of software for? As short as reasonable, but some kind of overview can be really helpful.


问:
Version control and project management for freelancing jobs
Are there version control and project management tools which "work well" with freelancing jobs, if I want to keep my customer involved in the project at all times?

What concerns me is that repository hosting providers have their fees based on the "number of users", which I feel is the number which will constantly increase as I finish one project after another. For each project, for example, I would have to add permissions to my contractor to allow him to pull the source code and collaborate.

So how does that work in practice? Do I "remove" the contractor from the project once it's done? This means I basically state that I offer no support and bugfixes anymore. Or do freelances end up paying more and more money for these services?

Do you use such online services, or you host them by yourself? Or do you simply send your code to your customer by e-mail in weekly iterations?

答:
I depends on what are you developing. For .NET Projects and for Java Projects as well I would suggest you "Team FOundation Service" (www.tfspreview.com). Here you have a full TFS, including a Build Service. No need to create a contract for multiple years, no need to pay more than you have used. It is allways very interesting for Freelancers I think.

Otherwise think about TFS Express or a Git or SVN instance.


答:
The problem with a source control system that you use and give access to your clients is that they will often not use that SCM tool. eg. If you decide to use git, they may turn round and say "sorry, we use svn" or vice versa. In any case, do they really want to maintain your code in another repository? Chances are they'll want your code migrated to their existing scm and DB.

So, a zip is probably the best - package up everything and send it to them.

I understand you might want to offer them all the benefits of a SCM, but generally, they will take your zip, unpack it and import (ie checkin) the code to their system. All the benefits will be present, and they'll have the expertise to manage it a lot better than in a foreign tool.

Nothing is stopping you from using any online SCM system to develop in of course.

One more thing - when you've finished, what makes you think they won't continue to work on the code? If they come back to ask for some more work, you can't expect to continue where you  left off - if you did give them a SCM link, and they copied it internally, you'd have to start from scratch again, or with a fresh and updated version from them. The idea of storing all your code in a common repo is just not practical enough.

Title: Version control and project management for freelancing jobs

Body:
Are there version control and project management tools which "work well" with freelancing jobs, if I want to keep my customer involved in the project at all times?

What concerns me is that repository hosting providers have their fees based on the "number of users", which I feel is the number which will constantly increase as I finish one project after another. For each project, for example, I would have to add permissions to my contractor to allow him to pull the source code and collaborate.

So how does that work in practice? Do I "remove" the contractor from the project once it's done? This means I basically state that I offer no support and bugfixes anymore. Or do freelances end up paying more and more money for these services?

Do you use such online services, or you host them by yourself? Or do you simply send your code to your customer by e-mail in weekly iterations?


答:
I agree with you that most services do not work on a mindset similar to this, since their pricing model is around teams and not the usage case you want them for. It is not viable in the long run to add/remove users per project or juggling to keep your charging under an arbitrary price tag (what would you do if  a customer hires you again, enrol them back?)

I believe it has to do with how much your client base would like to interact with version control. Would they want to integrate your work with something like subversion externals or git submodules, or they just want to have the latest version somewhere? In the latter case, I think a script that checks out, "zips" and emails the latest version would be sufficient.


问:
Why aren't there native Javascript interpreters for Windows/Mac/Linux?
It seems to me it would be very useful to use Javascript for general server side scripting tasks as it has more or less the same features as Perl and Python. But AFAIK there are no generally available Javascript interpreters for the major machine architectures. I guess the other problem may be lack of libraries but surely these would come if the interpreters were there. Google's V8 maybe could be a starting point. Does anyone think we'll see this soon?</p>

答:
There is a javascript interpreter written for Java apps (called Rhino) and it seems to be designed to write server code in javascript, but have it execute as java code.

Personally, I think you're much better off with node.js as that is awesome. For a quick introduction, you can do much much worse than read the (free) NodeBeginner book.


问:
admin-over-clients application
I have the same web application running on several different servers.
Now I want a central place to administer everything in one web interface. What is the best way to do this?

Should I provide a REST interface on every web application and let the admin application make all the calls?

This seems like a common problem that's already been solved by smarter people than me.

UPDATE: I want to change the application data per web application + see the results per web application

答:
Not knowing anything about these applications its hard to make a recommendation.

That being said, generally I would try centralize the Configuration information and have the web servers go out and get it, Rather than to publish Configuration information out to the servers. (So I would never have to worry that the servers are out of sync.)

Title: admin-over-clients application


问:
Can we use Java for commercial use?
The Java is GPL license (reference from wikipedia). I am not sure I can use it in in commercial projects. I already have a website written in Java and I plan to use this for commercial use. Is that illegal?</p>

答:
As I know , according to current license Java is under BCL(Sun's Binary Code License) , you can use JDK and JRE free for commercial use .
 Use ECLIPSE as your IDE as enty point to develop your Java code.
It is an opensource one so you don't need any lisence for the same.
When you are working on project , you will need many other tools to perform various stuffs.
Most of required functions are given as plugins(downloadable) in eclipse.</p>

OwnerDisplayName: Shisoft

Title: Can we use Java for commercial use?


答:
I'm usually on the other side of the table here, typically we require any outside developers to "ride our rails" and use our SCM / CI / issue tracking setup. But I get the sense I'm in a minority.

What I would do if I were in your shoes is:

a) I'd probably use bitbucket as my default host. Their terms for private repos are much better inasmuch as they charge by the user. They are more flexible (HG and Git). The reason to go dcvs here is that, when you are done with the project, you can make sure they have a full fidelity copy then cut them off of the repo so you aren't paying for empty users. I do the opposite over here with our freelancers and it works very well.

b) Pick an issue tracker that is highly flexible and not embedded but will work with your DCVS. Redmine is a great choice here, and it also does some time tracking.

c) Make sure you have some CI infrastructure to publish changes to frequently; most clients want to see the website not the commits. Jenkins is a great fit as it is quite free to stand up and works with just about anything.

That puts you in a position to cover all your bases and should not cost an arm and a leg to get or keep going.


问:
Compilable modern alternatives to C/C++
I am considering writing a new software product. Performance will be critical, so I am wary of using an interpreted or language or one that uses a emulation layer (read java).

Which leads me to thinking of using C (or C++) however these are both rather long in the tooth. I haven't used either for a long time. I figured in the last 20 years someone has probably created something which is reasonably popular, nice to code in and compiled.

What more modern alternatives are there to C for writing high performance compiled code?

If C++ is a different beast than it was 15 years ago, I would consider it, I guess I had an assumption that it had some inherent problems.

Parallelisation would be important, but probably not across multiple machines.

答:
There is a language in development called The Rust Programming Language which pursues similar goals as C++ does, notably zero-cost abstractions and fine control over memory management. That said, it is perhaps the most notable upcoming candidate despite being still very young.

Apart from Rust there really aren't any other popular alternatives which compile to native code. There's Delphi and D too, of course, but they aren't as fast, popular or used. Google's Go language could be a candidate, but it's still very young and aims for a bit different domain.

However, do note that C#(assuming Microsoft platform) and Java might not be all that slow even though they run on top of a virtual machine; the just-in-time compilation of code can do some optimizations which traditional ahead-of-time compilers aren't capable of applying due to lack of information of the program state and environment.

Frankly I would personally not consider C to be a candidate if C++ is an option, mainly because of the fact that modern C++ is safer, works at higher level of abstraction, is more expressive and has practically no performance loss over C(in some cases C++ is notably faster). Simply put, C++ provides everything that C provides and more. Most of the C functionality is considered to be "deprecated" and better, safer, faster and more intuitive alternatives are provided by the C++ standard library.

Title: Compilable modern alternatives to C/C++


问:
Why don't languages use explicit fall-through on switch statements?
I was reading Why do we have to use break in switch?, and it led me to wonder why implicit fall-through is allowed in some languages (such as PHP and JavaScript), while there is no support (AFAIK) for explicit fall-through.

It's not like a new keyword would need to be created, as continue would be perfectly appropriate, and would solve any issues of ambiguity for whether the author meant for a case to fall through.

The currently supported form is:

```<code>switch (s) {
    case 1:
        ...
        break;
    case 2:
        ... //ambiguous, was break forgotten?
    case 3:
        ...
        break;
    default:
        ...
        break;
}
</code>```

Whereas it would make sense for it to be written as:

```<code>switch (s) {
    case 1:
        ...
        break;
    case 2:
        ...
        continue; //unambiguous, the author was explicit
    case 3:
        ...
        break;
    default:
        ...
        break;
}
</code>```

For purposes of this question lets ignore the issue of whether or not fall-throughs are a good coding style.

Are there any languages that exist that allow fall-through and have made it explicit?

Are there any historical reasons that switch allows for implicit fall-through instead of explicit?

答:
It's primarily historical, most languages just copied what C did.

The reason that C did it that way is that the creators of C intended switch statements to be easy to optimize into a jump table. This is also the reason that C limits switch statements to integral values.

In a jump table, the program will calculate what position to jump to based on the expression. The program will jump to that point and then continue executing from that point. If you want skip the rest of the table you have to include a jump to the end of the table. C uses explicit break statements so that there is a direct correspondence to this construct.


问:
How useful are infix operators in a programming language?
How useful are infix operators in a programming language? Are they worth the extra complexity they provide? Can you provide any examples where infix operators are better suited to the problem that can't be handled by just overloading the normal operators?</p>

答: Computer languages are designed for humans not machines. And humans are more used to infix operators than pre or postfixes.</p>


问:
Is there really Object-relational impedance mismatch?
It is always stated that it is hard to store applications objects in relational databases - the object-relational impedance mismatch - and that is why Document databases are better.

However, is there really an impedance mismatch? And object has a key (albeit it may be hidden away by the runtime as a pointer to memory), a set of values, and foreign keys to other objects. Objects are as much made up of tables as it is a document. Neither really fit.

I can see a use for databases to model the data into specific shapes for scenarios in the application - e.g. to speed up database lookup and avoid joins, etc., but won't it be better to keep the data as normalized as possible at the core, and transform as required?

答:
I think No.

Impedance mismatch is not an "Objects vs. Relations" problem.

Detail arguments can be found here(PDF file, 11/.pgs).

A problem of impedance mismatch between applications written in OO languages and relational DB is not a problem of discrepancy between object-oriented and relational approaches themselves. Its real causes can be found in habitual implementation of the OO approach. Direct comparison of the two approaches cannot be used as a base for the conclusion that they are discrepant or mismatched. Experimental proof of absence of contradiction between object-oriented paradigm and relational data model is also presented.


答:
This question has been answered on SO, and it includes some strong historic background for why "rec" is used.

Here is the important quote for posterity:

Functions are not recursive by default in the French CAML family of languages (including OCaml). This choice makes it easy to supercede function (and variable) definitions using let in those languages because you can refer to the previous definition inside the body of a new definition. F# inherited this syntax from OCaml.

Title: Why is the rec keyword needed in F#?


问:
Why use an OO approach instead of a giant "switch" statement?
I am working in a .Net, C# shop and I have a coworker that keeps insisting that we should use giant Switch statements in our code with lots of "Cases" rather than more object oriented approaches.  His argument consistently goes back to the fact that a Switch statement compiles to a "cpu jump table" and is therefore the fastest option (even though in other things our team is told that we don't care about speed).

I honestly don't have an argument against this...because I don't know what the heck he's talking about.

Is he right?

Is he just talking out his ass?

Just trying to learn here.

答: Even if this wasn't bad for maintainability, I don't believe that it will be better for performance. A virtual function call is simply one extra indirection (the same as the best case for a switch statement) so even in C++ the performance should be roughly equal. In C#, where all function calls are virtual, the switch statement should be worse, since you have the same virtual function call overhead in both versions.</p>


问:
Multiple style sheets best practice
I currently am working on a project which has one large style sheet for about 20 pages. The style sheet contains some styles which are specific for certain pages. I'd like to break the style sheet up so there is one style sheet for each page with one master style sheet that handles everything generic. The reason I want to do this is so people can work on multiple pages without having to worry about who has that large style sheet checked out (I'm using TFS). Is this good practice?</p>

答:
I'm not too experienced with this but in my opinion it really depends on your project and if it makes sense to do so.

It seems to me that in your case, with multiple people working on it, it would make sense but only if they really need to have access to the style sheet. The point of having a central style sheet is to keep the style consistent throughout each page. In projects I have worked on, the styling is usually predetermined or tuned up after the pages have been built.

If one page has just one element that needs to be customized, then I would just say use inline css to do so, since its really a special case. However if it gets to the point where a lot of items on that page need to be customized, then I'd say make a stylesheet for that page.

If the pages really differ enough to warrant each one having it's own style sheet in addition to the master style sheet then do so. But you should set a clear guide as to what the master style sheet should handle and make sure the individual style sheets don't conflict unless its truly necessary.

Title: Multiple style sheets best practice


问:
Should I store log files in version control
The log files in question are metrics log files.  One of them is a project file produced by SourceMonitor, to which I regularly add checkpoints to chart the progress of projects.</p>

答:
Nowadays storage is cheap.  If these are metrics that you can use to show performance increases that coincide with versions, then I'd say keeping them in source control is just fine.  Just make sure that you're storing them for a reason.  If you can regenerate these logs/performance files from the source (meaning I can check out the code, run it, and produce the exact file you're about to store), then you probably don't need to.

Lots of things are stored in version control these days, including any and all documentation and other files that change along with the version of the project/code.

Note: You would store these in a branch outside your code branch.  Like Thomas' answer states, the source code branch that is used to build/deploy the app should be be separate so that your build server (or you, if you don't have time/space) can download/checkout the code independently of the documentation.


答:
I wouldn't store them in version control, at least in the same project as the source code for the deliverable product. To me, it just doesn't make much sense to combine what's effectively logging data in a directory structure for a deliverable product. The repository used for the project shouldn't contain anything outside of what is needed to build and deploy/deliver the system at hand (including instructions for building and deploying).

I would recommend storing them in the same place or using the same methodology as you do your other documents, such as test result history, design documents, requirements specifications, and so on. I don't know what technology you use, but uploading them to a SharePoint server would work, as would uploading them to a shared data server and putting the path to them (and perhaps summaries of them) on a wiki page.

Title: Should I store log files in version control

Body: The log files in question are metrics log files.  One of them is a project file produced by SourceMonitor, to which I regularly add checkpoints to chart the progress of projects.</p>


答: I should not add log file in version control, they are temporary and static so you don't have to maintain the version of it. You also collect the results of the log files into a chart, so I don't think it's necessary to add the log files into version control.</p>


答:
If C++ is a different beast than it was 15 years ago, I would consider it, I guess I had an assumption that it had some inherent problems.

15 years ago, there was no C++ standard. The second one has been published last year. C++ best practices changed a lot in the 5 years after the publication of the 98 standard, and they are changing again with the publication of the 11 one.

Title: Compilable modern alternatives to C/C++

Body:
I am considering writing a new software product. Performance will be critical, so I am wary of using an interpreted or language or one that uses a emulation layer (read java).

Which leads me to thinking of using C (or C++) however these are both rather long in the tooth. I haven't used either for a long time. I figured in the last 20 years someone has probably created something which is reasonably popular, nice to code in and compiled.

What more modern alternatives are there to C for writing high performance compiled code?

If C++ is a different beast than it was 15 years ago, I would consider it, I guess I had an assumption that it had some inherent problems.

Parallelisation would be important, but probably not across multiple machines.


问:
Reading data from file and const
Is it sane to let a read method on a file object to be const? For example

```<code>size_t read(void* buffer,size_t length) const;
</code>```

The read method does not change the contents of the file, but updates the file pointer which is invisible behind a handle.

答:
Although the read method does not change the visible state of its object, it does change the visible state of the external world (the file handle), and so should not be declared const.  Here's why.

Marking a method const has two meanings: One to the programmer, and a different one to the compiler.

To the programmer, const says this method is idempotent.  I can call it as many times as I want and make no changes in the visible state of this object, its collaborators, or the outside world.  It has no visible side effects.

To the compiler, const means this method makes no changes to the state of this object.

To that end, you mark a method as const if it meets the programmers's definition of having no visible side effects.  The compiler's definition of const is merely a tool that the compiler can use to check your claim that the method is idempotent.

The mutable keyword, which you use to tell the compiler that this piece of an object's state can be changed and have no visible side effects, is both a tool used to adapt the compiler's understanding of const to the programmer's definition, and evidence that the two definitions are not the same.

Title: Reading data from file and const


答:
If you are privy to the information add Business Requirements.

What did the customer want?

How did the changes facilitate that?

What were or are some of the challenges in meeting the customers
needs?

What needs were not met and why?


答: IMO, no, it's place in archived backups, if you wish to have that data later. General rule I use, store only things that you make youself or some others, if you say, include source code of other tool. Any files produced by codegen tools, logs, any other output data should be left out of repository, or stored separetly. The point is that, usually, you can checkout required version and recreate that data at any moment. The are exceptions, I suppose, but I have not encountered them so far.</p>


答:
C/C++ is rather long in the tooth.... this is a good thing. It implies that they were designed well enough (ahem) that they are still very usable, that many people use them for everyday tasks, and that you will find a large body of developers whop are experts in them. Maturity is something to be treasured.

If you spend all your time looking for something new, just because its new and think therefore that is must somehow be better, you're in for a lot of disappointment. This applies to software languages, GUI systems (take note, Microsoft and Gnome) and lovers (take note, young ladies :) )

Now admittedly, if your experience of C++ is 20 years old, when C++ code was generally coded like C, then maybe its time to re-evaluate the language, all the features that were there in the day that were never quite used are used a lot more today, and a few standardisation efforts have expanded the language a little to make it appear much different from those old C-style developments. Not that C is bad too - its a perfect language for many types of coding task too!

Title: Compilable modern alternatives to C/C++


答:
A ScreenCast

When I left my last job I actually did unedited screencasts which, from what I've heard, were very helpful in onboarding new people.  I took my team in a room, set up a condenser mic and explained to them everything I knew about the project while recording the audio and screen.  Then, I let them ask me questions about it.  We were able to get much more information recorded than we could if I sat down and tried to type as fast as I could all day.


答: Depends on what your product is going to do.  If performance is really critical, then the go-to language of choice is still FORTRAN.  I also wouldn't rule out Java -- it's used in many high-volume financial trading applications.  Erlang is worth a look if your problem domain requires high concurrency.  Objective-C is nice, although I don't know how well supported it is outside the Apple ecosystem (beyond compilers and basic runtime).  I've also heard good things about Haskell's performance, but I'm not sure whether that's absolute performance or just performance relative to other functional languages.</p>

Title: Compilable modern alternatives to C/C++


问:
I am a beginner. Can I directly start learning C++11? or I have to learn old C++?
I'm a beginner and have only little knowledge in programming.

Would it be good if I directly learn C++ from books which cover new C++11 or should I study through the old best C++ books?

Should I have little knowledge about C++ before learning C++11? or I can start directly from there?

Would it cause problem if I directly start from C++11? If no, then suggest some books on C++11.

答:
Take a deep breath and read this article by Peter Norvig.

Have you read that? Ok, if you are a beginner, you need to start in small steps. -insert language here- can come later, check out Coursera or Udacity for some beginner computer science introduction courses.

Having completed that, I would advise slowly working your way through K&R's The C programming language if you are set on a 'C' language.

Work on the basics, the rest will come in time.


答:
Why do you wanna start with C++?

I personally recommend against C++ as a first language. It is tricky, complex, difficult... simply much lower level and more "unsafe" than most other programming languages.

I advise to pick c#, java, python or javascript ...and a good book along the way. You'll have a much more enjoyable time with these.

Title: I am a beginner. Can I directly start learning C++11? or I have to learn old C++?

Body:
I'm a beginner and have only little knowledge in programming.

Would it be good if I directly learn C++ from books which cover new C++11 or should I study through the old best C++ books?

Should I have little knowledge about C++ before learning C++11? or I can start directly from there?

Would it cause problem if I directly start from C++11? If no, then suggest some books on C++11.


答:
You will absolutely lose 100+ hours fiddling with CSS if you split all your files up into a master, and a .css file for each page.

Use one stylesheet if possible. Assuming your master file will contain mostly resets, and CSS sanity checks, this will not be changing much. You need to use a nice set of comments to break up this one CSS file into distinguishable and labelled sections for your website.

I am not familiar with TFS, but if you are having check in/out problems, get people to branch the file and merge back? They will be working on their own seperate areas?

Title: Multiple style sheets best practice

Body: I currently am working on a project which has one large style sheet for about 20 pages. The style sheet contains some styles which are specific for certain pages. I'd like to break the style sheet up so there is one style sheet for each page with one master style sheet that handles everything generic. The reason I want to do this is so people can work on multiple pages without having to worry about who has that large style sheet checked out (I'm using TFS). Is this good practice?</p>


答:
Get your build server to gather your metrics and store them there against each build.

There should be some stuff that you only need the latest version of and some stuff that you need permanently to graph improvements. For example, if you build a whole code coverage report every build, you only ever need to look at the latest report to decide where to focus your test-writing efforts. But it is useful to keep code coverage %, branch coverage %, etc for every build and graph it out.

Jenkins is very good for managing this kind of thing. The HTML publisher plugin can be made to publish temporary, current reports (or you can keep them for n days, if you have the space and need), while the plot plugin can be made to track long-term progress.


问:
When should code favour optimization over readability and ease-of-use?
I am in the process of designing a small library, where one of my design goals is that the API should be as close to the domain language as possible. While working on the design, I've noticed that there are some cases in the code where a more intuitive, readable attribute/method call requires some functionally unnecessary encapsulation. Since the final product will not necessarily require high performance, I am unconcerned about making the decision to favour ease-of-use in my current project over the most efficient implementation of the code in question.

I know not to assume readability and ease-of-use are paramount in all expected use-cases, such as when performance is required. I would like to know if there are more general reasons that argue for a design preferring more efficient implementations—even if only marginally so?

答:
API == interface

This should be as simple and intuitive as it can be. It is also totally independent of the implementation.

Implementation == inner working

Make a clean implementation, with well structured code and good design decisions. Premature optimization is the root of evil. Take a profiler and check where you bottlenecks are.


答:
Current standard of C++ is C++11, which was published in 2011. So it's not 20 years old standard. And there have been numerous standards in between. Each of them introducing numerous performance improvements.

Compilers also have been constantly improving. They are far better at optimizing, than they used to be.

Executable formats have also improved, 20 years ago you had a.out, now you have ELF.

Overall, suggestion that C++ didn't change in 20 year cannot be further from the truth.

Also, keep in mind, that C and C++ are very different languages.

Title: Compilable modern alternatives to C/C++


答: You can also store them in a NoSQL database, then you could write an interface to get data reporting.  I think NoSQL should be suitable for this.</p>


答:
It's hard to say.

Old C++ is more of a minefield, and it's nice to learn how to navigate such a beast. It will also make you understand why things are done how they are, and what the implications of different constructs are.

Then again, old C++ is not what you want when you write code.

But then, yet again, old C++ is what a lot of industry will be churning on for 20 more years.

I love C++ 11, but it is only usable in startups for now. Not in large legacy code bases. And jumping straight to C++ 11 might leave you with undeveloped skills in nasty C++ parts. Which will backfire once some advanced C++ 11 construct leaks, or crashes because it's used in a syntactically correct, but logically incorrect way.


答:
thinks scalability. Will you use your css later ? In an other project ?
What will the result if i've a MVC application and my view requests me many files not delivred ?

In my opinion, define a css for a specific module + some main where basic html, body, h1, p, span , can be defined

Title: Multiple style sheets best practice


问:
ReSharper's effect on coding interviews
Anyone who has used R# or CodeRush knows how fast you can put together simple constructs (and refactor complex ones) with a simple keyboard shortcut.  However, do these productivity plugins cause a false evaluation of ability during interviews?

Part of being a productive code writer (and making a good first impression in an interview) is writing good code - fast.

If I had two candidates:

Doesn't use plugins.  She thinks about the problem, sits down at a stock IDE at the interview PC that looks exactly like hers and types out the code in a minute or two, as usual.  Done.  Pass.

Uses plugins.  He thinks about the problem, sits down at a stock IDE at the interview PC and realizes "fe + tab" no longer writes a foreach loop automatically, and all the shortcuts are gone.  He then bumbles around the keyboard hitting his normal hotkeys and popping up strange windows and getting flustered.  It takes him 3 minutes to write what normally would take 30 seconds.  Done.  Looked like they didn't know their way around the IDE at times.  Must be new to this IDE and thus not had much experience with it or maybe the language.  Pass, but a 'meh' mark beside their name.

In your experience, how do you handle plugins during interviews as the interviewer or interviewee?  What are the best practices to getting what the candidate really knows?  There can be candidates who don't understand code, and use R# as a crutch.  There can also be candidates who know the code in and out and use R# because it's just plain faster than the built in VS or Eclipse templates.  Is it best to just not use an IDE at all?  Let them bring their own PC?  Others?

答:
I'd argue that tools like ReSharper actually make you a better candidate over all.

For one, something like ReSharper is going to teach you about language constructs you might not have known about, as well as better ways to organize your code toward thinking about a problem or structuring it for readability.  ReSharper, in a sense, keeps you sharp with the best practices for slinging code, rather than letting you fall back to bad or obsolete habits, or worse the bad kind of laziness.

A good coder needs to understand basic constructs, but not manually type them in. The good kind of lazy lets the tools do the borning grunt work, and the extra time saved is instead spent thinking about the problem.  This makes one a better developer overall.

I'd complete the line of reasoning by stating that if the interview process is favoring sticks and stone knives, it's fundamentally broken.

Title: ReSharper's effect on coding interviews


问:
What is the value of workflow tools?
I'm new to Workflow developement, and I don't think I'm really getting the "big picture". Or perhaps to put it differently, these tools don't currently "click" in my head.

So it seems that companies like to create business drawings to describe processes, and at some point someone decided that they could use a state machine like program to actually control processes from a line and boxes like diagram. Ten years later, these tools are huge, extremely complicated (my company is currently playing around with WebSphere, and I've attended some of the training, its a monster, even the so called "minimalist" versions of these workflow tools like Activiti are huge and complicated although not nearly as complicated as the beast that is WebSphere afaict).

What is the great benefit in doing it this way? I can kind of understand the simple lines and boxes diagrams being useful, but these things, as far as I can tell, are visual programming languages at this point, complete with conditionals and loops. Programmers here appear to be doing a significant amount of work in the lines and boxes layer, which to me just looks like a really crappy, really basic visual programming language.

If you're going to go that far, why not just use some sort of scripting language? Have people thrown the baby out with the bathwater on this? Has the lines and boxes thing been taken to an absurd level, or am I just not understanding the value in all this?

I'd really like to see arguments in defense of this by people that have worked with this technology and understand why its useful. I don't see the value in it, but I recognize that I'm new to this as well and may not quite get it yet.

答:
It is not very clear which tool you are using. I guess you may be referring to the general set of tools called Business Process Modeling tools. There is a good reason for using such tools. Any quality business define its functions in terms of processes and analyst as well as business experts can draw such processes comfortably (until you tie them with standards...). You can create such processes at the conceptual level without any knowledge of web programming and if you have the right tool, you may be able to convert the process into a working application too (experienced people must come on board for this magic to go into production of course). So the idea is good.

The objective of the visual tools is not just documentation of the processes. The use of the tools is meant to help professional re-engineer processes and, in times, run simulations to discover points where the processes are less efficient than desired so that plans can be put in place to remove the bottlenecks.

There is a standard way that many companies use today called BPMN 2.0 (Business Process Modeling Notation). I do recommend that you get into understanding this notation if your tool is using it.

The Business Process Management Body of Knowledge is a famous resource, that you may want to consider as well.

The above covers the business side. The technical side requires SOA and BPEL, I am not sure I can provide advice on those here and now though.

Title: What is the value of workflow tools?


答:
There are a lot of usability enhancements that make C++11 more comprehensible to a beginner, especially one who has experience in other languages with those features.  Other changes in C++11 are only of interest to advanced users, so you're likely to get overwhelmed if you pick up a book that is designed to mostly teach the differences.  Make sure any book you get is designed for complete beginners to C++.

That being said, you'll probably have to learn the old way eventually, as there is a lot of existing code out there, and even new C++11 code will contain the old way of doing things if the programmer so chooses.  I write C++ for a living, and my company still hasn't even gotten around to evaluating C++11-compatible compilers, let alone using one in production.


问:
Where does Java get its SOA reputation from?
I see lots of SOA books surrounding Java and have always had the subliminal notion that Java is the "right" language for robust/enterprisey SOA, even though I know what SOA involves and  that it is perfectly possible using other languages & frameworks.

What exclusive traits Java has that other languages/platforms don't, that makes it so popular for SOAs?

答: Java IDEs and annotations make it easy to create web services.  So anyone who wants to learn about SOA and web services tends to run into a lot of Java-based tutorials (likely where your "subliminal notion" came from), and anyone who wants to get their feet wet with some simple service implementation gets quick gratification from experimenting with Java.  I don't think that Java is "better" than other languages at SOA, but it's arguably easier to get started using SOA with Java.</p>


答:
From a developer's point of view, you are right in saying that these "visual" environments are really hard to work with. SharePoint 2010 Workflows, which I use, throws out every best practice around creating good enterprise software - no automated testing, no code reuse, unreadable software... Anything more complex than an out-of-the-box template can be painful to maintain, as you are experiencing.

But from the business' point of view, workflows have massive benefits - at least, in theory. To quote from this white paper, the Efficiency, Accountability, Control and Ease of use of an automated workflow provide huge productivity gains. Imagine how much more inefficient a simple approval or on-boarding process would be without this automation. Also, the very act of defining a workflow is valuable to an organization that is trying to get control over their business processes.

The current state of workflow software is not the business' fault. They just want to make their lives easier, and workflows are great for that. I would mostly blame us, the IT department:

For not being more transparent with the business about how complex and fragile the system really is. We hide all the complexity.

For not being able to "scratch our itch" with intuitive, simple workflow solutions. This is probably more of a rant against large enterprise packages like SharePoint and SAP, but they are better than the custom solutions out there

Title: What is the value of workflow tools?

Body:
I'm new to Workflow developement, and I don't think I'm really getting the "big picture". Or perhaps to put it differently, these tools don't currently "click" in my head.

So it seems that companies like to create business drawings to describe processes, and at some point someone decided that they could use a state machine like program to actually control processes from a line and boxes like diagram. Ten years later, these tools are huge, extremely complicated (my company is currently playing around with WebSphere, and I've attended some of the training, its a monster, even the so called "minimalist" versions of these workflow tools like Activiti are huge and complicated although not nearly as complicated as the beast that is WebSphere afaict).

What is the great benefit in doing it this way? I can kind of understand the simple lines and boxes diagrams being useful, but these things, as far as I can tell, are visual programming languages at this point, complete with conditionals and loops. Programmers here appear to be doing a significant amount of work in the lines and boxes layer, which to me just looks like a really crappy, really basic visual programming language.

If you're going to go that far, why not just use some sort of scripting language? Have people thrown the baby out with the bathwater on this? Has the lines and boxes thing been taken to an absurd level, or am I just not understanding the value in all this?

I'd really like to see arguments in defense of this by people that have worked with this technology and understand why its useful. I don't see the value in it, but I recognize that I'm new to this as well and may not quite get it yet.


答:
You do not need to use old C++ to start using C++ 11, there are new features in C++ 11 but their use is optional. Knowing how to use C++ 11 features could be an advantage, it certainly wouldn't be a disadvantage when working with legacy (pre 11) code-bases once you knew the idiosyncrasies of the older versions.

Learn C++ would be a good place to start learning and Appendix B will teach you the C++ 11 features after you have learnt the basics.

I can see why some people have suggested Java, C#, etc. as easier alternative languages but I learnt a bit of C++ before moving onto C# and I'm not a worse programmer because of it, to the contrary programming skills go much deeper than language syntax/functionality and with a solid foundation in C++ you could learn any other imperative OOP language easily.


答: I've never used it, but a friend of my swears by Cython which lets you use C style primitives in performance critical parts of your code while keeping the general python syntax and being able to take full advantage of pythons higher level constructs to reduce development time everywhere else.</p>

Title: Compilable modern alternatives to C/C++


问:
Why is Clean Code suggesting avoiding protected variables?
Clean Code suggests avoiding protected variables in the "Vertical Distance" section of the "Formatting" chapter:

Concepts that are closely related should be kept vertically close to each other. Clearly this rule doesn't work for concepts that belong in separate files. But then closely related concepts should not be separated into different files unless you have a very good reason. Indeed, this is one of the reasons that protected variables should be avoided.

What is the reasoning?

答:
Protected variables should be avoided because:

They tend to lead to YAGNI issues. Unless you have a descendant class that actually does stuff with the protected member, make it private.

They tend to lead to LSP issues. Protected variables generally have some intrinsic invariance associated with them (or else they'd be public). Inheritors then need to maintain those properties, which people can screw up or willfully violate.

They tend to violate OCP. If the base class makes too many assumptions about the protected member, or the inheritor is too flexible with the behavior of the class, it can lead to the base class' behavior being modified by that extension.

They tend to lead to inheritance for extension rather than composition. This tends to lead to tighter coupling, more violations of SRP, more difficult testing, and a slew of other things that fall within the 'favor composition over inheritance' discussion.

But as you see, all of these are 'tend to'. Sometimes a protected member is the most elegant solution. And protected functions tend to have fewer of these issues. But there are a number of things that cause them to be treated with care. With anything that requires that sort of care, people will make mistakes and in the programming world that means bugs and design problems.


答:
I haven't read the book, but I can take a stab at what Uncle Bob meant.

If you put protected on something, that means that a class can inherit it.  But member variables are supposed to belong to the class in which they are contained; this is part of basic encapsulation.  Putting protected on a member variable breaks encapsulation because now a derived class has access to the implementation details of the base class.  It's the same problem that occurs when you make a variable public on an ordinary class.

To correct the problem, you can encapsulate the variable in a protected property, like so:

```<code>protected string Name
{
    get { return name; }
    private set { name = value; }
}
</code>```

This allows name to be safely set from a derived class using a constructor argument, without exposing implementation details of the base class.

Title: Why is Clean Code suggesting avoiding protected variables?

Body:
Clean Code suggests avoiding protected variables in the "Vertical Distance" section of the "Formatting" chapter:

Concepts that are closely related should be kept vertically close to each other. Clearly this rule doesn't work for concepts that belong in separate files. But then closely related concepts should not be separated into different files unless you have a very good reason. Indeed, this is one of the reasons that protected variables should be avoided.

What is the reasoning?

Body:
I haven't read the book, but I can take a stab at what Uncle Bob meant.

If you put protected on something, that means that a class can inherit it.  But member variables are supposed to belong to the class in which they are contained; this is part of basic encapsulation.  Putting protected on a member variable breaks encapsulation because now a derived class has access to the implementation details of the base class.  It's the same problem that occurs when you make a variable public on an ordinary class.

To correct the problem, you can encapsulate the variable in a protected property, like so:

protected string Name
{
    get { return name; }
    private set { name = value; }
}

This allows name to be safely set from a derived class using a constructor argument, without exposing implementation details of the base class.


答: It's really the same reason you avoid globals, just on a smaller scale.  It's because it's hard to find everywhere a variable is being read, or worse, written to, and hard to make the usage consistent.  If the usage is limited, like being written in one obvious place in the derived class and read in one obvious place in the base class, then protected variables can make the code more clear and concise.  If you're tempted to read and write a variable willy-nilly throughout multiple files, it's better to encapsulate it.


答:
When you say your project is performance sensitive, do you mean every line of code of it? Or, like normal, is there a smaller percentage that is performance criticial while the rest of it is your ordinary run of the mill business code?

After you answer that, what is the bigger risk for your project: that the end result is too slow, or that you never finish it in the first place?

Assuming you answer the second for both, you should develop in a higher level language that supports native interop (Python, Ruby, the .Net Family all have this). First, finish the project. Then profile, optimize, rinse, repeat. Only after that, consider reqriting choice segment of your application in native code and integrating that native code with your finished product.

Title: Compilable modern alternatives to C/C++


答:
To answer the title question: When you really need the performance gain. Real-time systems, embedded systems, or something like this. Or when the code is at the very low level and there are abstraction over abstraction layers built over it. Even then I'd prefer proven bottlenecks before optimization. You won't win much when the code is called once in an hour. When it is called hundred thousands of times a second, then there's a number.

Since the final product will not necessarily require high
  performance...

There. Seems like you should go for readability and ease-of-use first and put a comment there: "Optimize by doing Foo. Maybe. If necessary. Better not."

Title: When should code favour optimization over readability and ease-of-use?

Body:
I am in the process of designing a small library, where one of my design goals is that the API should be as close to the domain language as possible. While working on the design, I've noticed that there are some cases in the code where a more intuitive, readable attribute/method call requires some functionally unnecessary encapsulation. Since the final product will not necessarily require high performance, I am unconcerned about making the decision to favour ease-of-use in my current project over the most efficient implementation of the code in question.

I know not to assume readability and ease-of-use are paramount in all expected use-cases, such as when performance is required. I would like to know if there are more general reasons that argue for a design preferring more efficient implementations—even if only marginally so?


答:
Never optimize unless you have very good reasons. There is so much going under the hood (there is a ton of obscure optimizations in the compiler or even in the CPU itself) that it's very hard to know what kind of impact your optimization will have. You could make it faster or slower, you will never know unless you profile it.

Also, if your application is already fast enough, why should you bother making it faster? It's  time you will waste when you could spend it making your code more readable.


答:
Some very good answers already here. But one thing to add:

In most modern OO languages it is a good habit (in Java AFAIK its necessary) to put each class into its own file (please don't get nitty about C++ where you often have two files).

So it is virtually impossible to keep the functions in a derived class acessing a protected  variable of a base class "vertically close" in source code to the variable definition. But ideally they should be kept there, since protected variables are intended for internal use, which makes functions acessing them often "a closely related concept".


问:
How do you name your personal libraries?
I'm pretty bad with naming things.

The only name I can every generically come up with is 'helper'. Say, if I have a header file that contains helping functions for manipulating paths, I tend to put it inside my "helper" directory and call it "path-helper.hpp" or something like that.

Obviouslly, that's a bad naming convention. :)

I want to have a consistent naming scheme for my folder (and namespace) which I can use to always refer to my own headers and libraries, but I have trouble finding names that are easy to type or remember (like boost)... so I end up calling some of them "helper" or "stdext" or whatnot, which isn't a great idea.

How do you find names for your libraries that are easy to remember and easy to type, and which aren't too generic (like "helper" or "std" or "stdext" or the like)?

Any suggestions on how to go about doing this?

答:
Try to group helper functions thematically and include the theme in the library name. A library name like "helper" may by too generic, but a name like "PathHelper", "FileIOHelper" says pretty much about what functions one can expect in that lib (personally, I prefer "...Utilities", but that's just a matter of personal taste). For example, I have lib names like "MathUtilities", "StringUtilities" "ConfigUtilities", "DBUtilities" and so on.

Of course, for bigger libraries in our team we use names without any generic term at the end. And to be honest, we have also a library called "Common" for some functions and classes which don't group well under a specific topic name. But we try to keep that lib small.


问:
A sample Memento pattern: Is it correct?
Following this query on memento pattern, I have tried to put my understanding to test.

Memento pattern stands for three things:

Saving state of the "memento" object for its successful retrieval

Saving carefully each valid "state" of the memento

Encapsulating the saved states from the change inducer so that each state remains unaltered

Have I achieved these three with my design?

Problem

This is a zero player game where the program is initialized with a particular set up of chess pawns - the knight and queen. Then program then needs to keep adding set of pawns or knights and queens so that each pawn is "safe" for the next one move of every other pawn.

The condition is that either both pawns should be placed, or none of them should be placed. The chessboard with the most number of non conflicting knights and queens should be returned.

Implementation
I have 4 classes for this:

protected ChessBoard (the Memento)

```<code>private int [][] ChessBoard;

public void ChessBoard();
protected void SetChessBoard();
protected void GetChessBoard(int);
</code>```

public Pawn This is not related to memento. It holds info about the pawns

```<code>public enum PawnType: int
{
    Empty = 0,
    Queen = 1,
    Knight = 2,
}
//This returns a value that shown if the pawn can be placed safely
public bool IsSafeToAddPawn(PawnType);
</code>```

public CareTaker This corresponds to caretaker of memento

This is a double dimentional integer array that keeps
a track of all states. The reason for having 2D array is to
keep track of how many states are stored and
which state is currently active. An example:

0 -2

1 -1

2 0 - This is current state. With second index 0/

3 1 - This state has been saved, but has been undone

```<code>private int [][]State;
private ChessBoard [] MChessBoard;

//This gets the chessboard at the position requested and assigns it to originator
public ChessBoard GetChessBoard(int);

//This overwrites the chessboard at given position
public void SetChessBoard(ChessBoard, int);

private int [][]State;
</code>```

public PlayGame (This is the originator)

```<code>private bool status;
private ChessBoard oChessBoard;

//This sets the state of chessboard at position specified public
SetChessBoard(ChessBoard, int);

//This gets the state of chessboard at position specified public
ChessBoard GetChessBoard(int);

//This function tries to place both the pawns and returns the status of this attempt
public bool PlacePawns(Pawn);
</code>```

Edit after discussion with Kevin

The way I am trying to apply design patterns to my problems is not correct. In a way it helps me understand "how" to "implement" it. Yes. But then, this is not its ideal usage. I might as well simplify my "learning" problem and use my text book ones.

Also refer to this question on programmers.stackoverflow and all the discussions!

答: You don't need a Memento pattern for this problem, just simple backtracking.  I didn't quite understand your use of 'pawn', but basically you put something in the first legal spot.  You only need to remember the current position and the best so far.  When you can't put anything else on the board, then save the position if it is better than the previous best.  Then undo the last placement and try the next spot.</p>


问:
Why do we have to use break in switch?
Who decided (and based on what concepts) that switch construction (in many languages) has to use break in each statement?

Why do we have to write something like this:

```<code>switch(a)
{
    case 1:
        result = 'one';
        break;
    case 2:
        result = 'two';
        break;
    default:
        result = 'not determined';
        break;
}
</code>```

(noticed this in PHP and JS; there are probably many other languages using this)

If switch is an alternative of if, why we can't use the same construction as for if? I.e.:

```<code>switch(a)
{
    case 1:
    {
        result = 'one';
    }
    case 2:
    {
        result = 'two';
    }
    default:
    {
        result = 'not determined';
    }
}
</code>```

It is said that break prevents the execution of the block following the current one. But, does someone really run into the situation, where there was any need for execution of the current block and following ones? I didn't. For me, break is always there. In every block. In every code.

答: Break statement is a jumping statement that allows the user to exit the nearest enclosing switch (for your case), while, do, for or foreach. it's just as easy as that.</p>

Title: Why do we have to use break in switch?


答:
Generally, it's an organic process for me.

My namespaces tend to mirror my folder names, primarily because I think it's easier to find things that way.

Corporate projects generally have a company prefix in front of the namespace, and for personal projects I toggle between project-prefix.folder and just folder for the names.

The "main" folders tend to be obvious for their name, and are generally related to their function - "Foo".  For larger projects, I'll break out the main folder to reflect the major programming paradigm I may be following.  So for MVVM, I would have "Foo.View", "Foo.ViewModel", and "Foo.Model" as example names.

Invariably, helper functions that don't fit anywhere else start to creep into the project.  I'll start with a "common" or "utilities" type folder to first land them.  "Helpers", "Base", and "Core" would work just as well for an initial landing place.

I try to name my functions based upon the Subject and / or Action that they perform.  So I could have a PathManager, PathChecker, etc...  Oftentimes, I know I'll have several Actions related to a subject, so I'll name the class after the Subject and add methods as needed.  A thesaurus can come in handy here.

I have found a high correlation between ease of naming an object and how well I can describe what the function is supposed to do.  One of my personal checkpoints is that if I'm struggling to name something then that means I need to reflect upon what the function is actually supposed to be doing.  Once I fix the functionality issues, the name comes easily.

As I gather more helper functions, I'll migrate them to their own folder and / or namespace.  Whether they get a folder off of the root project or whether they get a sub-folder to the utility folder depends upon the nature and quantity of the functions.

Title: How do you name your personal libraries?

Body:
I'm pretty bad with naming things.

The only name I can every generically come up with is 'helper'. Say, if I have a header file that contains helping functions for manipulating paths, I tend to put it inside my "helper" directory and call it "path-helper.hpp" or something like that.

Obviouslly, that's a bad naming convention. :)

I want to have a consistent naming scheme for my folder (and namespace) which I can use to always refer to my own headers and libraries, but I have trouble finding names that are easy to type or remember (like boost)... so I end up calling some of them "helper" or "stdext" or whatnot, which isn't a great idea.

How do you find names for your libraries that are easy to remember and easy to type, and which aren't too generic (like "helper" or "std" or "stdext" or the like)?

Any suggestions on how to go about doing this?