问:
Asterisks in Multi-line comments
Using Visual Studio 2012 with C#, when I write multi-line comments, VS automatically begins each line with an asterisk, like this:

```<code>/*
 *
 *
 */
</code>```

I was just curious if this was the case in programming languages other than C#, or if there was a specific reason for this template.

答:
Some of the first comment syntax introduced into programming where statement comments. These kinds of comments required their own line.

Such as in basic

```<code>REM This is a comment.
</code>```

This created longer source code and used a keyword. Around the same time came end-of-line comments that requires only one character to start the comment.

Such as Fortran or Assembly

```<code>MOV C,1 ; This is a comment
</code>```

For languages that had simple grammar this was fine, but as more advanced grammar was developed two characters were used to start a comment.

Such as in C++

```<code>int c = 1; // This is a comment
</code>```

Or such as SQL

```<code>SELECT * FROM x -- This is a comment
</code>```

Many languages supported block comments in addition to end-of-line comments. These languages often supported the use of math operators *+/ to write expressions.

A block comment can not use the same grammar syntax used for code blocks. For example, if { } is used to block code then it can't be reused for comments. The same is true for () brackets since they are used to order math expressions. So often two characters were used to open/close the block comment.

We take syntax highlighting of today's IDEs for granted. When block comments were introduced to programming there was no syntax highlighting. Someone could easily introduce a bug if block comments were too close to math expressions.

For example; If you used (- this is a comment -) to mark blocks, then you could easily write a math expression as;

```<code>int x = 1+(-10);
int y = 2+(z-);
</code>```

The above would actually compile to int x = 1+;

These kinds of problems actually do exist in some older languages. As a result the use of /* this is a comment */ for multi-line comments became very popular. The reason is that visually /* is not a valid math operations.

For example;

```<code>int x = 1 /* 8;
int y = 3 */;
</code>```

To a human reader there is no mistake. It's not valid math. You can still read the comment inside the expression. StackExchange is adding syntax highlight (lol) but picture it without and colors.

This became a standard comment block because it solved many grammar problems in parsing the language while remaining easily identifiable to humans as a comment.

When VS adds an extra * to each line. It's to ensure readability of the comment when there is no syntax highlighting. If you open the source code in a regular text editor, then those lines are clearly shown as a comment.

If the start of a comment /* scrolls above the screen. There is no way to know if what you're reading is a comment or not. Example; someone blocked out a chunk of code.

I was just curious if this was the case in programming languages other than C#, or if there was a specific reason for this template.

The specific reason is human readability, and has nothing to do with the programming language itself. For long comments that may scroll off screen it allows the reader to understand the text is a comment.

Any character would suffice as this example;

```<code>/*
 # Still a comment.
 # Still readable if very long.
 #
 #
 */
</code>```

Visual Studio will automatically add * characters to multi-line comments. This is a configurable options in the IDE.

It should be noted that other popular IDEs also offer this feature. I've seen it in Eclipse, WebStorm, IntelliJ and NetBeans. Those editors will add new lines to comment blocks while you type for languaging such as C++, Java and PHP.

I've never seen this done for XML or HTML block comments in any editor. It appears to be a common feature for C style languages.

Title: Asterisks in Multi-line comments

Body:
Some of the first comment syntax introduced into programming where statement comments. These kinds of comments required their own line.

Such as in basic

REM This is a comment.

This created longer source code and used a keyword. Around the same time came end-of-line comments that requires only one character to start the comment.

Such as Fortran or Assembly

MOV C,1 ; This is a comment

For languages that had simple grammar this was fine, but as more advanced grammar was developed two characters were used to start a comment.

Such as in C++

int c = 1; // This is a comment

Or such as SQL

SELECT * FROM x -- This is a comment

Many languages supported block comments in addition to end-of-line comments. These languages often supported the use of math operators *+/ to write expressions.

A block comment can not use the same grammar syntax used for code blocks. For example, if { } is used to block code then it can't be reused for comments. The same is true for () brackets since they are used to order math expressions. So often two characters were used to open/close the block comment.

We take syntax highlighting of today's IDEs for granted. When block comments were introduced to programming there was no syntax highlighting. Someone could easily introduce a bug if block comments were too close to math expressions.

For example; If you used (- this is a comment -) to mark blocks, then you could easily write a math expression as;

int x = 1+(-10);
int y = 2+(z-);

The above would actually compile to int x = 1+;

These kinds of problems actually do exist in some older languages. As a result the use of /* this is a comment */ for multi-line comments became very popular. The reason is that visually /* is not a valid math operations.

For example;

int x = 1 /* 8;
int y = 3 */;

To a human reader there is no mistake. It's not valid math. You can still read the comment inside the expression. StackExchange is adding syntax highlight (lol) but picture it without and colors.

This became a standard comment block because it solved many grammar problems in parsing the language while remaining easily identifiable to humans as a comment.

When VS adds an extra * to each line. It's to ensure readability of the comment when there is no syntax highlighting. If you open the source code in a regular text editor, then those lines are clearly shown as a comment.

If the start of a comment /* scrolls above the screen. There is no way to know if what you're reading is a comment or not. Example; someone blocked out a chunk of code.

I was just curious if this was the case in programming languages other than C#, or if there was a specific reason for this template.

The specific reason is human readability, and has nothing to do with the programming language itself. For long comments that may scroll off screen it allows the reader to understand the text is a comment.

Any character would suffice as this example;

/*
 # Still a comment.
 # Still readable if very long.
 #
 #
 */

Visual Studio will automatically add * characters to multi-line comments. This is a configurable options in the IDE.

It should be noted that other popular IDEs also offer this feature. I've seen it in Eclipse, WebStorm, IntelliJ and NetBeans. Those editors will add new lines to comment blocks while you type for languaging such as C++, Java and PHP.

I've never seen this done for XML or HTML block comments in any editor. It appears to be a common feature for C style languages.


问:
Google review microformats, microdata, RDFa, oh my!
I'm developing a website which includes a section for reviews. I want to include Google's microformat for review information so that details of the review show up in Google's snippet thingy, like this:

However, according this page, Google supports three different formats for the review data, "microformat", "microdata" and RDFa. They all seem to do exactly the same thing, though, and I have no idea which one to choose...

RDFa looks nice - in that the data is fairly separate from the actual content (which makes my life a bit easier). Except it's based on XML namespaces, which isn't going to play well with HTML5 (the site isn't HTML5 yet, but I imagine it will be ported eventually).

The "hReview microformat" seems to use special CSS classes to denote the various sections of the review, which seems like a bad mix of concerns to me...

So I'm kind of leaning towards the "microdata" format, which looks like it's closer to the HTML5 way of doing things (i.e. no special namespaces). An example of that would be (from the page I linked above):

```<code><div>
  <div itemscope itemtype="http://data-vocabulary.org/Review">
    <span itemprop="itemreviewed">L’Amourita Pizza</span>
    Reviewed by <span itemprop="reviewer">Ulysses Grant</span> on
    <time itemprop="dtreviewed" datetime="2009-01-06">Jan 6</time>.
    <span itemprop="summary">Delicious, tasty pizza in Eastlake!</span>
    <span itemprop="description">L'Amourita serves up traditional
      wood-fired Neapolitan-style pizza, brought to your table promptly
      and without fuss. An ideal neighborhood pizza joint.</span>
    Rating: <span itemprop="rating">4.5</span>
  </div>
</div>
</code>```

But as I said, all the formats are basically the same, just slightly different... which one should I choose?

答:
It's not finalized yet, but there is work underway to standardize the embedding of RDFa in HTML5.  See:  http://dev.w3.org/html5/rdfa/

Given that RDFa has been around for a while, and is proven and stable, and easily interoperates with other RDF based semantic data sources, I think you should seriously consider RDFa.

Also, consider the traction that RDFa already has. See: http://www.readwriteweb.com/archives/w3c_pleased_with_semantic_web_adoption.php

ContentLicense: CC BY-SA 2.5


问:
why no native compiler of C# or other “productive” language?
I've been reading about D and Go and how they aim at being compiled to machine code yet be convenient (like garbage collection, no need to manipulate pointers unless needed) and I agree that there is a need for such a language. However designers of both Go and D for some reason decided to invent a new language. Why? Why not take existing language which is popular, proven to be productive but is not compiled to native code like C#? What are technological reasons for that? Would it be hard to implement garbage collection (D does), linq or something entirely else?</p>

答:
Templates in C++ make it possible for a relatively small source file to generate an arbitrary number of different functions, each containing a different sequence of instructions, but in order for a program to actually run, the number of such functions must be bounded.

Generics in .NET languages like C# also allow a small source file to specify a huge number of functions, but there is no need to actually generate the instructions for any of them until such time as they're actually executed. Whereas C++ will choke if a template would generate an infinite number of functions, C# will have no problem, given the ability to defer machine code generation until runtime.

While it would be possible to have a compiler generate native code that included within itself a mechanism for generating additional code on demand, a code generator that produces optimized code is going to be a rather complicated beast.  It's easier to have the compiler render code into a form where generics do not have to be expanded out into machine instructions, and then have a JITter ("Just In Time compiler") which can take code of that form, along with a list of required type substitutions, and produce a machine-code representation of a method that works with the necessary types.

ContentLicense: CC BY-SA 3.0


问:
Optimistic & Pessimistic Programming - Ensuring multiple tasks are called only once for specific record
Let's say you have 10 database records which you need to process in the following way:

Start

Pull 2 records from the database with the 'Processed' flag set to 'false'

Call the external web service with the custom data from this 2 records.

Update those 2 records in the database and set them as 'Processed' = 'true'

Goto 1

Now, what can happen in this scenario?

-

An error can occur while pulling the records from the database

that's fine, as in the next round we will try to get them again.

An error can occur while calling an external web service

that's also fine, as in the next round we will try to send those 2 records again

An error can occur while calling the database for the processed record update

what to do now? Are you optimistic that this will never happen?

keep in mind that you already sent those 2 records via web service and you must not send them again at any cost

one option is to call a database update in a loop until it runs successfully !?

-

The question is, how (would) you handle this situation?

**UPDATE**

Code illustration:

```<code>loop
{
    db = database
    ws = webservice

    trans = db.open_transaction

    recs = trans.query_for_two_records_and_update_processed_to_true

    ws_response = ws.send_text_messages(recs)

    if (ws_response == success)
    {
        trans.commit() // what would you do if this fails?
    }
    else
    {
        trans.rollback()
    }
}
</code>```

答:
I believe your requirements are theoretically impossible to implement.

Is there no way to check whether the web service has received the records? Some other service operation? If so you could check before you submit.

Also check with the service owner to see if they can make their service idempotent.

Or set up a manual process to handle the failures.


答:
Since you are so confident you can reprocess step #3 (sending to web service), why can't you just mark processed = true right after step #2?

start

fetch 2 unprocessed records

update processed = true

send to web service.

I only recommend this because of how critical it is to never send to the web service more than once AND you are so confident you can continue to reprocess any failures to send to the web service.

Title: Optimistic & Pessimistic Programming - Ensuring multiple tasks are called only once for specific record

Body:
Let's say you have 10 database records which you need to process in the following way:

Start

Pull 2 records from the database with the 'Processed' flag set to 'false'

Call the external web service with the custom data from this 2 records.

Update those 2 records in the database and set them as 'Processed' = 'true'

Goto 1

Now, what can happen in this scenario?

-

An error can occur while pulling the records from the database

that's fine, as in the next round we will try to get them again.

An error can occur while calling an external web service

that's also fine, as in the next round we will try to send those 2 records again

An error can occur while calling the database for the processed record update

what to do now? Are you optimistic that this will never happen?

keep in mind that you already sent those 2 records via web service and you must not send them again at any cost

one option is to call a database update in a loop until it runs successfully !?

-

The question is, how (would) you handle this situation?

**UPDATE**

Code illustration:

```<code>loop
{
    db = database
    ws = webservice

    trans = db.open_transaction

    recs = trans.query_for_two_records_and_update_processed_to_true

    ws_response = ws.send_text_messages(recs)

    if (ws_response == success)
    {
        trans.commit() // what would you do if this fails?
    }
    else
    {
        trans.rollback()
    }
}
</code>```


答:
It's always possible to come up with an even worse case that ruins whatever solution you come up with. Assume a hostile web service, or a hostile database, and you're screwed.

But in the scenario you describe, you mainly need a more reliable action log than an external database. Let's assume that the local file system is reliable if you don't increase file sizes (which could easily fail if the disk is full).

Then the program should, at startup, create a small file which contains just two fixed-size records, each consisting of space for an ID and a status flag. In addition, we change the database to something slightly more elaborate: the processed flag can now be "new", "in progress" and "processed".

Then you want something like this pseudocode:

```<code>txlog = disk struct { id, status }

record = db -> load record
txlog -> id = record.id, status = sending
db -> processed = in progress, on failure txlog -> clear and start over
web -> send request, on error response goto service error, on timeout abort
txlog -> status = sent
db -> processed = done, on failure abort
txlog -> clear
</code>```

The service error handler looks like this:

```<code>txlog -> status = failed
db -> processed = new, on failure abort
txlog -> clear
</code>```

Now, the interesting part comes next. If you get a db error and abort, or your program suddenly disappears (power loss), or if you never get a response from the web service (webservice crashed, or connectivity loss), your program will eventually start again and realize that the txlog file is not cleared. Then it needs to go into error recovery mode.

If the txlog has status "sending", check the db record. If that has status "new", your program died before it could send the request. Clear the log and proceed normally.

If the db record has status "in progress", you're in trouble: it means something went wrong at a point where you might have sent the request to the web service and it might have been processed. Maybe you lost power or network, or the web service did, but you can't know whether the request went through. In this case, you can only alert a human operator to take a look. I'll talk about that later.

If the txlog has status "sent", the record was sent. If the db still has status "in progress", then try to set the status again. If not, your program died just before it could clear the txlog, or the db did its update but disappeared without sending a success message. Either way, clear the log and move on.

But what about the error case? This is the "worse case" that I mentioned in the beginning, the real issue of the unreliable system that you're dealing with. Power loss at just the wrong time. A network cable that suddenly gets cut. Your system needs to adapt, and if, as in the case you're describing, it can't (the web service you describe just doesn't give that option), you're screwed if the worst case happens. The process I described will at least alert you to it. The human operator can then perhaps contact the web service administrators to ask them about their logs, or otherwise make an informed decision what to do about the operation that may or may not have been performed.

On a side note, could we design, say, a text message service that is idempotent? Sure. The service would require, as a first step in every process, allocating a GUID for the message to be sent. Once you have that GUID, you can store it in the transaction log. Then you send your message with the GUID. The service can then check its own records and discover that the message with this GUID has already been sent, and therefore not send it again. And even if the web service failed to properly record the fact that it sent the message, the final receiver can do the same - the phone, for example, could see that it already received a message with that GUID and ignore the new one.

Body:
It's always possible to come up with an even worse case that ruins whatever solution you come up with. Assume a hostile web service, or a hostile database, and you're screwed.

But in the scenario you describe, you mainly need a more reliable action log than an external database. Let's assume that the local file system is reliable if you don't increase file sizes (which could easily fail if the disk is full).

Then the program should, at startup, create a small file which contains just two fixed-size records, each consisting of space for an ID and a status flag. In addition, we change the database to something slightly more elaborate: the processed flag can now be "new", "in progress" and "processed".

Then you want something like this pseudocode:

txlog = disk struct { id, status }

record = db -> load record
txlog -> id = record.id, status = sending
db -> processed = in progress, on failure txlog -> clear and start over
web -> send request, on error response goto service error, on timeout abort
txlog -> status = sent
db -> processed = done, on failure abort
txlog -> clear

The service error handler looks like this:

txlog -> status = failed
db -> processed = new, on failure abort
txlog -> clear

Now, the interesting part comes next. If you get a db error and abort, or your program suddenly disappears (power loss), or if you never get a response from the web service (webservice crashed, or connectivity loss), your program will eventually start again and realize that the txlog file is not cleared. Then it needs to go into error recovery mode.

If the txlog has status "sending", check the db record. If that has status "new", your program died before it could send the request. Clear the log and proceed normally.

If the db record has status "in progress", you're in trouble: it means something went wrong at a point where you might have sent the request to the web service and it might have been processed. Maybe you lost power or network, or the web service did, but you can't know whether the request went through. In this case, you can only alert a human operator to take a look. I'll talk about that later.

If the txlog has status "sent", the record was sent. If the db still has status "in progress", then try to set the status again. If not, your program died just before it could clear the txlog, or the db did its update but disappeared without sending a success message. Either way, clear the log and move on.

But what about the error case? This is the "worse case" that I mentioned in the beginning, the real issue of the unreliable system that you're dealing with. Power loss at just the wrong time. A network cable that suddenly gets cut. Your system needs to adapt, and if, as in the case you're describing, it can't (the web service you describe just doesn't give that option), you're screwed if the worst case happens. The process I described will at least alert you to it. The human operator can then perhaps contact the web service administrators to ask them about their logs, or otherwise make an informed decision what to do about the operation that may or may not have been performed.

On a side note, could we design, say, a text message service that is idempotent? Sure. The service would require, as a first step in every process, allocating a GUID for the message to be sent. Once you have that GUID, you can store it in the transaction log. Then you send your message with the GUID. The service can then check its own records and discover that the message with this GUID has already been sent, and therefore not send it again. And even if the web service failed to properly record the fact that it sent the message, the final receiver can do the same - the phone, for example, could see that it already received a message with that GUID and ignore the new one.


问:
Web Developer or Software Engineer?
A question that I have been asking myself and really confused which path to take.

So I need your guys help as to the pros and cons of these 2 professions in today's world. I love web applications development as the Web is the best thing to happen in this age and nearly everyone gets by on the World Wide Web. And also tend to keep learning about new technologies and about web services.

On the other hand I like software engineering also for the desktop applications as I have had experience with development small scale software in VB.Net, Java, C++, etc.

Which path has more scope and better future? What's your view?

答:
Stop separating the two - Web development is a subset of software engineering, like a specialization. And there's nothing wrong with having specializations. </p>

<p>Do you use good software engineering practices like using version control, writing specs, code refactoring, writing unit tests wherever necessary, having a formal test phase with proper testers, etc? If yes then congratulations, you are already a software engineer. If no, then these are the things you can apply even in web development and become much more productive/professional as a developer. </p>

Title: Web Developer or Software Engineer?

Body:
Stop separating the two - Web development is a subset of software engineering, like a specialization. And there's nothing wrong with having specializations.

Do you use good software engineering practices like using version control, writing specs, code refactoring, writing unit tests wherever necessary, having a formal test phase with proper testers, etc? If yes then congratulations, you are already a software engineer. If no, then these are the things you can apply even in web development and become much more productive/professional as a developer.


问:
From a TDD perspective, am I a bad person if I test against a live endpoint instead of a mock?
I follow TDD religiously.  My projects typically have 85% or better test coverage, with meaningful test cases.

I do a lot of work with HBase, and the main client interface, HTable, is a real pain to mock.  It takes me 3 or 4 times longer to write my unit tests than it does to write tests that use a live endpoint.

I know that, philosophically, tests that use mocks should take priority over tests that use a live endpoint.  But mocking HTable is a serious pain, and I'm not really sure it offers much of an advantage over testing against a live HBase instance.

Everyone on my team runs a single-node HBase instance on their workstation, and we have single-node HBase instances running on our Jenkins boxes, so it's not an issue of availability.  The live endpoint tests obviously take longer to run than the tests that use mocks, but we don't really care about that.

Right now, I write live endpoint tests AND mock-based tests for all my classes.  I'd love to ditch the mocks, but I don't want quality to decline as a result.

What do you all think?

答:
My first recommendation would be to not mock types you don't own. You mentioned HTable being a real pain to mock - maybe you should wrap it instead in an Adapter that exposes the 20% of HTable's features you need, and mock the wrapper where needed.

That being said, let's assume we're talking about types you all own. If your mock-based tests are focused on happy path scenarios where everything goes smoothly, you won't lose anything ditching them because your integration tests are probably already testing the exact same paths.

However, isolated tests become interesting when you start thinking about how your system under test should react to every little thing that could happen as defined in its collaborator's contract, regardless of the actual concrete object it's talking to. That's part of what some call basic correctness. There could be many of those little cases and many more combinations of them. This is where integration tests start getting lousy while isolated tests will remain fast and manageable.

To be more concrete, what happens if one of your HTable adapter's methods returns an empty list ? What if it returns null ? What if it throws a connection exception ? It should be defined in the Adapter's contract if any of those things could happen, and any of its consumers should be prepared to deal with these situations, hence the need for tests for them.

To sum up : you won't see any quality decline by removing your mock-based tests if they tested the exact same things as your integration tests. However, trying to imagine additional isolated tests (and contract tests) can help you think out your interfaces/contracts extensively and increase quality by tackling defects that would have been hard to think about and/or slow to test with integration tests.


答:
You assume that the thought process behind Go and D was "we want a language compiled to native code that isn't C or C++". Then you wonder why the designers didn't just write native code compilers for Java or C#.

But who says that this was the thought process behind those languages? I can't speak for the designers, of course, but from what I've read, the primary idea behind D was "C++ has a syntax that makes compilers complicated and slow, and metaprogramming using templates is an unreadable nightmare; I can make a language that can do metaprogramming better than C++". Keep in mind that the primary designer of D is a C++ compiler writer.

Also, it's not that easy to just compile Java and C# to native code. Java's bytecode is part of the documented interface of the Java runtime environment. It's totally legal for a Java program to generate bytecode at runtime, and then use a class loader to load that. The same applies to C#. In fact, regular expression libraries and other things often do exactly that. You have mocking libraries, aspect libraries, all these things love to mess with bytecode. If you try to create a native-only environment for Java or C#, these things stop working. So at best you could compile a subset of Java to native code. But then you face the fact that all this stuff that's being done at runtime is actually an important part of the way these languages are used; it replaces things that are done with offline code generation or compile time tricks in other languages.

Title: why no native compiler of C# or other “productive” language?

Body: I've been reading about D and Go and how they aim at being compiled to machine code yet be convenient (like garbage collection, no need to manipulate pointers unless needed) and I agree that there is a need for such a language. However designers of both Go and D for some reason decided to invent a new language. Why? Why not take existing language which is popular, proven to be productive but is not compiled to native code like C#? What are technological reasons for that? Would it be hard to implement garbage collection (D does), linq or something entirely else?</p>


问:
Can the Jacquard loom be considered stateless?
Can the Jacquard loom, pictured below complete with its chains of paper cards

be considered stateless? As far as I can tell I can tell, each operation is not dependant on the previous. Or did it have any concept of branching and/or looping?

答:
Well although the loom's engine contains internal state -- the current card -- this state is not accessible to the "program". Therefore from the point of view of the operator, the loom is stateless. Running a program through the loom does not depend on previous programs or subsequent programs.

The cards you feed to the loom can not change, making them immutable. They describe the line to be woven, rather than issuing a command. Therefore they are declarative.

The cards do have side-effects, so they are unsafe.

I would say that the loom is therefore functional, although not purely functional. It receives a parameter in the form of a chain of cards, and performs a classic comprehension on those cards, although this evaluation does have side effects.

The Real question, though, is does the Jacquard loom have a Buddha nature?

;)


答:
If you cannot use transactions as @RobertHarvey said, use three states: 'unprocessed', 'processing' and 'processed'. Log all failures in a persistent log of some sort (file), and if 3 or 4 fails, try to set it back to 'unprocessed'.

And then manually solve ones stuck in 'processing' using the info in log.


问:
How many programming languages is a programmer expected to be an expert at?
Do most programmers specialize on a single stack, leaving other things be, or are they expert at multiple languages at the same time? If it's more than one, how many is standard?

By expert, I mean more than simply knowing the syntax of a language - an expert knows enough of standard libraries, tools, environments and syntax to be able to write non-trivial programs without having to constantly look things up or read books/tutorials.

答:
None as there are likely some programmers that won't be experts in any language but they enjoy the diverse environment they have and will use various languages depending on circumstances as some may know a few server-side technologies like PHP, ASP.Net in C#.Net or VB.Net, or Java, a couple of client side scripting languages like JavaScript or Flash, and this is without getting into any hardware used to put up the web stuff here.

At the same time, there may be some programmers that are experts in a dozen languages or more as that is what they study rather faithfully most of the time to keep on top of so much within each language.


答:
I've seen this pattern many times in various C-syntax languages such as C, C++, Java, C#, and even JavaScript. The extra asterisks at the beginning of each line have no syntactic significance. They are there purely to aid in readability by catching your eye and making obvious that you are looking at a multi-line comment.

The use of this template (comment pattern) predates by many, many years the appearance of IDEs and text editors that could style comments by displaying them in a unique color. So to get a feel for the utility of this approach, look at file that uses a variety of comment types on the console or in an editor that displays all text in the same style. Try to quickly spot the comments.

Title: Asterisks in Multi-line comments

Body:
Using Visual Studio 2012 with C#, when I write multi-line comments, VS automatically begins each line with an asterisk, like this:

```<code>/*
 *
 *
 */
</code>```

I was just curious if this was the case in programming languages other than C#, or if there was a specific reason for this template.


问:
Is it a code smell if you are frequently creating an object just to call a method on it
I inherited a code base where there is a lot of code that goes something like this:

```<code>SomeDataAdapter sda = new SomeDataAdapter();
sda.UpdateData(DataTable updateData);
</code>```

And then sda is never used again.

Is that a code smell that indicates that those methods should actually be static class methods instead?

答:
Kind of. It usually means you want to pass a function around and your language of choice won't let you. It's kind of clumsy and inelegant, but if you're stuck in a language without first-class functions, there's not a whole lot you can do.

If none of those objects are getting passed as arguments to other functions, you could turn them into static methods and nothing would change.


答:
I would consider it an architecture smell in that UpdateData probably should belong to a 'service' class.

Where the data is an Apple.
Where AppleAdapter is service/business-intelligence class.
Where AppleService is a Singleton reference to an AppleAdapter that exists outside of the current method.

```<code>private static volatile AppleAdapter _appleService = null;
private static object _appleServiceLock = new object();
private AppleAdapter AppleService
{
    get
    {
        if (_appleService == null)
        {
            lock (_appleServiceLock)
            {
                if (_appleService == null)
                    _appleService = new AppleAdapter();
            }
        }
        return _appleService;
    }
}

public SomeAppleRelatedMethod(Apple apple)
{
    AppleService.UpdateData(apple);
}
</code>```

I don't think what you are doing is wrong necessarily but if SomeDataAdapter does indeed represent some kind of stateless business service, then a singleton would be the best practice for it.
Hope that helps! The example provided is fancy way to ensure no contention of the _appleService if it happened to be both null and accessed at exactly the same time by two or more threads.

You know what? If SomeDataAdapter is an ADO IDbDataAdapter (which it almost certainly is), disregard this entire response!

:P

I don't have permission to add a comment to the original question, but if you could specify where this code exists.

If this code represents a custom implementation of an IDbDataAdapter, and UpdateData is creating an IDbConnection, IDbCommand, and wiring it all up behind the scenes, then no I wouldn't consider that a code smell because now we're talking about streams and other things that need to be disposed of when we're done using them.

Title: Is it a code smell if you are frequently creating an object just to call a method on it

Body:
I inherited a code base where there is a lot of code that goes something like this:

```<code>SomeDataAdapter sda = new SomeDataAdapter();
sda.UpdateData(DataTable updateData);
</code>```

And then sda is never used again.

Is that a code smell that indicates that those methods should actually be static class methods instead?

Body:
I would consider it an architecture smell in that UpdateData probably should belong to a 'service' class.

Where the data is an Apple.
Where AppleAdapter is service/business-intelligence class.
Where AppleService is a Singleton reference to an AppleAdapter that exists outside of the current method.

private static volatile AppleAdapter _appleService = null;
private static object _appleServiceLock = new object();
private AppleAdapter AppleService
{
    get
    {
        if (_appleService == null)
        {
            lock (_appleServiceLock)
            {
                if (_appleService == null)
                    _appleService = new AppleAdapter();
            }
        }
        return _appleService;
    }
}

public SomeAppleRelatedMethod(Apple apple)
{
    AppleService.UpdateData(apple);
}

I don't think what you are doing is wrong necessarily but if SomeDataAdapter does indeed represent some kind of stateless business service, then a singleton would be the best practice for it.
Hope that helps! The example provided is fancy way to ensure no contention of the _appleService if it happened to be both null and accessed at exactly the same time by two or more threads.

You know what? If SomeDataAdapter is an ADO IDbDataAdapter (which it almost certainly is), disregard this entire response!

:P

I don't have permission to add a comment to the original question, but if you could specify where this code exists.

If this code represents a custom implementation of an IDbDataAdapter, and UpdateData is creating an IDbConnection, IDbCommand, and wiring it all up behind the scenes, then no I wouldn't consider that a code smell because now we're talking about streams and other things that need to be disposed of when we're done using them.


问:
Print bottom view of a binary tree
For a binary tree we define horizontal distance as follows:

```<code>    Horizontal distance(hd) of root = 0
    If you go left then hd = hd(of its parent)-1, and
    if you go right then hd = hd(of its parent)+1.
</code>```

The bottom view of a tree then consists of all the nodes of the tree, where there is no node with the same hd and a greater level. (There may be multiple such nodes for a given value of hd. In this case all of them belong to the bottom view.) I'm looking for an algorithm that outputs the bottom view of a tree.

Examples:

Suppose the binary tree is:

```<code>         1
        /  \
       2    3
      / \  / \
     4   5 6  7
            \
             8
</code>```

Bottom view of the tree is: 4 2 5 6 8 7

```<code>    Ok so for the first example,
    Horizontal distance of node with value 1: 0, level = 1
    Horizontal distance of node with value 2: 0 - 1 = -1, level = 2
    Horizontal distance of node with value 3: 0 + 1 = 1, level = 2
    Horizontal distance of node with value 4: -1 - 1 = -2, level = 3
    Horizontal distance of node with value 5: -1 + 1 = 0, level = 3
    Horizontal distance of node with value 6: 1 - 1 = 0, level = 3
    Horizontal distance of node with value 7: 1 + 1 = 2, level = 3
    Horizontal distance of node with value 8: 0 + 1 = 1, level = 4

    So for each vertical line that is for hd=0, print those nodes which appear in the last level of that line.
    So for hd = -2, print 4
    for hd = -1, print 2
    for hd = 0, print 5 and 6 because they both appear in the last level of that vertical line
    for hd = 1, print 8
    for hd = 2, print 7
</code>```

One more example for reference :

```<code>         1
      /     \
    2         3
   / \       / \
  4   5     6     7
 / \ / \   / \    / \
8  9 10 11 12 13 14 15
</code>```

So the output for this will be :
8 4 9 10 12 5 6 11 13 14 7 15

```<code>Similarly for this example
hd of node with value 1: 0, , level = 1
hd of node with value 2: -1, level = 2
hd of node with value 3: 1, level = 2
hd of node with value 4: -2, level = 3
hd of node with value 5: 0, , level = 3
hd of node with value 6: 0, level = 3
hd of node with value 7: 2, level = 3
hd of node with value 8: -3, level = 4
hd of node with value 9: -1, level = 4
hd of node with value 10: -1, level = 4
hd of node with value 11: 1, level = 4
hd of node with value 12: -1, level = 4
hd of node with value 13: 1, level = 4
hd of node with value 14: 1, level = 4
hd of node with value 15: 3, level = 4

So, the output will be:
hd = -3, print 8
hd = -2, print 4
hd = -1, print 9 10 12
hd = 0, print 5 6
hd = 1, print 11 13 14
hd = 2, print 7
hd = 3, print 15

So the ouput will be:
8 4 9 10 12 5 6 11 13 14 7 15
</code>```

I already know a method in which I can do it using a lot of extra space (a map, and a 1-D array for storing the level of the last element in that vertical line) and with time complexity of $O(N \log N)$.
And this is the implementation of this method:

```<code>#include <iostream>
#include <cstdio>
#include <map>
#include <vector>

using namespace std;

struct Node{
       int data;
       struct Node *left, *right;
};

Node* newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}

int height(Node *node)
{
    if(node == NULL)
            return 0;
    else{
         int lh = height(node->left);
         int rh = height(node->right);

         if(lh > rh)
               return (lh+1);
         else
               return (rh+1);
    }
}

void printBottom(Node *node, int level, int hd, int min, map< int, vector<int> >& visited, int lev[], int l)
{
     if(node == NULL)
             return;
     if(level == 1){
              if(lev[hd-min] == 0 || lev[hd-min] == l){
                      lev[hd-min] = l;
                      visited[hd-min].push_back(node->data);
              }
     }
     else if(level > 1)
     {
          printBottom(node->left, level-1, hd-1, min, visited, lev, l);
          printBottom(node->right, level-1, hd+1, min, visited, lev, l);
     }
}

void findMinMax(Node *node, int *min, int *max, int hd)
{
     if(node == NULL)
             return;

     if(hd < *min)
          *min = hd;
     else if(hd > *max)
          *max = hd;

     findMinMax(node->left, min, max, hd-1);
     findMinMax(node->right, min, max, hd+1);
}

int main()
{
    Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->left->left->left = newNode(8);
    root->left->left->right = newNode(9);
    root->left->right->left = newNode(10);
    root->left->right->right = newNode(11);
    root->right->left->left = newNode(12);
    root->right->left->right = newNode(13);
    root->right->right->left = newNode(14);
    root->right->right->right = newNode(15);

    int min = 0, max = 0;

    findMinMax(root, &min, &max, 0);

    int lev[max-min+1];
    map < int, vector<int> > visited;
    map< int,vector<int> > :: iterator it;

    for(int i = 0; i < max-min+1; i++)
            lev[i] = 0;

    int h = height(root);

    for (int i=h; i>0; i--){
        printBottom(root, i, 0, min, visited, lev, i);
    }

    for(it = visited.begin() ; it != visited.end() ; it++) {
        for(int i=0 ; i < it->second.size() ; i++) {
            cout << it->second[i] << " ";
        }
    }

    return 0;
}
</code>```

I am seeking help to do this in more optimized way, which used less space or time. Is there any other efficient method for this problem?

答:
There are still some things about your question that are unclear, but it seems like your rule for "bottom" is a node that does not have grandchildren. The following function will print all nodes that meet this definition of bottom:

```<code>// Print out nodes that don't have grandchildren
void printBottom2(Node *root)
{
    if (root->left) {
        // recursive call for left child
        printBottom2(root->left);
    }

    // check for grand children of this node:
    if (
         // left isn't present or has no children
         ( !root->left || ( !root->left->left && !root->left->right ) )
         &&
         // right isn't present or has no children
         ( !root->right || ( !root->right->left && !root->right->right) )
       )
    {
        // Since there is no child of left or right, print data:
        cout << root->data << " ";
    }

    if (root->right) {
        // recursive call for right child
        printBottom2(root->right);
    }
}
</code>```

You can display the full bottom of a tree by calling printBottom2 with just the root node: printBottom2(root); in your code above.

Title: Print bottom view of a binary tree

Body:
There are still some things about your question that are unclear, but it seems like your rule for "bottom" is a node that does not have grandchildren. The following function will print all nodes that meet this definition of bottom:

// Print out nodes that don't have grandchildren
void printBottom2(Node *root)
{
    if (root->left) {
        // recursive call for left child
        printBottom2(root->left);
    }

    // check for grand children of this node:
    if (
         // left isn't present or has no children
         ( !root->left || ( !root->left->left && !root->left->right ) )
         &&
         // right isn't present or has no children
         ( !root->right || ( !root->right->left && !root->right->right) )
       )
    {
        // Since there is no child of left or right, print data:
        cout << root->data << " ";
    }

    if (root->right) {
        // recursive call for right child
        printBottom2(root->right);
    }
}

You can display the full bottom of a tree by calling printBottom2 with just the root node: printBottom2(root); in your code above.


问:
how should I handle server error during ajax logout?
I need to write a handler for server error during user logout. What is a common practice?

```<code>ajax.post({
    url: '/auth/logout'
}).done(function (response) {
    switch (response.statusCode) {
        case 200:
        {
            //update UI related to userinformation
        }
        case 500:
        {
            //what should I do here?
        }
    }
})
</code>```

Note: The ajax function is reimplementation of $.ajax() with the exception that it always calls done callback (custom promise object is always resolved and never rejected)

UPDATE:
On server I destroy session and delete auto login cookie if it's present. Is it a sensible approach (if server error is received) to delete cookies related to session name and auto login on client using javascript (presuming that I know their names)?

答:
This is related to the age-old question, "How do I handle the error if I try to delete a resource that isn't found?" Practically speaking, the job is done. Usually, I'll just move on, at most logging a WARN if it matters.

The risk here comes from a login session being a security artifact. So if the logout failed, you may have a lingering session that would be vulnerable to attack.

Most of the time, that may not matter. Generally, once you drop the reference to the session token (or whatever security artifact you're using), then it can't be recovered anyway.

Depending on what user experience you want, you could just fail silently, or else let the user know that logout failed, and let them try again.

But if you were writing a website for a bank, it's more of a problem. Implement some sort of retry mechanism. Maybe run it in the background, to retry until you get a positive result.


答: I think this problem goes even deeper than that. Even if you do refactor it into a static method, then you get code where you call single static method all over the place. Which in my opinion is code smell in itself. It might indicate you are missing some important abstraction.  Maybe you want to create a code that will do some pre and post-processing while allowing you to change what happens in between. That pre and post-processing will contain the common calls while the in between will depend on concrete implementation.</p>


答: It depends on the environment where you're programming. At a previous job, most of my work was in Perl; during my time there I got quite proficient at it. Now I work at a place that has legacy programs in three languages that I barely know the syntax; I'm expected to maintain them in addition to my work on new projects. I'm now less a master of any language, but I think I've gotten a better feel for programming. I've learned how to think more abstractly, see the big picture first, and then look up the syntax and the libraries to fill in the details.

Title: How many programming languages is a programmer expected to be an expert at?

Body:
Do most programmers specialize on a single stack, leaving other things be, or are they expert at multiple languages at the same time? If it's more than one, how many is standard?

By expert, I mean more than simply knowing the syntax of a language - an expert knows enough of standard libraries, tools, environments and syntax to be able to write non-trivial programs without having to constantly look things up or read books/tutorials.


答:
When an error occurs in a web application, this is what happens:

Error

Try/Catch (or any other comparison mechanism)

window.error

Browser error

Your application should consider 2 kind of errors (minimum):

FATAL Error

NON-FATAL Error

A fatal error is an error that does not allow the execution of the application, and does not consider the possibility that the client retry to execute the action. Probably, the user is informed that an error has occurred, and all the information already present in the client are destroyed to force a creation of the data structure needed from scratch.

A NON-fatal error must allow the user to understand that something has happened and, in the case log-in case, he/she/it must rerun the action.

Then, as described:

A 500 from the server can not be considered a fatal error in a web app for the Log-in action. It should be treated as an action like the others, probably NON-fatal.

A good practice to understand what errors to consider, and what is their degree of severity, is to create a table that describes actions, and consider columns with the different options of possible errors:

a. invalid url;

b. server response error;

c. response content error;

d. physical connection/network errors;

Title: how should I handle server error during ajax logout?

Body:
I need to write a handler for server error during user logout. What is a common practice?

```<code>ajax.post({
    url: '/auth/logout'
}).done(function (response) {
    switch (response.statusCode) {
        case 200:
        {
            //update UI related to userinformation
        }
        case 500:
        {
            //what should I do here?
        }
    }
})
</code>```

Note: The ajax function is reimplementation of $.ajax() with the exception that it always calls done callback (custom promise object is always resolved and never rejected)

UPDATE:
On server I destroy session and delete auto login cookie if it's present. Is it a sensible approach (if server error is received) to delete cookies related to session name and auto login on client using javascript (presuming that I know their names)?


答:
Fundamentally you should do the same thing you did for sucess -- let the user know about it.

Note that this is specific to the front end, because the front end session continues.   The back end should return sucess, even if it doesn't have a valid session to close out.  Only if it truly is, for some strange reason, going to maintain the session, should it return failure.  In which case it is vital that your front end let the user know about it.


问:
Interface questions for using Command Pattern and Dependency Injection together
I have many projects that have essentially the same high level requirement: test all hardware on a device. Each device can have a different communication protocol, requires different test equipment to exercise the device, etc.  So, at a high level a test is essentially the following:

obtain handles to test equipment

apply stimulus to device

measure/detect/record something measurable

remove stimulus

store results

handle errors

I thus created an interface class ( CTestEquipment ) as every piece of test equipment can be a concrete class with a unique implementation.  The device under test can be considered a piece of test equipment as well.  I'm using Dependency Injection for the driver of the test equipment.  This is to allow for easy changes from one driver to another and to keep the driver and the equipment somewhat decoupled. For instance, a power supply might use a GPIB driver, a VISA driver, or raw serial commands. Each project can choose which is applicable and change one line ( the driver instantiation ).

Next, I created classes to implement the Command pattern for the test equipment/device. So, CTestEquipment inherits from CCmdReceiver. A concrete command class calls the execute method which via the receiver calls the test equipment's tx/rx methods. Those methods call the underlying driver.

Questions/Problems:
How do I extract the received data from the command?  Right now execute has no arguments and returns nothing. A concrete command might only transmit, only receive, or do both so the execute interface needs to either return a value even when there's no received data or some other way I need to be able to access it.  CSetSerialNumber has no received data. CGetMode does.

Since the command is calling tx/rx which ultimately calls the driver's tx/rx how do I package the data to those calls since each driver could take something different?  I've contemplated a CPacket interface and various concrete implementations but then how do I make sure passing a concrete class that doesn't match the driver is caught?

```<code>//--------------------------------------------------------------------------------------
// CCommand
//      Abstract interface that defines the execute method
//--------------------------------------------------------------------------------------
class CCommand
{
protected:
CCmdReceiver *      _rcvr_p;            // receiver interface

// Default Constructor
CCommand()
{}

public:
// Constructor
CCommand
    (
    CCmdReceiver *  r               // receiver interface
    ) :
   _rcvr_p      ( r )
{}

// Destructor
virtual ~CCommand()
{}

// Method to Execute the Command
virtual void execute() = 0;
};

//--------------------------------------------------------------------------------------
// CCmdReceiver
//      Abstract interface that defines the command action
//--------------------------------------------------------------------------------------
class CCmdReceiver
{
public:
virtual void flush() = 0;

virtual void rx( std::vector< unsigned char > & v ) = 0;

//virtual void tx( std::string const & s ) = 0;
virtual void tx( CPacket * p ) = 0;
};

/*------------------------------------------------------------------------------
Test equipment driver abstract base class
------------------------------------------------------------------------------*/
class CDriver
{
public:
/*--------------------------------------------------------------------------
Constructor
--------------------------------------------------------------------------*/
CDriver() :
    _is_open            ( false )
{}

/*--------------------------------------------------------------------------
Destructor
--------------------------------------------------------------------------*/
virtual ~CDriver()
{}

//protected:
/*--------------------------------------------------------------------------
Close the Driver
    Must be implemented in a derived class
--------------------------------------------------------------------------*/
virtual void close() = 0;

/*--------------------------------------------------------------------------
Get the Received Data
--------------------------------------------------------------------------*/
template< typename tVal >
tVal getRxData();

/*--------------------------------------------------------------------------
Determine if the Driver is Open
--------------------------------------------------------------------------*/
virtual bool isOpen()
{
return( _is_open );
}

/*--------------------------------------------------------------------------
Open the Driver
    Must be implemented in a derived class
--------------------------------------------------------------------------*/
virtual void open() = 0;

/*--------------------------------------------------------------------------
Receive Data
--------------------------------------------------------------------------*/
virtual void rx()
{}

/*--------------------------------------------------------------------------
Set Open/Closed Flag State
--------------------------------------------------------------------------*/
inline void setOpenState
    (
    bool const & open = true
    )
{
_is_open = open;
}

/*--------------------------------------------------------------------------
Transmit Data
--------------------------------------------------------------------------*/
virtual void tx
    (
    std::string const & cmd         // command to transmit
    )
{}

private:
bool    _is_open;           // flag to indicate if protocol is open
};

//--------------------------------------------------------------------------------------
// Abstract Test Equipment Class
//      Utilizes constructor DI for device driver
//      Utilizes RAII for open/close
//--------------------------------------------------------------------------------------
class CTestEquipment : public CCmdReceiver
{
public:
/// Constructor
CTestEquipment
    (
    boost::shared_ptr< CDriver > const &
                drvr        // device driver
    ) :
    _drvr           ( drvr ),
    _init_cnt           ( 0 )
{
_drvr->open();
incInitCnt();
}

/// Destructor
virtual ~CTestEquipment()
{
if( isInitialized() )
     {
     _drvr->close();
     }
}

/// Function to Access the Equipment's Driver
inline boost::shared_ptr< CDriver > const & accessDriver() const
{
return( _drvr );
}   // accessDriver()

/// Decrement the Initialization Count
inline void decInitCnt()
{
--_init_cnt;
}   // decInitCnt()

/// Get the Initialization Count
inline int getInitCnt() const
{
return( _init_cnt );
}   // getInitCnt()

/// Increment the Initialization Count
inline void incInitCnt()
{
++_init_cnt;
}   // incInitCnt()

/// Check if Initialization has Occurred
inline bool isInitialized() const
{
return( _init_cnt >= 1 );
}   // isInitialized()

/// Determine if the Driver is Open
inline bool isOpen() const
{
return( _drvr->isOpen() );
}   // isOpen()

 protected:
/// Reset the Equipment
virtual void reset()
{
//_drvr->reset();
}

/// Function to Receive Data from the Equipment
inline void rx()
{
_drvr->rx();
}

/// Function to Set the Device to a Default State
virtual void setToDflts()
{}

/// Function to Transmit a Command to the Equipment
inline void tx( std::string const & cmd )
{
_drvr->tx( cmd );
}

/// Function to Transmit a Command, Receive the Response, and Return the Parsed    Value
template< typename tVal >
tVal txRx
    (
    std::string const & cmd         // command to transmit
        )
{
_drvr->tx( cmd );
_drvr->rx();

return( _drvr->getRxData< tVal >() );
}

protected:
boost::shared_ptr< CDriver > const &
        _drvr;              // device driver
int     _init_cnt;          // initialization count
};

class CGetMode : public CCommand
{
public:
CGetMode
    (
    CCmdReceiver *  rcvr            // command receiver
    );

void execute()
    {
    // G: what type is cmd?
    // G: what type is buffer?
    // G: how do we access buffer?
    _rcvr_p->flush();
    _rcvr_p->tx( cmd );
    _rcvr_p->rx( buffer );
    }
 };

//--------------------------------------------------------------------------------------
// CSetSerialNumber
//     Extends command interface. Implements the execute method and invokes it on a receiver.
//--------------------------------------------------------------------------------------
class CSetSerialNumber : public CCommand
{
public:
// Constructor
CSetSerialNumber
    (
    CCmdReceiver *  rcvr                // command receiver
    );

void execute()
    {
    // G: what type is cmd?
    _rcvr_p->tx( cmd );
    }
};
</code>```

答:
You need a data transfer protocol.  It can be as simple as a string with comma-separated values, or as complex as some XML backed up by a schema.  Whatever you decide, the receiver will have to be smart enough to decode it.

As an example, one of your commands could retrieve a comma-separated header:

```<code>TIME, ALTITUDE, TEMPERATURE, AIRSPEED, WHATEVER
</code>```

This tells you not only the name of each signal, but how many signals there are.  You can use this information to set up your decoder on the receiver side.

You could also use something like Protocol Buffers.

Body:
You need a data transfer protocol.  It can be as simple as a string with comma-separated values, or as complex as some XML backed up by a schema.  Whatever you decide, the receiver will have to be smart enough to decode it.

As an example, one of your commands could retrieve a comma-separated header:

TIME, ALTITUDE, TEMPERATURE, AIRSPEED, WHATEVER

This tells you not only the name of each signal, but how many signals there are.  You can use this information to set up your decoder on the receiver side.

You could also use something like Protocol Buffers.


答: One, but must be able to read non-trivial real-world programs that are written in a few other languages from time to time.  In some way, the one in which the programmer is an expert is like their mother tongue, they think in it, but learning and speaking other languages is very good in that it shows the programmer can appreciate other ways of thinking.  If they can think in more than one language as fluent as their mother tongue, that is awesome.</p>


问:
How much effort should I invest in creating loosely coupled designs?
I am currently learning about design patterns.

I think most people would agree that these patterns are great tools, but should be used with moderation and not as the answer for everything. Using them too much would over-complicate the application with little benefit. Patterns should be used only where they can be the best solution or help in the creation of a good solution (do you agree?).

With this in mind:

The book I'm reading (Head First Design Patterns) frequently emphasizes the importance of loose coupling. This loose coupling is acheived by following principles such as 'program to an interface, not an implementation' and 'encapsulate what varies'.

Basically, most patterns I learned so far exist mostly to allow designs to be loosely coupled, and thus more flexible.

I understand the importance and benefits of loose coupling.

But my question is, how much effort should one actually invest in creating loosely coupled, flexible designs?

Those who oppose design patterns say that the costs to using these patterns often outweighs the benefits. You invest a lot of time in creating a loosely coupled design using some pattern, where in reality - the loose coupling, 'programing to an interface, not an implementation', and all of these principles - might not actually be so important.

What I'd like to know, is how much effort should I actually put in creating additional levels of abstraction and designs, only to allow my application to follow OO principles such as loose coupling, programmign to an interface, etc. Is it really worth it? How much effort should I put in this?

答:
Fatuous answer: the more you do it, the less effort it is.

Basically, building loosely coupled code isn't really very hard.  Training your mind to think in terms of loose coupling, on the other hand, is.  And, well, I believe it to be totally worth it.

Suppose you take a job that uses an iterative approach to software development, as has been recommended by most everyone over the last 20 years.  You build something that works beautifully in iteration 1.  In iteration 2 you build on top of it, adding some new features, and somewhat bending one or two things a bit when they don't fit into your iteration 1 concept of how things should work. Now comes iteration 3, and you find out the requirements demand you rethink your basic architecture.  How do you tear your code apart and rebuild it without going back to square one?

This happens.  A lot.  It either makes projects run late, or it makes everyone too scared to do what needs to be done in later iterations.  In the best case, you get a Big Ball of Mud.  Things like loose coupling and the single responsibility principle mitigate these problems in a big way.  That's why SOLID principles are touted--they really do help.

And you will find that after you've got a few loosely coupled designs under your belt, it starts to come naturally.  Patterns are things that people found that worked for them, so they documented them.  They're useful tools that also come naturally with time.


问:
Why should one subclass instead of composite when using the Factory Method design pattern?
I'm currently learning about design patterns. I learned about the Factory Method pattern.

This pattern means that in order to implement a factory to create objects, one should subclass the class that needs these objects, and have the subclass create them. This way the superclass only works with more abstract references instead of the concrete implementations the subclass generates, which creates a loosely coupled design.

This usually means the superclass becomes abstract, since it's createObject() method must be abstract so that the subclass containing the factory method will have to implement this method.

Like any factory pattern, this pattern encapsulates the creation of the concrete object, and allows the client to work with a higher level of abstraction. But this specific pattern is built on inheritance.

What I don't understand is - Why would anybody go through all the trouble of subclassing the class that needs a factory and making it abstract? Composition is so much better for this purpose in any way.

It makes much more sense to create an abstract class or an interface called Factory. It would declare one method: createObject(). We create concrete implementations of it for different purposes (WeaponFactory, TitleFactory..) Then, we give the client a Factory member instance factory. This reference is set to whatever concrete Factory is needed at runtime, and the client can simply use factory's createObject() when needed (without having to know what concrete implementation factory is holding).

I don't understand why one would go through the trouble of subclassing a class and making it abstract just for the benefit of allowing it to use a factory in a loosely-coupled manner.

The simple composition-based design I described is better in any way - I think.

Do you agree? Could  you explain why anybody would use the Factory Method Pattern I described?

答:
In general i agree that composition its better than inheritance. GOF design patterns are great because there are probably the first attempt to build a language (the patterns are a language for me) in a new level of abstraction, at design level instead of programatic level, this is great, but some concrete patterns are perhaps obsolete or can be improved to adapt to your concrete situation, technology or preferences. The study of patterns is a good thing, can teach you some good OO tricks and techniques, but the application of patterns "by the book" its never a good idea IMMO.

Anyway, i see a problem with your design, at least a problem in a static typed language, WeaponFactory return weapons and titleFactory return titles i suppose, the return type for "createObject" its different and this return type is part of the signature of the method. But off course with composition and DI you can achieve the same goals that the factory method try to achieve. For example:

```<code>Client clientWithRealWeapon = new Client(new RealWeaponsFactory());
Client clientWithMocksWeapon = new Client(new MockWeaponsFactory());
</code>```

its a solution with composition and DI, the same can be done creating two subclass of client: ClientWithRealWeapons and ClientWithMocksWeapons that override a method for creating weapons.

Body:
In general i agree that composition its better than inheritance. GOF design patterns are great because there are probably the first attempt to build a language (the patterns are a language for me) in a new level of abstraction, at design level instead of programatic level, this is great, but some concrete patterns are perhaps obsolete or can be improved to adapt to your concrete situation, technology or preferences. The study of patterns is a good thing, can teach you some good OO tricks and techniques, but the application of patterns "by the book" its never a good idea IMMO.

Anyway, i see a problem with your design, at least a problem in a static typed language, WeaponFactory return weapons and titleFactory return titles i suppose, the return type for "createObject" its different and this return type is part of the signature of the method. But off course with composition and DI you can achieve the same goals that the factory method try to achieve. For example:

Client clientWithRealWeapon = new Client(new RealWeaponsFactory());
Client clientWithMocksWeapon = new Client(new MockWeaponsFactory());

its a solution with composition and DI, the same can be done creating two subclass of client: ClientWithRealWeapons and ClientWithMocksWeapons that override a method for creating weapons.


答:
I think that you're looking at the problem the wrong way. If you have a need to create one of several subclasses, then you'll need to use the Factory method as you've described it to solve the problem.

For example, if you have a system where you need to have the vast majority of your code be the same but only vary in a few details, then subclassing makes sense in its own right and you'll do that, then create the factories that are able to kick out the correct subclasses based on the rules each needs. You might also have a legacy system where subclasses are already in use, and you find that as it scales you want to add factories to help with creation of your objects.

If you are using something like an Entity system and you don't need subclasses of your Product object, by all means don't create them. However, you might want to make sure your single Class at least implements an Interface, because every once in a while you need to use a completely unrelated implementation when you get a requirement you didn't see coming.

Title: Why should one subclass instead of composite when using the Factory Method design pattern?

Body:
I'm currently learning about design patterns. I learned about the Factory Method pattern.

This pattern means that in order to implement a factory to create objects, one should subclass the class that needs these objects, and have the subclass create them. This way the superclass only works with more abstract references instead of the concrete implementations the subclass generates, which creates a loosely coupled design.

This usually means the superclass becomes abstract, since it's createObject() method must be abstract so that the subclass containing the factory method will have to implement this method.

Like any factory pattern, this pattern encapsulates the creation of the concrete object, and allows the client to work with a higher level of abstraction. But this specific pattern is built on inheritance.

What I don't understand is - Why would anybody go through all the trouble of subclassing the class that needs a factory and making it abstract? Composition is so much better for this purpose in any way.

It makes much more sense to create an abstract class or an interface called Factory. It would declare one method: createObject(). We create concrete implementations of it for different purposes (WeaponFactory, TitleFactory..) Then, we give the client a Factory member instance factory. This reference is set to whatever concrete Factory is needed at runtime, and the client can simply use factory's createObject() when needed (without having to know what concrete implementation factory is holding).

I don't understand why one would go through the trouble of subclassing a class and making it abstract just for the benefit of allowing it to use a factory in a loosely-coupled manner.

The simple composition-based design I described is better in any way - I think.

Do you agree? Could  you explain why anybody would use the Factory Method Pattern I described?


答:
Amount of effort required is not always going to tell you enough; I think a better measure would be the effort to payoff ratio.  But figuring out what the payoff might be is not always straightforward and error free.

The thing to keep in mind with patterns that increase flexibility is that it costs some effort to put them in, and unless you can see exactly why you need them, you may end up having the complication in the code, but never ever using it.  If the flexibility is never flexed, it might as well not be there.

There is one thing that you should do always (or as close to it as you reasonably can get): making the individual components of your software (objects for OOP, functions for functional or procedural programming) into black boxes.  A black box is something whose insides (implementation) we don't know or care about.

If we don't know or care about how it works, then we aren't going to try to use anything but the interface, so if the implementation changes without changing the interface, that only matters inside the black box -- nothing outside it can be affected.  It also makes thinking about the program easier, because you don't have to keep every single detail of the whole program in your head.  The more details you can legitimately forget, the more room there is in your head for the details that matter.

I think you've misunderstood the objections to design patterns; I'm not a fan of them, but I very much like the principle of loose coupling and programming to an interface.  My strongest objection to them is that they're presented as a pre-packaged solution that doesn't encourage understanding the principles behind them, but rather encourages memorization of details.  I'm not going to recommend that you don't study them, but when you do, remember that understanding the principles behind them is more important than the specifics of any particular pattern.

One of the objections to design patterns is that they're 'obvious' or that 'I was using them before I heard of them, just not by that name'.  The reason people can make those objections, or the originators of design patterns could come up with them in the first place, is that they understood the principles behind them.

Using black boxes organizes your code in a sane way and they don't typically cost much (if anything); use them everywhere.  Using a design pattern or some other technique that adds a layer of abstraction or complicates things has a cost; never use them just because they're pretty or neat or clever; use them when they fit the problem and the cost is worth paying to get the benefit.

Title: How much effort should I invest in creating loosely coupled designs?

Body:
I am currently learning about design patterns.

I think most people would agree that these patterns are great tools, but should be used with moderation and not as the answer for everything. Using them too much would over-complicate the application with little benefit. Patterns should be used only where they can be the best solution or help in the creation of a good solution (do you agree?).

With this in mind:

The book I'm reading (Head First Design Patterns) frequently emphasizes the importance of loose coupling. This loose coupling is acheived by following principles such as 'program to an interface, not an implementation' and 'encapsulate what varies'.

Basically, most patterns I learned so far exist mostly to allow designs to be loosely coupled, and thus more flexible.

I understand the importance and benefits of loose coupling.

But my question is, how much effort should one actually invest in creating loosely coupled, flexible designs?

Those who oppose design patterns say that the costs to using these patterns often outweighs the benefits. You invest a lot of time in creating a loosely coupled design using some pattern, where in reality - the loose coupling, 'programing to an interface, not an implementation', and all of these principles - might not actually be so important.

What I'd like to know, is how much effort should I actually put in creating additional levels of abstraction and designs, only to allow my application to follow OO principles such as loose coupling, programmign to an interface, etc. Is it really worth it? How much effort should I put in this?


答:
First create a list, indexed by vertical line, recording the maximum level found on that line.  Walk the tree one time to fill in this list.

At this point every list[vertical] entry contains the level that can be seen in the bottom view of the tree.

Then walk the tree again, printing out each node whose level matches the maximum found on its line.

```<code>int MaxLvl[];

void printBotOne( node *qNode, int Level, int Column ) {
  if qNode then {
    printBotOne(qNode->left, Level+1, Column-1);
    if MaxLvl[Column]<Level then MaxLvl[Column] = Level;
    printBotOne(qNode->right, Level+1, Column+1);
  }
}

void printBotTwo( node *qNode, int Level, int Column ) {
  if qNode then {
    printBotTwo(qNode->left, Level+1, Column-1);
    if MaxLvl[Column]==Level then cout << qNode->data << " ";
    printBotTwo(qNode->right, Level+1, Column+1);
  }
}

void printBottom( node *qNode ) {
  for(int II = 0; II<nodecount; II++) MaxLvl[II] = 0;
  printBotOne(qNode, 0, nodecount/2);
  printBotTwo(qNode, 0, nodecount/2);
}
</code>```

This requires a 1D array and runs in O(N).

Title: Print bottom view of a binary tree

Body:
For a binary tree we define horizontal distance as follows:

```<code>    Horizontal distance(hd) of root = 0
    If you go left then hd = hd(of its parent)-1, and
    if you go right then hd = hd(of its parent)+1.
</code>```

The bottom view of a tree then consists of all the nodes of the tree, where there is no node with the same hd and a greater level. (There may be multiple such nodes for a given value of hd. In this case all of them belong to the bottom view.) I'm looking for an algorithm that outputs the bottom view of a tree.

Examples:

Suppose the binary tree is:

```<code>         1
        /  \
       2    3
      / \  / \
     4   5 6  7
            \
             8
</code>```

Bottom view of the tree is: 4 2 5 6 8 7

```<code>    Ok so for the first example,
    Horizontal distance of node with value 1: 0, level = 1
    Horizontal distance of node with value 2: 0 - 1 = -1, level = 2
    Horizontal distance of node with value 3: 0 + 1 = 1, level = 2
    Horizontal distance of node with value 4: -1 - 1 = -2, level = 3
    Horizontal distance of node with value 5: -1 + 1 = 0, level = 3
    Horizontal distance of node with value 6: 1 - 1 = 0, level = 3
    Horizontal distance of node with value 7: 1 + 1 = 2, level = 3
    Horizontal distance of node with value 8: 0 + 1 = 1, level = 4

    So for each vertical line that is for hd=0, print those nodes which appear in the last level of that line.
    So for hd = -2, print 4
    for hd = -1, print 2
    for hd = 0, print 5 and 6 because they both appear in the last level of that vertical line
    for hd = 1, print 8
    for hd = 2, print 7
</code>```

One more example for reference :

```<code>         1
      /     \
    2         3
   / \       / \
  4   5     6     7
 / \ / \   / \    / \
8  9 10 11 12 13 14 15
</code>```

So the output for this will be :
8 4 9 10 12 5 6 11 13 14 7 15

```<code>Similarly for this example
hd of node with value 1: 0, , level = 1
hd of node with value 2: -1, level = 2
hd of node with value 3: 1, level = 2
hd of node with value 4: -2, level = 3
hd of node with value 5: 0, , level = 3
hd of node with value 6: 0, level = 3
hd of node with value 7: 2, level = 3
hd of node with value 8: -3, level = 4
hd of node with value 9: -1, level = 4
hd of node with value 10: -1, level = 4
hd of node with value 11: 1, level = 4
hd of node with value 12: -1, level = 4
hd of node with value 13: 1, level = 4
hd of node with value 14: 1, level = 4
hd of node with value 15: 3, level = 4

So, the output will be:
hd = -3, print 8
hd = -2, print 4
hd = -1, print 9 10 12
hd = 0, print 5 6
hd = 1, print 11 13 14
hd = 2, print 7
hd = 3, print 15

So the ouput will be:
8 4 9 10 12 5 6 11 13 14 7 15
</code>```

I already know a method in which I can do it using a lot of extra space (a map, and a 1-D array for storing the level of the last element in that vertical line) and with time complexity of $O(N \log N)$.
And this is the implementation of this method:

```<code>#include <iostream>
#include <cstdio>
#include <map>
#include <vector>

using namespace std;

struct Node{
       int data;
       struct Node *left, *right;
};

Node* newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}

int height(Node *node)
{
    if(node == NULL)
            return 0;
    else{
         int lh = height(node->left);
         int rh = height(node->right);

         if(lh > rh)
               return (lh+1);
         else
               return (rh+1);
    }
}

void printBottom(Node *node, int level, int hd, int min, map< int, vector<int> >& visited, int lev[], int l)
{
     if(node == NULL)
             return;
     if(level == 1){
              if(lev[hd-min] == 0 || lev[hd-min] == l){
                      lev[hd-min] = l;
                      visited[hd-min].push_back(node->data);
              }
     }
     else if(level > 1)
     {
          printBottom(node->left, level-1, hd-1, min, visited, lev, l);
          printBottom(node->right, level-1, hd+1, min, visited, lev, l);
     }
}

void findMinMax(Node *node, int *min, int *max, int hd)
{
     if(node == NULL)
             return;

     if(hd < *min)
          *min = hd;
     else if(hd > *max)
          *max = hd;

     findMinMax(node->left, min, max, hd-1);
     findMinMax(node->right, min, max, hd+1);
}

int main()
{
    Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->left->left->left = newNode(8);
    root->left->left->right = newNode(9);
    root->left->right->left = newNode(10);
    root->left->right->right = newNode(11);
    root->right->left->left = newNode(12);
    root->right->left->right = newNode(13);
    root->right->right->left = newNode(14);
    root->right->right->right = newNode(15);

    int min = 0, max = 0;

    findMinMax(root, &min, &max, 0);

    int lev[max-min+1];
    map < int, vector<int> > visited;
    map< int,vector<int> > :: iterator it;

    for(int i = 0; i < max-min+1; i++)
            lev[i] = 0;

    int h = height(root);

    for (int i=h; i>0; i--){
        printBottom(root, i, 0, min, visited, lev, i);
    }

    for(it = visited.begin() ; it != visited.end() ; it++) {
        for(int i=0 ; i < it->second.size() ; i++) {
            cout << it->second[i] << " ";
        }
    }

    return 0;
}
</code>```

I am seeking help to do this in more optimized way, which used less space or time. Is there any other efficient method for this problem?

Body:
First create a list, indexed by vertical line, recording the maximum level found on that line.  Walk the tree one time to fill in this list.

At this point every list[vertical] entry contains the level that can be seen in the bottom view of the tree.

Then walk the tree again, printing out each node whose level matches the maximum found on its line.

int MaxLvl[];

void printBotOne( node *qNode, int Level, int Column ) {
  if qNode then {
    printBotOne(qNode->left, Level+1, Column-1);
    if MaxLvl[Column]<Level then MaxLvl[Column] = Level;
    printBotOne(qNode->right, Level+1, Column+1);
  }
}

void printBotTwo( node *qNode, int Level, int Column ) {
  if qNode then {
    printBotTwo(qNode->left, Level+1, Column-1);
    if MaxLvl[Column]==Level then cout << qNode->data << " ";
    printBotTwo(qNode->right, Level+1, Column+1);
  }
}

void printBottom( node *qNode ) {
  for(int II = 0; II<nodecount; II++) MaxLvl[II] = 0;
  printBotOne(qNode, 0, nodecount/2);
  printBotTwo(qNode, 0, nodecount/2);
}

This requires a 1D array and runs in O(N).


问:
Moving Old Projects To Newer IDE's and Libraries
At work we have a few older projects that are stuck on .NET 1.1 and VS 2003. While these are probably to much work now to move forward I'm wondering if the effort to keep our newer projects up to date will be worth it. Specifically we would be looking at moving about 30 projects from .NET 3.5 to .NET 4.0 and VS2008 to VS2010.

My Questions for the community are:

Do you move your projects along as new tools and libraries become available or just start the newest stuff in the newest versions?

If you do move forward have you found the benefits out weigh the cost of the upgrade?

答:
I would definitely upgrade an ASP.NET 1.1 or 2.0 project if I needed to make significant changes to it.

If it's just puttering along, needing no work other than the odd copy change, leave it be. But it you have to add any real new functionality, it's worth doing the upgrade.

I've not encountered any problems that took more than minor effort to fix. Now, I'll concede that I haven't upgraded any massively complex projects from 1.1, only simple ones. But I've upgraded big sites from 2.0 to 3.5 (admittedly not a huge change between those two versions) without issue. And found it well worth doing so, if only to get access to LINQ when writing new functionality.

I wouldn't consider upgrading a 3.5 project to 4.0 just for the sake of doing so. Only if you really need or want something from the 4.0 framework.

As for Visual Studio versions, absolutely. We work in VS2010. I upgrade any project or solution that was last saved in an older version. I've never seen any issues upgrading the solution file to a newer Visual Studio.


问:
How many user stories per person should be completed per sprint?
Just ran across this figure, and wondering if there's another well know source than would help confirm these numbers:

Based on data I analyzed on successfully finished sprints, I
determined that a team should average around 1 to 1-1/2 user stories
(product backlog items of any sort, really) per person per sprint.

SOURCE: Mike Cohn's Blog on "Should the Daily Standup Be Person-by-Person or Story-by-Story?"

答:
The last I heard was that it was 1.5/2x the number of team members.

Also note, that Mike Cohn is not implying you should use these numbers, he is simply saying that over the many years in the industry and the many teams he has coached, he has found 1.5x/2x stories per team member to work best.  He gave this answer when I asked him what he considered to be the ideal user story size.

ContentLicense: CC BY-SA 4.0


问:
TDD verifying dependency method invoked correctly
I am trying to follow TDD in my proj but I can't get my head around how to verify I am calling a dependency correctly or even if I should be trying to verify it.  Here's the requirement:

Write an AddSalesOrderTask class that is responsible for adding an order to an ERP system.  The class can take any dependencies needed but must have an Execute method signature like this:

```<code>public class AddSalesOrderTask {

  public override bool Execute(OrderData input) {
     throw new NotImplementedException();
  }
}
</code>```

The AddSalesOrderTask.Execute method needs to map OrderData to ERPSalesOrder and then call IERPClient.AddSalesOrder.

I have an interface to access the ERP service like so:

```<code>public interface IERPClient {
    void AddSalesOrder(ERPSalesOrder order);
}
</code>```

How do I verify that the mapping is done and then passed into the client?  Should I be testing both operations in this method?  To make this testable my first thought was to introduce an IMapper interface and pass it as a dependency to AddSalesOrderTask:

```<code>public interface IMapper<in TFrom, in TTo> {
    void Map(TFrom source, TTo destination);
}
</code>```

Following TDD would this be a good first test?

```<code>    private AddSalesOrderTask _testObj;

    [Fake, UsedImplicitly]
    private IERPClient _client;

    [Fake, UsedImplicitly]
    private IMapper<Order, SalesOrder> _mapper;

    [TestInitialize]
    public void MyTestInitialize() {
        Fake.InitializeFixture(this);
        _testObj = new AddSalesOrderTask();
    }

    [TestMethod]
    public void Execute_MappedSalesOrderAddedToERP() {

        // Arrange
        var input = new OrderData();
        var salesOrder = new SalesOrder();

        // Act
        _testObj.Execute(input);

        // Assert
        A.CallTo(() => _mapper.Map(context.Order, salesOrder))
            .MustHaveHappened();
        A.CallTo(() => _client.AddSalesOrder(salesOrder))
            .MustHaveHappened();
    }
</code>```

Am I thinking about this correctly?

答:
If had a requirement that a SalesOrder needed to be added to an ERP system how would I do this in a TDD approach?

In TDD you could start with unit tests for the mapper and the ERPClient, and afterwards add a test like yours for the AddSalesOrderTask. You can also switch the order and start with tests for AddSalesOrderTask first, especially if you want to do TDD with stepwise refinement. But the more interesting question for your AddSalesOrderTask is, as @RobertHarvey has already pointed out in his comment, if the parts work together as intended. So if you want this to develop fully with TDD, you should also write an "integration test" for the parts, using the real mapper and the real ERP client. Note that TDD does not necessarily mean to write only unit tests.

An fully automated integration test will be more effort (and it will run much slower), since you will probably need a full test environment of your ERP system for this test, with a defined set of test data. If your ERP is a bloated monster, this can become a real pain, so you have to check if the fully automated TDD approach here is worth the additional effort, or if some (semi-)manual testing might be the better alternative. But if you think this might be working in your case, you can probably omit the unit test for your AddSalesOrderTask class (at least, as long as its responsibility is so trivial as in your case).

P.S.: I guess it should be

```<code> _testObj = new AddSalesOrderTask(_mapper, _client);
</code>```

in MyTestInitialize, you have to inject the two dependencies somewhere?

Body:
If had a requirement that a SalesOrder needed to be added to an ERP system how would I do this in a TDD approach?

In TDD you could start with unit tests for the mapper and the ERPClient, and afterwards add a test like yours for the AddSalesOrderTask. You can also switch the order and start with tests for AddSalesOrderTask first, especially if you want to do TDD with stepwise refinement. But the more interesting question for your AddSalesOrderTask is, as @RobertHarvey has already pointed out in his comment, if the parts work together as intended. So if you want this to develop fully with TDD, you should also write an "integration test" for the parts, using the real mapper and the real ERP client. Note that TDD does not necessarily mean to write only unit tests.

An fully automated integration test will be more effort (and it will run much slower), since you will probably need a full test environment of your ERP system for this test, with a defined set of test data. If your ERP is a bloated monster, this can become a real pain, so you have to check if the fully automated TDD approach here is worth the additional effort, or if some (semi-)manual testing might be the better alternative. But if you think this might be working in your case, you can probably omit the unit test for your AddSalesOrderTask class (at least, as long as its responsibility is so trivial as in your case).

P.S.: I guess it should be

 _testObj = new AddSalesOrderTask(_mapper, _client);

in MyTestInitialize, you have to inject the two dependencies somewhere?


问:
What is the word to describe languages that have classes and inheritance?
What is the word used to describe the type of programming languages that provide explicit syntax for defining classes and that support inheritance?

For example: "A ______ language, such as C++, Java, C#, or D."

I keep thinking "object oriented", but that also includes languages like Lua and JavaScript, which aren't quite what I'm thinking of.

I am sure there is a definitive term for this group of languages, I just do not know what it is.

答:
Class-based object-oriented language

Class-based programming, or more commonly class-orientation, is a style of object-oriented programming (OOP) in which inheritance is achieved by defining classes of objects, as opposed to the objects themselves (compare prototype-based programming).


答:
Tricky question, because there are a lot of factors at play.

On the one hand, keeping current will make your life much better in the long run. Eventually hardware and operating systems will outrun your code libraries, and you'll either have to do a huge upgrade, under pressure, or you'll have to deploy some evil kludge environment.

On the other hand, spending a lot of time updating existing code will make your deliverables look like crap. In the business world, you seldom get credit for things not breaking, and, ironically, you often get credit for fixing things that only broke because you neglected them.

I say use your judgment. Keep mission critical stuff up to date, and let older, less relevant code fall by the wayside.

Title: Moving Old Projects To Newer IDE's and Libraries

Body:
At work we have a few older projects that are stuck on .NET 1.1 and VS 2003. While these are probably to much work now to move forward I'm wondering if the effort to keep our newer projects up to date will be worth it. Specifically we would be looking at moving about 30 projects from .NET 3.5 to .NET 4.0 and VS2008 to VS2010.

My Questions for the community are:

Do you move your projects along as new tools and libraries become available or just start the newest stuff in the newest versions?

If you do move forward have you found the benefits out weigh the cost of the upgrade?


问:
Is a genetic algorithm needed when computation is infinitely fast?
From what I understand, genetic algorithms try out multiple variations and evaluate the fitness of each variation. Then they select the best variations, change them a bit and continue the process with the next generation.

But what if we have unlimited computation resources? Can we then just try out all possible variations and evaluate their fitness without resorting to the complex process of breeding new generations? In other words, are genetic algorithms only needed when computation is expensive and when a brute-force method is impossible? Or do they add other benefits as well?

答:
Genetic algorithms are basically a guided trial-and-error methodology. The only advantage I can think of for a GA over a exhaustive search is that since GA optimizes a fitness function in steps, you might get to an optimal solution faster, because the GA will favor solutions that are incrementally better. An exhaustive search that's guaranteed to find a solution might go the long way around.

If "computation resources" means CPU but not memory, then the GA gene pool might have a smaller memory footprint, requiring less memory.

On the other hand, because of hill climbing, a GA might get stuck on a local maximum & any mutations might not be sufficient to shake it loose.

Also, the search time for GA grows exponentially with the size of the input, so an exhaustive search may end up being faster after all, depending on the size of the space you're searching, and if you can constrain the size of the space by excluding possibilities.

...

Lately I've been thinking about GAs in terms of "entropy per second" and measuring the progress of my GA as a measure of how many distinct possibilities it runs through per second. Then I can compare that to the total entropy of the problem space. If a brute force search can beat that entropy per second with parallelization or fast processors, then a GA's "best score" isn't any better than a discovered "best score".

But I've just been noodling that over; I haven't actually instrumented a GA that way yet.

(Entropy is ln(N) for N possible states, or ln(N) - sum(n * ln(n) for all n) / N where n is the possible ways to achieve one result out of N possible outcomes.)

Interesting question :)


问:
Is doing an assignment inside a condition considered a code smell?
Many times I have to write a loop that requires initialization of a loop condition, and an update every time the loop executes. Here's one example:

```<code>List<String> currentStrings = getCurrentStrings();
while(currentStrings.size() > 0) {
  doThingsThatCanAlterCurrentStrings();
  currentStrings = getCurrentStrings();
}
</code>```

One things I dislike about this code is the duplicate call to getCurrentStrings(). One option is to add the assignment to the condition as follows:

```<code>List<String> currentStrings;
while( (currentStrings = getCurrentStrings()).size() > 0) {
  doThingsThatCanAlterCurrentStrings();
}
</code>```

But while I now have less duplication and less code, i feel that my code is now harder to read. On the other hand, it is easier to understand that we are looping on a variable that may be changed by the loop.

What is the best practice to follow in cases like this?

答:
That sort of construction shows up when doing some sort of buffered read, where the read fills a buffer and returns the number of bytes read, or 0. It's a pretty familiar construct.

There's a risk someone might think you got = confused with ==. You might get a warning if you're using a style checker.

Honestly, I'd be more bothered by the (...).size() than the assignment. That seems a little iffy, because you're dereferencing the assignment. ;)

I don't think there's a hard rule, unless you're strictly following the advice of a style checker & it flags it with a warning.