问:
Is LINQ to SQL dead?
Is there any reason to keep using Linq to SQL, or is it better to move to ORM techniques like EF, NHibernate etc.

We are using Linq to SQL in a new large enterprise application that will exist for a long time. The motivation for this new enterprise application is that the application was ordinary written in Visual Basic and since Microsoft stopped the support we where forced to rewrite the application. It’s seems that we are already there but this time with our DAL (Data Access Layer).

I have already read this article, but it only compare to EF's weakness.

答:
It's not dead, but Microsoft is now focused on the Entity Framework.

I've used LINQ to SQL on small projects, and it's quite nice as a lightweight data-layer and i'd consider using it again on similar sized projects. The LINQ implementation itself is really good and until recently much better than the NHibernate LINQ project. On the larger project I used L2S on, I found it hard to come up with a unit-of-work pattern that I was happy with, due to limitations with the L2S 'DataContext' class. Trying to implement something like 'Session per request' with L2S seems either very difficult or impossible.

I also wouldn't really consider L2S as a true ORM, as it really doesn't give you many mapping options. Your class design really needs to follow your database schema (table-per-class) otherwise it will fight with you every step of the way. Another thing I don't like about L2S is the need to use specific types (EntitySet and EntityRef) to handle collections, references and lazy-loading. This means it's not possible to keep your domain model ORM agnostic without adding another layer of abstraction.

My other issue with L2S is the sole reliance on LINQ to generate queries. The LINQ provider is very well written and generally creates decent SQL for the majority of queries but I have my concerns that there are more complex queries that can't be expressed well with LINQ. Using L2S you basically have to revert to calling stored procedures in these cases, whereas (for example) NHibernate has several API's (LINQ provider, QueryOver, HQL etc) that can be used when you want more control over the generated SQL.

In L2S's defence over NHibernate, there is a lot less overhead in getting it up and running on a project.

Title: Is LINQ to SQL dead?


问:
How can I deal with a team member who dislikes making comments in code?
One of my team members consistently avoids making comments in his code.

His code is not self-documenting, and other programmers have a difficult time understanding his code.

I have asked him several times to comment his code, however he just gives excuses or claims that he will do it later. His concern is that adding comments will take too much time and delay the projects.

What argument can I present to him to convince him to properly document his code?

On that note, am I wrong to focus on the code comments or is this indicative of a larger problem which should be addressed?

答:
If you have an employee who can't follow instructions, reprimand him, and make sure it's clear that it won't help his career advance. Consistency in coding style is critical for a team, and if everyone else is writing comments and this one isn't, that will hurt the coding style.

That said, you can probably help him out. In my experience, when someone protests that commenting takes too much time there is a psychological barrier such as…

He is self-conscious about his code/design choices and doesn't want to lay them out in prose. (Code reviews can be helpful to bolster someone's self-confidence as much as to tear them down.)

He works very linearly and doesn't think ahead much. Commenting is painful because it forces him to unload the immediate code he was about to write from his working memory in order to compose his intent in a different way. (If this is true, commenting becomes very important for his code quality.)

Historically people don't understand his comments.

It's important for a programmer to realize that comments are like tests: They're not just for future use – They're for the programmer himself. They force him to think differently about his approach.

None of this is a substitute for CI, tests, or code reviews. It's just one of many critical parts of coding that is, itself, not writing code.

ContentLicense: CC BY-SA 3.0


答:
To supplement the answers here, I might add "If you want it done right you have to do it yourself."

I don't mean becoming "chief code commenter", I mean becoming a role model in demonstrating what you would like this other developer to do. They say showing is more effective than telling. If you can demonstrate the benefit of quality comments, or even mentor this other developer (to the extent that he's willing) you may find more success in code comment adoption.

Similarly, at home there are some household chores I don't care to do. However those same chores happen to be my wife's "pet peeve" chores... chores that must be done for her to be happy. The same situation applies vice versa. I think you may have to accept that this other developer has different priorities than you, and will not agree with you on everything. The solution that my wife and I have found is that for those "pet peeve" chores we just have to do them ourselves, even if it means doing a little more work on our own.

Title: How can I deal with a team member who dislikes making comments in code?

Body:
One of my team members consistently avoids making comments in his code.

His code is not self-documenting, and other programmers have a difficult time understanding his code.

I have asked him several times to comment his code, however he just gives excuses or claims that he will do it later. His concern is that adding comments will take too much time and delay the projects.

What argument can I present to him to convince him to properly document his code?

On that note, am I wrong to focus on the code comments or is this indicative of a larger problem which should be addressed?


问:
How do we avoid GPL violation when modifying and releasing a program using code coverd by this license?
A friend and I have started a project using code from another project, that is covered licensed under GPL. We have distributed it freely on our website, and under its download button, we've added a direct download link to the modified source code also for free. At the about section of the application, we have credited the guys who built the original code. Does the fact that we have a different project name violate the terms of the GPL? And also, if we include the original GPLv2 notice from the original app does that help us comply with it? If not, please state exactly what we have to do to comply with the GPL.
The code we're using is an older version, released under GPLv2, and that project has been discontinued, and moved to a different one, where they're still developing. We haven't used any of their current coding, which is released under GPLv3.</p>

答:
The GNU General Public License v2 reads:

[1] You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.

[2] You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.

b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.

That means that when your project is based on GPLv2 software, it also has to be released under GPLv2.

For that reason the GPL is often criticized for being a "viral" license - using GPL code in a project "infects" it with the GPL and prohibits you from releasing it under a different license.

To do so you have to:

Make sure the GPL in text form is included in the distribution of the program and make clear that these license conditions apply to your program

Leave any copyright or warranty notices of the other authors intact

Publish the sourcecode

Add a change date as a comment to each source file you edit


答:
You avoid a GPL violation by simply adhering to the GPL license terms. From what you describe (your source is available, license terms are still GPLv2, source acknowledged) you've done enough.

You don't need to include the original GPLv2 notice; your own version is sufficient. However, you do need to acknowledge the copyright of the initial contributors.

Using a new project name is no violation of the GPL. It's in fact the norm for forks of OSS projects, and might be required under trademark law.

Title: How do we avoid GPL violation when modifying and releasing a program using code coverd by this license?

Body:
A friend and I have started a project using code from another project, that is covered licensed under GPL. We have distributed it freely on our website, and under its download button, we've added a direct download link to the modified source code also for free. At the about section of the application, we have credited the guys who built the original code. Does the fact that we have a different project name violate the terms of the GPL? And also, if we include the original GPLv2 notice from the original app does that help us comply with it? If not, please state exactly what we have to do to comply with the GPL.
The code we're using is an older version, released under GPLv2, and that project has been discontinued, and moved to a different one, where they're still developing. We haven't used any of their current coding, which is released under GPLv3.</p>


问:
Fast compression in C++ and decompression in C#

Overview

I am working on a client-server application. The client is written in C++ (working on Windows, planning to support Linux) and the server is a .NET RESTful service. I need to HTTP POST some data to the server. The data is a unicode string that I need to compress using any fast compression algorithm (needs to be light on CPU). On the server I need to decompress raw bytes and get a string.

Problem

I cannot decompress raw bytes and I end up with decompressor's output buffers stay intact.

I tried

I have tried using Google Snappy, there is only a C/C++ version and any .NET ports don't appear to be finished. I also checked LZ4, where compression/decompression works in a single language, but when I try to use both - I cannot decompress data correctly (the decompressed bytes are set to 0s).

Question

Has anyone tried using a fast C/C++ compression and C# decompression? Any recommendations?

Client application shall not use more than 5% of CPU - that's a vague requirement I have. I plan to try gzip and maybe deflate, but I am not sure if I can configure compression levels there or whether it will work in both C/C++ and C#. Client collects some near real time data into a small buffer, when that buffer gets full it shall be compressed and POSTed. The whole OS process shall take less than 5% of the machine's CPU. A buffer is roughly posted 2 times a second which creates a traffic of about 2Kb/sec.

答:
You must develop a program that will run in the console. Your program will be called "TP2.exe" and
has three parameters:

the name of an input file,

a boolean (true or false) indicating whether you want to compress
the input file or unpack.

the name of the output file (the result will be written to this
file.)

For example, if you run the program with the following command in the console:
TP2.exe test.txt true test2.txt
Your program will read the file test.txt as input and writes the compressed file test2.txt output.
Another example: if you run the program with the following command in the console:

```<code>TP2.exe test2.txt false test.txt
</code>```

Your program will read the file and write test2.txt the decompressed file test.txt output. Your program should use the method of compression / decompression simply discussed in the course is based on the use of a self-organized list.

An example file uncompressed and compressed file example is provided as an example of CLIC. For the work is simple to make, you can assume that the sentences are already cut into words and that there is a single word
per line.

Finally, at the implementation level, it is recommended to use a linked list to list the self-organized because it would be more efficient. A good idea would be to use a linked list implementation of the STL library.

Body:
You must develop a program that will run in the console. Your program will be called "TP2.exe" and
has three parameters:

the name of an input file,

a boolean (true or false) indicating whether you want to compress
the input file or unpack.

the name of the output file (the result will be written to this
file.)

For example, if you run the program with the following command in the console:
TP2.exe test.txt true test2.txt
Your program will read the file test.txt as input and writes the compressed file test2.txt output.
Another example: if you run the program with the following command in the console:

TP2.exe test2.txt false test.txt

Your program will read the file and write test2.txt the decompressed file test.txt output. Your program should use the method of compression / decompression simply discussed in the course is based on the use of a self-organized list.

An example file uncompressed and compressed file example is provided as an example of CLIC. For the work is simple to make, you can assume that the sentences are already cut into words and that there is a single word
per line.

Finally, at the implementation level, it is recommended to use a linked list to list the self-organized because it would be more efficient. A good idea would be to use a linked list implementation of the STL library.


问:
What the right pattern to Use here
scenario:

I have an entity called Member. Members fall into multiple types. Some types are below.

Supporter

Volunteer

Sponsor

Player

I can create class for each type and inherit from the base Member entity. But when a Member has more than 1 type in a given time, it is not the right way.

can I use decorator pattern to achieve this intent? Or what the best pattern to get this work?

EDIT :

Language I use is C#

Also different Member types can have additional methods, for example, Sponsor can have its own methods as Donate(), Or the Volunteer can have a method Subscribe() and so on. these thing have to be considered.

答:
I would definitely not use a decorator pattern, because I can hardly see how it corresponds to the domain model.

But what is the domain? It sounds like it is a list of members in a sports club or similar. Why do you track which types of members? Is it purely for keeping the information in a member database, or do you actually use that information in some kind of calculation?

If you are not actually using the information, then you don't need some kind of polymorphic approach. You should simple create Boolean properties on the Member class, IsSupporter, IsVolunteer, etc.

However, if you actually use this for something, you might need a polymorphic approach. I think that the fact that a member can be of several types indicate that there is a hidden domain concept, such as a Role.

A Member should then have multiple roles. A Member method, whose implementation would depend on the role, should probably be implemented by making a similar call to all the roles in the member.

But more information on the domain could lead to a better answer.

Title: What the right pattern to Use here


问:
Avoid DD anomalies
I have this problem called out by PMD (static code analyzer) more often that I would like, and would like to know how someone with more experience than me would write it. My code is functional but I find it inelegant, so I want to know how other programmers would write this piece.

The case is, in a network/IO petition I may or may not get a result from, but my parent method is not null-proof so I always have to return something. I also don't like several returns on a method.

```<code>public String getBingLocation(Coordinate... data)
{
    String response = "Not Retrieved";
    final Coordinate location = data[0];
    JSONObject locationData;
    try {
        locationData = NetworkManager.getJSONResult(ApiFormatter
                .generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude));
        if (null != locationData) {
            final String address = this.getAddressFromJSONObject(locationData);
            response = address;
        }
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } finally {
        location.Street = response;
    }
    return response;
}
</code>```

Other example:

```<code>public static Object loadObject(final String fileName, final Context context) {
    Object object = null;
    try {
        ObjectInputStream objectInputStream = null;
        try {
            final FileInputStream fileStream = context.openFileInput(fileName);
            objectInputStream = new ObjectInputStream(fileStream);
            object = objectInputStream.readObject();
        } catch (final ClassNotFoundException catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } catch (final ClassCastException catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } catch (final Exception catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } finally {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
        }
    } catch (final IOException catchException) {
        LoggerFactory.consoleLogger().printStackTrace(catchException);
    }
    return object;
}
</code>```

答:
As for your first example, I'd write it like this :

```<code>public String getBingLocation(Coordinate... data)
{
    String response;
    final Coordinate location = data[0];
    JSONObject locationData;
    try {
        locationData = NetworkManager.getJSONResult(ApiFormatter
                .generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude));
        if (null != locationData) {
            final String address = this.getAddressFromJSONObject(locationData);
            response = address;
        } else {
            response = "Not Retrieved";
        }
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } finally {
        location.Street = response;
    }
    return response;
}
</code>```

The main idea  is to avoid overriding a value without reading it (this means one assignement is useless because never read).

A solution is to have a single return statement, and return a non initialized variable. Then go through all possible path and check that a value is always assigned, and no more than once.

Title: Avoid DD anomalies

Body:
As for your first example, I'd write it like this :

public String getBingLocation(Coordinate... data)
{
    String response;
    final Coordinate location = data[0];
    JSONObject locationData;
    try {
        locationData = NetworkManager.getJSONResult(ApiFormatter
                .generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude));
        if (null != locationData) {
            final String address = this.getAddressFromJSONObject(locationData);
            response = address;
        } else {
            response = "Not Retrieved";
        }
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        response = "Not Retrieved";
    } finally {
        location.Street = response;
    }
    return response;
}

The main idea  is to avoid overriding a value without reading it (this means one assignement is useless because never read).

A solution is to have a single return statement, and return a non initialized variable. Then go through all possible path and check that a value is always assigned, and no more than once.


答:
am I wrong to focus on the code comments or is this indicative of a bigger problem that should be addressed?

Somewhat. Great code doesn't need comments. However as you said, his code is not self-documenting. So I would not focus on the comments. You should focus on improving the skill and craftsmanship of your developers.

So how to do that? Doc Brown's suggestions about reviews/refactoring sessions is a good idea. I find pair programming even more effective, but it may also be considerably more difficult to implement.


问:
How important is it to reduce the number of lines in code?
I am a Software developer who works on J2SE (core java).

Often during our code reviews we are asked to reduce the number of lines in our code.

It's not about removing redundant code, it's about following a style that focuses on doing the same things with fewer lines in the code, while I believe in having clarity in code even if it means increasing the number of lines.

What do you think is the right way of doing things?

If LOC (lines of code) is a small number, how does it affect the code?
If LOC is a larger number, how does it affect the code?

example from the website : "javaranch"  -

```<code>public static void happyBirthday(int age)
{
    if ((age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0))))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
</code>```

VS

```<code>public static void happyBirthday(int age)
{

    boolean sweet_sixteen = (age == 16);
    boolean majority = (age == 21);
    boolean adult = (age > 21);
    boolean decade = (age % 10) == 0;
    boolean quarter = (age % 25) == 0;

    if (sweet_sixteen || majority || (adult && (decade || quarter)))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
</code>```

答:
I think fewer lines of code = more readable code

But of course, there is some limit, when you start to minify/obscure your code just to get fewer lines.

```<code>/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
    var num = number+"";
    while(num.length < digits){
        num='0'+num;
    }
    return num;
}
</code>```

This is minification the logic remains the same, just less readable. This shouldn't be done by humans, this minification is done by machine to be read by a machine.

```<code>function zP(e,t){var n=e+"";while(n.length<t){n="0"+n}return n}
</code>```

If you can remove some piece of code, and the algorithm still doing what it is supposed to do, ok go ahead. Just don't minify your code, there are better tools for doing that.

Body:
I think fewer lines of code = more readable code

But of course, there is some limit, when you start to minify/obscure your code just to get fewer lines.

/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
    var num = number+"";
    while(num.length < digits){
        num='0'+num;
    }
    return num;
}

This is minification the logic remains the same, just less readable. This shouldn't be done by humans, this minification is done by machine to be read by a machine.

function zP(e,t){var n=e+"";while(n.length<t){n="0"+n}return n}

If you can remove some piece of code, and the algorithm still doing what it is supposed to do, ok go ahead. Just don't minify your code, there are better tools for doing that.


问:
Why is reverse debugging rarely used?
gdb implemented support for reverse debugging in 2009 (with gdb 7.0). I never heard about it until 2012. Now I find it extremely useful for certain types of debugging problems. I wished that I heard of it before.

Correct me if I'm wrong but my impression is that the technique is still rarely used and most people don't know that it exists. Why?

Do you know of any programming communities where the use of reverse debugging is common?

Background information:

Stackoverflow: How does reverse debugging work?

gdb uses the term "reverse debugging" but other vendors use other terms for identical or similar techniques:

Microsoft calls it IntelliTrace or "Historical Debugging"

There's a Java reverse debugger called Omniscient Debugger, though it probably no longer works in Java 6

There are other Java reverse debuggers

OCaml's debugger (ocamldebug) calls it time travel

答:
I think it is important to expand a little further on this "reverse" or "historic" debugging. I think to understand complex systems and behavior in those, to replay "events" which make state explicit is absolutely crucial.

What I want to express is that you are not alone in wondering why this technique is not so much applied today or why the related problems are rarely discussed clearly.

So let’s emphasize two very important concepts here:

1.To understand a programming system it is helpful to make state explicit

2.To even further understand a programming system replaying sequences of state (events) can help a lot.

Here are some sources which tackled the problem and proposed or designed solutions for the problem (dealing with state in complex systems):

-Out of the tar bit, paper: http://shaffner.us/cs/papers/tarpit.pdf
Main ideas: avoid, isolate or make state explicit

-CQRS
http://www.cqrs.nu/
This is a combination of two concepts: Command Query Segregation and Event Sourcing. There exists different implementations ( Java,C# , Scala).
The replaying of Tate sequences and the evolving of a domain model are the crucial parts here.

If you really zoom out and see the very broad picture you can already see that with the "rise" of functional programming people are already ((un)consciously ) attracted to fp because it makes state explicit!
But that only deal with point one, to address the second one you need another concept which could be "loosely" described as functional reactive programming.

So you might say all well and good but who actually uses CQRS and FRP? I would say (IMO because I don’t have concrete numbers)   actually a lot of companies its just that they don’t know the work they do has this terminology.  Maybe you google a bit around and you hear from enterprises which use CQRS, there are some success stories already out there.
FRP too is rising slowly as an example I could give Netflix: http://techblog.netflix.com/2013/02/rxjava-netflix-api.html
Which just released an implementation of RX which is actually .NET based (but has a Javascript implementation too). So People are using these techniques today already, IN THE LARGE to understand complex systems and to make them even better. That is why they use reverse debugging techniques.

Title: Why is reverse debugging rarely used?


答: I'm surprised no one has mentioned code reviews yet. Do code reviews! When he has a check in of bad quality don't just say "add comments". Constantly ask questions and get him to tell you what his code does and why. Take notes. Then, at the end of the code review give him a copy of the notes and tell him to make your questions fairly obvious. Either by more comments or by just refactoring his code to make it better quality (preferably the latter when possible)</p>


问:
What's the progress on Haskell records?
Recently I stumbled once again on the issues of Haskell's records, in particular the uniqueness of field names. (It's a pain...)

I already read A proposal for records in Haskell from SPJ and Greg Morrisett, but its last update was in 2003.

Another paper called Lightweight Extensible Records for Haskell from SPJ and Mark Jones is even older: It's from a Haskell workshop in 1999.

Now I'm wondering if the process of giving Haskell new records made any progress.

Does anybody know something about it or can anybody point me to some further reading?

答:
My two pennies.

Believe it or not, Haskell is too much used to allow a breaking change with existing software. And it's difficult to add records withoud breaking an important part of the language.

UPDATE: BTW, I think that records are a good new feature. I like the most, not having members names polluting global namespace.

Title: What's the progress on Haskell records?


答:
I currently work as a senior applications developer and project business analyst for a major company and never has the line count of my development been a center of interest. However, I believe that the more condensed a code can be, the better, BUT not at the cost of being able to quickly analyze and correct (or add on to) it. To me, when you are in charge of business critical application that MUST have a vast level of scalability and capable of on the fly alterations in a non-stop changing environment, concise, easy to read code is one of the most important elements in development. To the credit of Erik Dietrich's reply, this :

```<code>void someMethod() {
someobject.doSomething(someSingleton.getInstance().with().a().lot().of().law().of().demeter().violations()).and().if().that().werent().enough().theres().more();
}
</code>```

would be completely unacceptable to me, however, I found altering all the companies existing code from :

```<code>if (boolean == true){
value.prop = option1;
}
else{
value.prop = option2;
}
</code>```

to:

```<code>value.prop =  boolean ? option1 : option2;
</code>```

was an excellent code condensing choice that doesn't sacrifice readability.

As far as how it effects the code? I have never noticed a performance increase or decrease from, let's say, 100 lines of code. Simple fact is that it's more the process you utilize to arrive at the final product than the number of lines it takes to arrive there. I have seen some processes written very condensed, however inefficient, perform differently than longer codes with better code flow.

Title: How important is it to reduce the number of lines in code?

Body:
I am a Software developer who works on J2SE (core java).

Often during our code reviews we are asked to reduce the number of lines in our code.

It's not about removing redundant code, it's about following a style that focuses on doing the same things with fewer lines in the code, while I believe in having clarity in code even if it means increasing the number of lines.

What do you think is the right way of doing things?

If LOC (lines of code) is a small number, how does it affect the code?
If LOC is a larger number, how does it affect the code?

example from the website : "javaranch"  -

```<code>public static void happyBirthday(int age)
{
    if ((age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0))))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
</code>```

VS

```<code>public static void happyBirthday(int age)
{

    boolean sweet_sixteen = (age == 16);
    boolean majority = (age == 21);
    boolean adult = (age > 21);
    boolean decade = (age % 10) == 0;
    boolean quarter = (age % 25) == 0;

    if (sweet_sixteen || majority || (adult && (decade || quarter)))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
</code>```

Body:
I currently work as a senior applications developer and project business analyst for a major company and never has the line count of my development been a center of interest. However, I believe that the more condensed a code can be, the better, BUT not at the cost of being able to quickly analyze and correct (or add on to) it. To me, when you are in charge of business critical application that MUST have a vast level of scalability and capable of on the fly alterations in a non-stop changing environment, concise, easy to read code is one of the most important elements in development. To the credit of Erik Dietrich's reply, this :

void someMethod() {
someobject.doSomething(someSingleton.getInstance().with().a().lot().of().law().of().demeter().violations()).and().if().that().werent().enough().theres().more();
}

would be completely unacceptable to me, however, I found altering all the companies existing code from :

if (boolean == true){
value.prop = option1;
}
else{
value.prop = option2;
}

to:

value.prop =  boolean ? option1 : option2;

was an excellent code condensing choice that doesn't sacrifice readability.

As far as how it effects the code? I have never noticed a performance increase or decrease from, let's say, 100 lines of code. Simple fact is that it's more the process you utilize to arrive at the final product than the number of lines it takes to arrive there. I have seen some processes written very condensed, however inefficient, perform differently than longer codes with better code flow.


问:
3d point cloud render from x,y,z 2d array with texture
Need some direction on 3d point cloud display using OpenGL in c++ (vs2008). I am brand new to OpenGL and trying to do a 3d point cloud display with a texture. I have 3 2D arrays (each same size 1024x512) representing x,y,z of each point. I think I am on the right track with

```<code>glBegin(GL_POLYGON);
 for(int i=0; i<1024; i++)
 {
      for(int j=0; j<512; j++)
      {
            glVertex3f(x[i][j], y[i][j], z[i][j]);
      }
 }
 glEnd();
</code>```

Now this loads all the vertices in the buffer (I think) but from here I am not sure how to proceed. Or I am completely wrong here.

Then I have another 2D array (same size) that contains color data (values from 0-255) that I want to use as texture on the 3D point cloud and display.

I understand that this maybe a very basic OpenGL implementation for some but for me this is a huge learning curve. So any pointers, nudge or kick in the right direction will be appreciated.

答:
You should use a modern OpenGL approach, and forget about glBegin and glEnd. You can use this to learn it Learning Modern 3D Graphics Programming (on web archive).

First, you should put your data in a linear array, like (or something like that). Then you define the opengl buffers that point your data, and load the shader programs to paint it. And, after that your draw routine will be easy as:

```<code>glClearColor( 0.2f, 0.0f, 0.0f, 0.0f );
glClear( GL_COLOR_BUFFER_BIT );

glUseProgram( myShaderProgram );

glBindBuffer( GL_ARRAY_BUFFER, posBufferObject );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 );

glBindBuffer( GL_ARRAY_BUFFER, colBufferObject );
glVertexAttribPointer( 1, 1, GL_UNSIGNED_BYTE, GL_FALSE, 0, 0 );

glEnableVertexAttribArray( 0 );
glEnableVertexAttribArray( 1 );

glDrawArrays( GL_POINTS, 0, 1024*512 );

glDisableVertexAttribArray( 0 );
glDisableVertexAttribArray( 1 );
glUseProgram( 0 );
</code>```

The link shows everything you need. Your example code is deprecated, and using buffers and shaders is more efficient.

Body:
You should use a modern OpenGL approach, and forget about glBegin and glEnd. You can use this to learn it Learning Modern 3D Graphics Programming (on web archive).

First, you should put your data in a linear array, like (or something like that). Then you define the opengl buffers that point your data, and load the shader programs to paint it. And, after that your draw routine will be easy as:

glClearColor( 0.2f, 0.0f, 0.0f, 0.0f );
glClear( GL_COLOR_BUFFER_BIT );

glUseProgram( myShaderProgram );

glBindBuffer( GL_ARRAY_BUFFER, posBufferObject );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 );

glBindBuffer( GL_ARRAY_BUFFER, colBufferObject );
glVertexAttribPointer( 1, 1, GL_UNSIGNED_BYTE, GL_FALSE, 0, 0 );

glEnableVertexAttribArray( 0 );
glEnableVertexAttribArray( 1 );

glDrawArrays( GL_POINTS, 0, 1024*512 );

glDisableVertexAttribArray( 0 );
glDisableVertexAttribArray( 1 );
glUseProgram( 0 );

The link shows everything you need. Your example code is deprecated, and using buffers and shaders is more efficient.

ContentLicense: CC BY-SA 4.0


答:
Does this programmer do some code maintenance. If not, he should: check for any disliked project you have around and assign its maintenance to him.

Usually those are the badly documented projects where you lose hours trying to understand what is going on to correct what could have been easy to correct.
If this kind of experience does not make him want up to date, correct and useful documentation nothing will.


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

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

答:
I've seen a couple of horrible outsourcing projects that succeeded in significantly increasing costs while either failing to increase or actually reducing efficiency.

In the worst case the new outsource team were put in place and up skilled but the existing on-shore team remained in place because the outsource team weren't trusted to actually do any of the critical work.

At this point the logical thing to do would obviously have been to accept failure and shut down the outsource team but because management weren't willing to publicly admit that it hadn't worked both teams were left in place (at a significant increase in cost with no increase in efficiency or usable capacity) until the whole thing could be buried.

In another instance development was outsourced and the original team laid off.  Two years later they realised that it hadn't worked and paid to bring the whole lot in-house again only to find that in addition to the very significant costs of another handover, the impact of lost knowledge, recruitment fees, contract terminations and so on, the outsource organisation had lost a significant chunk of the source code.

(Note: I'm not saying outsourcing can't work, just that too many times people are seduced by potential savings and don't consider the realities of their new world, the change to process and working practices and so on which leads to majorly screwed projects)

ContentLicense: CC BY-SA 2.5


问:
Will Authentication over HTTPS Slow My Application?
I am building a web application and RESTful web service.

I have been reading various articles about the best way to authenticate the requests to the web service.

The best option for me seems to be to use HTTP basic authentication. Pretty much every article ive read says that authentication should be encrypted over SSL or equivalent.

Im not totally sure what this involves. Does this mean that my whole web service will have to be on a secure server? Will this slow things down?

答:
With HTTP basic authentication, the username and password the user provides is sent with every request to the server. This means they are in plain text even in areas of your site that don't necessarily need to be secure. Obviously, you'll want SSL here to keep your users safe. </p>

<p>In theory, you could use cookie authentication and only put SSL on the login page(where the username and password is sent). If your cookies are decently secure and safe against replay attacks, then an attacker wouldn't be able to do anything with them even if they did manage to get one. </p>

Body:
With HTTP basic authentication, the username and password the user provides is sent with every request to the server. This means they are in plain text even in areas of your site that don't necessarily need to be secure. Obviously, you'll want SSL here to keep your users safe.

In theory, you could use cookie authentication and only put SSL on the login page(where the username and password is sent). If your cookies are decently secure and safe against replay attacks, then an attacker wouldn't be able to do anything with them even if they did manage to get one.


答:
HTTPS (SSL) isn't user authentication FYI.  It just provides encryption between 2 endpoints.

But yes, there is a teeny tiny bit of overhead from it (though not enough to warrant a change in plans/hardware).  See here :

https://stackoverflow.com/questions/548029/how-much-overhead-does-ssl-impose

Title: Will Authentication over HTTPS Slow My Application?

Body:
I am building a web application and RESTful web service.

I have been reading various articles about the best way to authenticate the requests to the web service.

The best option for me seems to be to use HTTP basic authentication. Pretty much every article ive read says that authentication should be encrypted over SSL or equivalent.

Im not totally sure what this involves. Does this mean that my whole web service will have to be on a secure server? Will this slow things down?


问:
How do I deal with a slow and undedicated colleague in the team?
I have been working on a new project. The project works like this: The end user can access a webapp using a link and he can add multiple systems on his network and manage that particular systems details. My part involves the front end and the webserver, which is done in python. My python actually communicates with another project which is entirely done in c & c++. The c/c++ project is the main app which does all the functionality. My python sends the user request to it and displays the response from it to the user.

I am very familiar with my work and I will finish it soon. Since that's not much work in it. And I am a person who loves to work. I spends most of the time in office and only go home when I feel sleepy.

The c/c++ app is managed by another colleague who has 5+ year experience and can do things much faster than me, but he never does it. May be he doesn't like to do it. His app crashes often when my python communicate with it or returns wrong values. It's full of bugs. Since my app depends on it, I am having a hard time building it. Instead of fixing the bugs, he asks me to slow down my work. He asks me to tell manager that my work needs a lot of time. He is asking me to fool the manager and even forcing me to work slowly like him.

During project meeting, when manager asks him about the bugs he says that he fixed everything and it works fine. Since he is my colleague, I couldn't tell anything to the manager. I obviously need to have a good relationship with my colleagues more than my manager, since most of the time we will be with our colleagues, not with the manager.

I am not able to tell the manager anything regarding this, since if manager asks him why, then he may think I complained about him to the manager. And he keeps on lying in the meeting. And since he fixes the bug slowly, it even slows down my work. Now I thought of working on the front-end part of my app  and finishing it off so that in the mean time he can make his project stable. Now he is asking me to tell the manager that my front end part require a lot of work and I may need more and more time, simply so that he can drag the project down. And the sad thing is our actual manager has gone to the US, so we have a temporary manager and this guy doesn't know about the project much, so the c,c++ just fools him.

Can anyone suggest me how I deal with this?
I wanted to finish off the project soon. How can I make him work even by maintaining a good relationship with him?

Responses to comments:

If he's really deliberately misleading the company, you should report him to management.

I am new to this company and the other guy has been there for many years. And I have just started knowing my colleagues. If I directly go and complaint him, I don't think so I can make good relationship with my other colleagues. Even he has the power to mislead them. I am not telling he is a bad guy, he can do the work, but he is not doing it.

Doesn't your company have any kind of bug tracking system ?

Here actual bug tracking system isn't there. The company tries to finish off the project as soon as possible and gives it to the QA. And then fixes the bugs reported by QA.

This is why companies should give employees stock / options or some sort of ownership. That way you can literally tell the guy "You are costing me monetary growth... don't you want to make money also?".

The company has the stock options they have given me a 2500 share, mostly he too would have got some more.

Seniority does deserve some benefit of a doubt. You really need to speak to him first and try to understand the problem. He may be out of his depth, you may be able to help him, there could easily be variables you are unaware of. It may be hard now, but you could easily make the situation a lot worse by jumping the gun.

I even does it, first his app wasn't handling multiple requests at a time, he was using a queue to handle the requests I sent to him. I even suggested to him some of my ideas on it. He said he already had these ideas, and will be executing them. His explanations was: "Everything require certain time to do and this is a project which may need two years to complete and we are asked to finish it in two months". I used to have a hard time coding during first few weeks because of this bug. But now he fixed it. But he is using a single queue for a user requests and that is now slowing down the app, since it processes one request at a time.

What is QA doing this whole time? Why aren't they reporting/confirming the status of the project(s)?

The manager is the person who decides when to give to the QA. As of now it has not yet given to QA. He said we should give it by this month end.

答:
Showing initiative by requesting additional tasks and asking how you can add value to the organization is the best way to earn trust.

Your manager might not be technical enough to figure out who is slowing down the project, but they are probably smart enough to recognize that a developer who is actively seeking out new tasking is breezing through their current tasking. This will lead to a conversation where you can make it clear that you are waiting on bug fixes from others on your current tasking. Frame the discussion in terms of how you can add additional value to the organization by efficiently using your free time, not how your colleague is being too slow with his bug fixes.


问:
Velocity does not plateau over time, why?
I have plotted my team burn up chart and its velocity per iteration. To me it looks really bad (velocity fluctuates a lot). What should I be looking for to diagnose the root cause of this behaviour?

答:
For your question, it's hard to tell why it has fluctuation because it might be because of story card, people in the team, or product owner capability. So, in my experience, the velocity will be fluctuated because, for example:

Your team member might not be dedicated team members. To work and
understand each other, they need to work together long enough. If your team
swap people in the team in/out often, this make dynamic in the team and also affect velocity.

Story cards are too big. So, team can't go in detail as much as they can in planning/estimation. They will find during the sprint that something is harder than they think.

I guess you are doing scrum. In scrum, we have to do sprint planning part 1 (Product owner choose what to do) and sprint planning part 2 (Team decides how much they can do). So, the situation might be, after product owner choose the cards to the sprint, team doesn't go in detail deep enough in sprint planning part 2 so they can't find the hidden problem that they need to let Product owner knows. If they found the problems at first, they will break them OR think about how to get rid of the risk. This make the estimation to be correct enough before start working on the sprint.

If the story cards are not in detail, estimation will not be accurate. The estimation at first can be a rough one but before start the sprint or before the story cards go to the sprint, they need to be splited and clarified enough to get almost correct estimation. This helps velocity of team to be more stable.

Product owner might not be able to clarify story cards clear enough before start working on sprint. This is also really important thing because this is the goal for the team to work in this 2 weeks. If product owner just choose the card to the sprint and team don't understand it yet, they anyway need to understand them during sprint and the answer might turn out that it has more than they discussed and the estimation is wrong. So, this clearly affects velocity.

etc...

Anyway, in my opinion, I don't think the fluctuation of velocity is important as long as we know what the situation on each sprint. Velocity is just a thing to tell you how stable your team can work. If it's not stable, we have to find out in detail of each sprint about "what happened". This is just a way to clarify/make the problem happen so we are able to fix it. So, velocity just tell us what was going on in that sprint to we can think back and improve to make it stable. Velocity is a projection of the project. And the fluctuation of velocity doesn't mean team can't deliver product, it just helps you think about the projection in the future and what are the problems to solve to make everything smooth.


答:
Basic authentication is setting a username and password in the header of the http request. If you don't use SSL or equivalent then that username and password is sent in plain text and is trivial for anyone to steal.

Most web servers support HTTPS out of the box nowadays and although it does add overhead to every call that overhead is minimal.

You could secure some endpoints and not others (ie have an authenticate endpoint that produces a token that can be used for other calls). I would strongly recommend SSL for the whole service though as its much more secure. (if nothing else it stops sensitive data being intercepted)


问:
Hourly or per project billing?
How do you bill your programming projects? Do you do it per hour? Per job?

Please include what kind of project you are doing in the answer. (Mobile, Web, Desktop, etc... You can be more specific if you want.)

BONUS:

If you'd like to give specific amounts in your answer, you may. ;-)

答:
We all know that hourly billing would be better (for non-trivial projects), but it is very hard to have it accepted by the customer.

So you should do a high degree planning and scheduling along with the customer, so he will know that you're not trying to cheat him. You could also try to agree on compensations if the project takes more time that planned in spite of the high quality scheduling (it should be clear at this point the value of a good scheduling, shared with the customer). Don't forget to plan also risk management.

If you do so you chances to have an hourly billing would be higher, but if you really don't want to cheat on the customer on the hours you spend on his project, it would become not much better than per-project billing...

Title: Hourly or per project billing?


问:
JUnit Testing in Multithread Application
This is a problem me and my team faces in almost all of the projects. Testing certain parts of the application with JUnit is not easy and you need to start early and to stick to it, but that's not the question I'm asking. The actual problem is that with n-Threads, locking, possible exceptions within the threads and shared objects the task of testing is not as simple as testing the class, but testing them under endless possible situations within threading.

To be more precise, let me tell you about the design of one of our applications:

When a user makes a request several threads are started that each analyse a part of the data to complete the analysis, these threads run a certain time depending on the size of the chunk of data (which are endless and of uncertain quality) to analyse, or they may fail if the data was insufficient/lacking quality. After each completed its analysis they call upon a handler which decides after each thread terminates if the collected analysis-data is sufficient to deliver an answer to the request.

All of these analysers share certain parts of the applications (some parts because the instances are very big and only a certain number can be loaded into memory and those instances are reusable, some parts because they have a standing connection, where connecting takes time, ex.gr. sql connections) so locking is very common (done with reentrant-locks). While the applications runs very efficient and fast, it's not very easy to test it under real-world conditions.

What we do right now is test each class and it's predefined conditions, but there are no automated tests for interlocking and synchronization, which in my opionion is not very good for quality insurances.

Given this example how would you handle testing the threading, interlocking and synchronization?

答:
Sounds like you're doing integration testing not unit testing

In general, when you unit test you split the code into its smallest parts and test each one in isolation. Sometimes, you need to emulate dependencies - a process called mocking. Good mocking libraries include JMockit (for mocking absolutely anything including making String mutable) or Mockito if your needs are normal.

These days multithreaded applications in Java should be built upon the java.util.concurrent packages and have ExecutorService at their heart. Unless your needs are very specific there is no real requirement to access Thread directly any more.

Given a design based on the concurrency packages you should be able to decompose your analysis and construct isolated unit tests for them. This approach should greatly simplify your code, and make the behaviour of threads a lot more predictable than it currently sounds.


答:
I'm going to state what most of the answers and comments hint at: you probably need to figure out the real issue here rather than trying to push your perceived solution through.

You are motivated to see comments in his code; why?  You gave a reason; why is that reason so important to you?  He is more motivated to do something else instead; why?  He'll give a reason; why is that reason so important to him?  Repeat this until you arrive at the level where the conflict really arises, and try to find a solution there that both of you can live with.  I'll bet it has very little to do with commenting.


问:
Java labels. To be or not to be
Before I start this question I know the java 'goto' is a big no go.

So I've been writing a program and I have some indented Loops and statements and I need to BREAK multiple on command. Rather than having a load of boolean variables and if(!<booleanName>) BREAK; statements throughout these loops and statements what is everyone's opinions on using labels to break them using the BREAK  statement?

e.g.

```<code> for(...) {

      indented_example_loops:     // Label name
           for(...) {
                for(...) {
                     if(match) break indented_example_loops;
                     // ^ Break statement to break the 2 for loops at once
                }
           }

 }
</code>```

Perfectly okay? Okay to do occasionally? Completely avoid? or should i go to a corner and call the Devil to take my soul?

答:
Separate the iteration and the processing by encapsulating the iteration.

Iterating over multi-level structures with nested loops leads to applications where most of the code is looping noise.  To process all the Level2Things in a Level0Thing, replace your nested loops with this:

```<code>for (Level2Thing t2: topThing.level2Things()) {
   // do something
}
</code>```

where level2Things() returns an Iterable<Level2Thing>.

You can find some sample code for encapsulating nested iterations here.

Title: Java labels. To be or not to be

Body:
Separate the iteration and the processing by encapsulating the iteration.

Iterating over multi-level structures with nested loops leads to applications where most of the code is looping noise.  To process all the Level2Things in a Level0Thing, replace your nested loops with this:

for (Level2Thing t2: topThing.level2Things()) {
   // do something
}

where level2Things() returns an Iterable<Level2Thing>.

You can find some sample code for encapsulating nested iterations here.


问:
Why is NoSQL better for this scenario?
Hypothetical scenario: Let's say we are downloading JSON from Facebook with details of a user's friend's checkins, posts, etc... These come in as one document per friend per activity, so with 8 activities a user with 300 friends will cause our system to make 2400 requests to Facebook, downloading 2400 JSON documents.

Let's say we want to merge these 2400 documents together, sort the activities by date_created descending and then page through them in a sort of pseudo newsfeed. Please do not comment on the wisdom of recreating a facebook newsfeed in this way.

Let's also suppose that we want to re-download all of this data whenever we are notified that it has changed by Facebook. (FB has an update service you can subscribe to for users of your app). For argument sake let's assume all of the data has to be refreshed every 5 minutes, and further assume we want to be able to support 1000 simultaneous users, and that the average JSON document size is 25kb.

I am curious as to how NoSQL techniques would be better than parsing the JSON on ingestion into a relational database? To me it seems like map/reduce are just synonyms for parse/aggregate and that both approaches will require the same thing to occur. What advantages would I get from using NoSQL?

答:
What advantages would I get from using NoSQL?

NoSQL will scale better as the number of users grows.

Traditional RDBMS don't really scale well. All that you can do is throw bigger machines at the problem. They aren't really suited for distributed systems (cloud e.g.).

NoSQL is (under given circumstances) better at handling hierarchical structures like documents/JSON.

The key point to understand is that these storage mechanisms are key-value based and thus can retrieved data that is stored together very fast, as opposed to data that is "merely related" (what RDBMS were built for).

In your case that would mean, that you can easily retrieve all records for a certain user very fast for example. In traditional relational databases you would either have to denormalize your schema for performance or keep the schema clean but potentially suffer performance penalties caused by joins or heavy aggregations.

Look at it this way: Why is a hash map (key value store) fast? You can retrieve items from a hashmap in almost O(1) as the hash directly translates to a memory address (simplified). Looking up a binary index in contrast to that would yield O(log(n));

For your case, MongoDB or CouchDB might be good solutions, as it's already based on JSON.

In my opinion, using a NoSQL solution here is a good choice. You want to retrieve all the activities of a user as a feed. If they're properly written to your data storage, then NoSQL should, in theory, excell at this, without the need for joining anything or worrying about proper indexes. @Earlz also mentioned that you have no ACID guarantee for NoSQL databases. This makes NoSQL fast and you probably don't need ACID properties for your application. Give it a try!

Moreover, there's a good article from Martin Fowler on the subject. He's made a nice diagram that I really like:

Go check out his pages to read some deep thoughts about NoSQL.

Title: Why is NoSQL better for this scenario?


答:
Jeff Atwood wrote a brief blogpost not so long ago about whether full encryption is the way to go. He describes some real-world examples and has a few lines on performance considerations too.

Also, he references this article about a Gmail case study, quoting the following:

In January this year (2010), Gmail switched to using HTTPS for everything by default. Previously it had been introduced as an option, but now all of our users use HTTPS to secure their email between their browsers and Google, all the time. In order to do this we had to deploy no additional machines and no special hardware. On our production frontend machines, SSL/TLS accounts for less than 1% of the CPU load, less than 10KB of memory per connection and less than 2% of network overhead. Many people believe that SSL takes a lot of CPU time and we hope the above numbers (public for the first time) will help to dispel that.

He also mentions some then-recent improvements to client-side caching of pages through HTTPS by the browser.

Despite this, he points out, there are other penalties, most of them being not performance but implementation costs:

Maintaining software quality while adding additional complexity for already busy teams,

Proxy caching is much harder to configure properly and needs code changes too,

It's hard to get security right for a mashup of content from different sources,

Low-end mobile devices might struggle with encryption.


答: I don't think fewer lines of code == more readable code. However, the reality, which is very different from the theory, is that the code with large number of lines are often written without a proper design. Consequently, requirement of fewer lines MAY force some programmers to come up with better design if they are capable. The twist is that many programmers are not, then the requirement does not help much.</p>


问:
RESTful Design: Multiple Relationships Between the Same 2 Entities
I am in the process of designing RESTful web services and got stuck at one point. The design is very simple with 3 entities:

```<code>- Project
- Status
- Employee
</code>```

The part I am having trouble with is capturing the relationships:

```<code>- A project has a current status (1 to 1 between Project and Status).
- A project has multiple 'possible subsequent status' (1 to many between Project and Status).
</code>```

The Visual Studio designer does not allow these two different relationships to be defined between these two entities. I am aware that it is just a modelling tool but at the same time, I am willing to know if this is the right approach.

Also, with this design, I am not sure how to access the Status entities using these two relationships.

```<code>http://serviceRootURL/Project(2)?$expand=Status // For current status
http://serviceRootURL/Project(2)?$expand=SubsequentStatus // For subsequent status
</code>```

Is it possible to use arbitrary relationship names with the expand keyword?

(The question probably touches OData a little bit as well since I am trying to make my library OData-compliant.)

答:
Do the current 'possible subsequent status' only depend on the current project status?

If yes then you could also model the possible status values as an entity with 1 occurence per status value. This would cause a change in the relationship between project and status to n:1 (a status can have any number of projects).

Add another recursive relationship "possible subsequent status" from status to status with a cardinality of 1:n.

Nice side effect of this is that you can easily list the projects with a particular status by starting with the status and following the relationship to the projects :-)

Don't know how well this can be modeled in VS or expressed in REST, sorry. But that would seem like a good model to me.


答:
Part of the problem is your functions have more than one responsibility.  They are both getting a result and handling errors.  You're also getting unnecessarily hung up trying to avoid multiple return points, which is a vestigial practice from C programming where it can cause memory leaks.  You should use multiple returns if it clarifies your code, especially in short functions.  I'm also guessing that your logging code is getting repeated all over the place.  If you separate those concerns and try to avoid repeating yourself, you get something like this:

```<code>public JSONObject getLoggedJSONResult(String api)
{
    try {
        return NetworkManager.getJSONResult(api);
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    }

    return null;
}

public String getBingLocation(Coordinate... data)
{
    final Coordinate location = data[0];

    JSONObject locationData = getLoggedJSONResult(
       ApiFormatter.generateBingMapsReverseGeocodingURL(
          location.Latitude, location.Longitude));

    if (null == locationData) {
        return "Not Retrieved";
    } else {
        return this.getAddressFromJSONObject(locationData);
    }
}
</code>```

As a general principle, most DD anomalies can be fixed by splitting the function.  It's mostly a matter of figuring out where to split it.

Your second example is trickier.  That sort of situation is why try-with-resources statements were invented.  You can use an early return to eliminate the DD anomaly on object, but you're not going to be able to do much about objectInputStream without a try-with-resources.

Title: Avoid DD anomalies

Body:
I have this problem called out by PMD (static code analyzer) more often that I would like, and would like to know how someone with more experience than me would write it. My code is functional but I find it inelegant, so I want to know how other programmers would write this piece.

The case is, in a network/IO petition I may or may not get a result from, but my parent method is not null-proof so I always have to return something. I also don't like several returns on a method.

```<code>public String getBingLocation(Coordinate... data)
{
    String response = "Not Retrieved";
    final Coordinate location = data[0];
    JSONObject locationData;
    try {
        locationData = NetworkManager.getJSONResult(ApiFormatter
                .generateBingMapsReverseGeocodingURL(location.Latitude, location.Longitude));
        if (null != locationData) {
            final String address = this.getAddressFromJSONObject(locationData);
            response = address;
        }
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
        return response;
    } finally {
        location.Street = response;
    }
    return response;
}
</code>```

Other example:

```<code>public static Object loadObject(final String fileName, final Context context) {
    Object object = null;
    try {
        ObjectInputStream objectInputStream = null;
        try {
            final FileInputStream fileStream = context.openFileInput(fileName);
            objectInputStream = new ObjectInputStream(fileStream);
            object = objectInputStream.readObject();
        } catch (final ClassNotFoundException catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } catch (final ClassCastException catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } catch (final Exception catchException) {
            LoggerFactory.consoleLogger().printStackTrace(catchException);
        } finally {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
        }
    } catch (final IOException catchException) {
        LoggerFactory.consoleLogger().printStackTrace(catchException);
    }
    return object;
}
</code>```

Body:
Part of the problem is your functions have more than one responsibility.  They are both getting a result and handling errors.  You're also getting unnecessarily hung up trying to avoid multiple return points, which is a vestigial practice from C programming where it can cause memory leaks.  You should use multiple returns if it clarifies your code, especially in short functions.  I'm also guessing that your logging code is getting repeated all over the place.  If you separate those concerns and try to avoid repeating yourself, you get something like this:

public JSONObject getLoggedJSONResult(String api)
{
    try {
        return NetworkManager.getJSONResult(api);
    } catch (final ClientProtocolException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    } catch (final JSONException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    } catch (final IOException e) {
        LoggerFactory.consoleLogger().printStackTrace(e);
    }

    return null;
}

public String getBingLocation(Coordinate... data)
{
    final Coordinate location = data[0];

    JSONObject locationData = getLoggedJSONResult(
       ApiFormatter.generateBingMapsReverseGeocodingURL(
          location.Latitude, location.Longitude));

    if (null == locationData) {
        return "Not Retrieved";
    } else {
        return this.getAddressFromJSONObject(locationData);
    }
}

As a general principle, most DD anomalies can be fixed by splitting the function.  It's mostly a matter of figuring out where to split it.

Your second example is trickier.  That sort of situation is why try-with-resources statements were invented.  You can use an early return to eliminate the DD anomaly on object, but you're not going to be able to do much about objectInputStream without a try-with-resources.


问:
Internationalization through SQL Database and performance issues
I'm using .Net technologies and because ASP.Net "instant translation" is not really easy to do  with ResX, since it has to be compiled after every change, there are a few hacks available (http://www.onpreinit.com/2009/06/updatable-aspnet-resx-resource-provider.html), but as it is, they're hacks... and they seem to have problems.

So I decided a while ago (in 2006, before I even saw solutions like the previous link) that I was going to set all the translation into an SQL Database, and cache all the translation needed in memory for performance.

The real problem begins when I want to do joins betweens table with multiple fields that are translated. Basically what I do is to store the ID of the translation inside each field, so I can add or edit translations into languages independently.

For example (it's not real but should show the concept):

```<code>ITEM(ItemID, TranslationReference_Name, TranslationReference_Use, ...)
TRANSLATION(TranslationReference, IDLanguage, Content)
</code>```

After that as you can guess, when I want a SQL Query to contain I need to do joins
And this is where it gets dirty, because I did not find any other way to do it, and for each field of ITEM that needs a translation into a specific IDLanguage, I need to do a join.

This is bad for performance, because the TRANSLATION table contains thousands of lines. So each time I do need to do a full join for every column that needs a translation.

Plus, the other problem is that I'd like to have the basic english translation if a specific language has not been translated yet, so as you can guess it becomes much more dirty to code...

I have no idea how to improve it. Should I simply give up the database joins idea and translate each result of the database on my .Net code, refering to a dictionnary (that I already have) containing the translation, so it will require no actual joins?

And this is only a few of the drawbacks of that solution... because in real use, I need users to upload their own dynamically translated content, and manage versions of these translations.

Keep in mind that I do not want to have N rows (N being the number of languages that this record is available) for the "ITEM" table, I know I could set 1 row by language, and have its translated content in nvarchar inside it, but that's not what I want because I need the same ID for every record, independant to the language it can be translated into.

I've searched accross the web and I did not find any good article about this.

I talked to another developper that had several languages translation for his data-heavy website, if I remember well he was using multiple table for the translation, he would not store IDLanguage inside a global TRANSLATION table, but would split every translation in its own table and do something like injecting the language in the SQL code to change, something like:

```<code>SELECT Content FROM Translation_EN ...
SELECT Content FROM Translation_FR ...
</code>```

It would be sure more effective than doing a join on a full table, but that won't simplify my SQL full of joins...

So I probably have to think about alternatives and I need your ideas and comments about this.

Thank you very much.

答:
Joins are good, use joins. For them to be effective though the join fields must be indexed as well as fields you intend to use in where clauses. Foreign Keys are not indexed automatically in SQL Server and I imagine they aren't in most other dbs either. PKs are generally indexed bu only if you formally make them a PK (which of course you should do).

Thousands of records is teeny tiny for a database. Our medium sized db has around 20 million records in one of it's main tables and we don't have performance problems. And we often join to 15-20 tables.


问:
How best to merge/sort/page through tons of JSON arrays?
Here's the scenario: Say you have millions of JSON documents stored as text files. Each JSON document is an array of "activity" objects, each of which contain a "created_datetime" attribute. What is the best way to merge/sort/filter/page through these activities via a web UI? For example, say we want to take a few thousand of the documents, merge them into a gigantic array, sort the array by the "created_datetime" attribute descending and then page through it 10 activities at a time.

Also keep in mind that roughly 25% of these JSON documents are updated every day, and updates have to make it into the view within 5 minutes.

My first thought is to parse all of the documents into an RDBMS table and then it would just be a simple query such as "select top 10 name, created_datetime from Activity where user_id=12345 order by created_datetime desc".

Some have suggested I use NoSQL techniques such as hadoop or map/reduce instead. How exactly would this work?

For more background, see: Why is NoSQL better for this scenario?

答:
How to merge/sort/page through a huge amount of data?

Well, for sorting, look at Quicksort if the data is more or less randomized, or Timsort if it's highly ordered.  (Quicksort degenerates easily into horrible performance on highly ordered data.)

For merging, there's a pretty simple algorithm for this: list comparison.

Take two lists, list A and list B.  Sort both lists using the same criteria.

Declare two iterators that refer to a single list element, one for each list.  Initialize them to reference the first element of their respective lists.

Repeat

Compare referenced element A (eA) to referenced element B (eB)

If eA < eB then handle eA appropriately and increment iterator-A

else if eB < eA then eB appropriately and increment iterator-B

else handle equality case appropriately and increment both iterators

until one iterator reaches the end of its list.

(optional) Handle the remaining elements in the other list, if appropriate

This basic concept can be used for a number of operations involving two lists, including merging, by specifying the "handle appropriately" cases. In this case, the appropriate way to handle it is to add an element to the output list.

For paging, let your database engine handle this one.


答:
First of all, try to understand how SSL (HTTPS) and HTTP authentication works.

The usual HTTP authentication methods (Digest, Basic, and any forms+cookie based authentication scheme you can implement on top of HTTP) are all insecure by themselves, because they send authentication information more or less in clear text. Whether the data is in POST fields or headers, and whether base64-encoding is applied, doesn't matter at all in this regard, the password is clearly visible to anyone with access to the network traffic. This means that HTTP authentication over an untrusted channel is worthless: all it takes for an attacker to read your password is a little network sniffing.

SSL implements a secure communication channel over an inherently insecure channel. This works, roughly, as follows:

Server sends a signed certificate

Client validates certificate against a list of known-good signing keys; certificate signatures can be chained, so that each node says "if the signature that signs me is good, then so am I", but ultimately, the chain needs to resolve to one of the handful of trusted authorities preconfigured on the client.

Client uses server's public encryption key to send a shared secret

Server decrypts shared secret using private key (because only the legitimate server has the private key, other servers will be unable to decrypt the shared secret)

Client sends actual request data, encrypted using the shared secret

Server decrypts request data, then sends an encrypted response

Client decrypts response and presents it to the user.

Note a few important points here:

The certificate chain allows clients to make sure that the server they're talking to is the real one, not someone intercepting their requests. This is why you should buy a real SSL certificate, and why browsers throw scary warnings at you when you hit a site that uses an invalid, expired, or otherwise incorrect certificate: all the encryption in the world doesn't help if you're talking to the wrong person.

The public/private encryption used to exchange the secret makes sure that succesful communication will only work between this particular pair of client and server: sniffed network packets will be encrypted, and they will require the server's private key to get at the data.

Symmetric encryption is used for the bulk of the request, because it has a much lower performance overhead than private/public key encryption. The key (shared secret) is exchanged using private/public key encryption though, because that is the only way to do so in a secure way (except transporting it over a separate channel, such as a courier service).

So obviously, there is some overhead involved, but it's not as bad as you'd think - it's mostly on the scale where "throw more hardware at it" is the appropriate response, unless you're preparing for absolutely massive amounts of traffic (think Google or Facebook). Under normal circumstances, that is, typical web application usage, the SSL overhead is negligible, and consequently, as soon as you have any confidential data at all, it's best to just run everything over SSL, including resources. SSL is also the only viable way of securing HTTP traffic; other methods are simply not as standardized and thus not widely supported, and you absolutely do not want to implement these things yourself, because honestly, it's just too easy to get them wrong.

TL;DR: Yes, SSL + Basic Authentication is a good idea, yes, you need a secure server (and a valid certificate), yes, it will slow things down a bit, but no, this is not something to worry about right now.


问:
How can I understand aggregation and containment?
I'm confused between aggregation and containment. I'm wondering if the following represent an aggregation or containment?</p>

```<code>class Auto
{

   private string model;
   private int speed;

     class AutoCustomer
     {
        public string LastName;
        public string Address;
        public DateTime DateOfPurchase;
     }
}
</code>```

答:
A good litmus test for aggregation vs. composition is asking yourself if you would delete the child-object when you delete the parent-object.

When you don't need the Auto anymore, do you still need the AutoCustomer it references? When you do, you have a case of aggregation. When you don't need it, you have a case of composition.


答:
HTTP basic auth without your own session handling will probably leave you open to Cross-site request forgery attacks. You can probably use it if you couple with your own session handling, but you may have trouble providing a clean "log out" function.

No matter what you use for authentication, you will need to use HTTPS to encrypt the connection (unless the web application is only accessed on a controlled, secure network). It may slow things down a bit (connection establishments are expensive, but browsers tend to keep connections for a while), but if you want a secure application, you won't be able to avoid it anyways, so you don't really need to worry about it.

Note: "HTTPS authentication" (which you mentioned in the title) is misleading - it could refer to SSL client certificate authentication, which has little to do with the text of your question and has it's own set of benefits and problems. You probably don't want to touch that.


问:
How to dynamically add new posts once they are created
I am trying to design an application where users can make posts with Django on the backend. Right now I have to refresh the page with JavaScript every 20 or 30 seconds to check for new posts that might be available for that page. I was wondering if there are  more effective ways to do this? Maybe with a JSON response? I am looking for a solution like Twitter, where they show how many new posts are available that are not on the page or even like on Facebook where they update the wall posts automatically.

Is there a particular technology should I be researching in order make the updates more efficient?

答:
There are several methods for this:

Web Sockets

Long Polling (or the blanket term Comet)

For solutions, check out:

django-socketio

Not a django implementation, but a great resource for concepts: SignalR

I would recommend going the websockets route, then falling back to long polling.  Here's a fairly scholarly article on long polling and best practices.


问:
How should I go about "overhauling" a large legacy application?

Possible Duplicate:

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

For my next project, I've been tasked with "overhauling" a large legacy web application with many parts.  It is a JSP application written in 2004 and it is used heavily by my company.

This application was designed badly in that there is no separation of concerns; no service layer, no DAO layer, no MVC structure.  Just a bunch of JSP files loaded with scriptlets containing logic and database queries mixed in with HTML.  It's a mess.

My boss has defined "overhaul" as basically rewriting the entire thing using the technologies we use for our more recent applications, which are:

Maven

Spring

JPA (w/Hibernate)

JSF

AND add a bunch of new features.

My question is: How do I go about this?  What should be my strategy for completely redoing a large application that is currently in use AND add a bunch of features?

Should I rewrite the existing application first and get it working with the updated technologies and THEN worry about adding new features afterward?  Or should I go about it like I'm creating a whole new application and implement the new features WITH the old features?

Has anyone done this successfully?  If so, what strategies were instrumental to your success?

Edit: More info from comments:

How bad does the design have to be to justify a rewrite? This design is pretty bad. There is tons of business logic hiding in the application. No specs, no logs of requirements changes, no list of bug fixes, no list of open bugs, no test suite, no documentation. And the guy who originally wrote it is now in upper management.

答:
I wouldn't suggest doing a rewrite a whole application. Especially one that is currently being used by the customer. You will never cut over to the new system until it can do everything that the old system does. While you are writing the new system, the customer and management are going to get impatient and want those new features. You, or someone else will have to add them to the old app, which takes away time from the new app, and will just pile on more work that you have to do before it's completed. The chances of you actually completing the project go down as time goes on, until you feel like you're on a never ending project and moral starts to go down.

Generally, a bad idea. As MichaelT link above states.

So what to do instead?

Take a good hard survey of the current code base. Find the good, the bad, the ugly, and the down right frightening. See what can be cleaned up quickly, what can be reused and refactored, what is no longer used or needed, and what needs a rewrite.

Design and implement your new DAL. Look at the pages and the code and detangle it so you have a separate Business layer calling that DAL. Focus on like pages at a time. Release as they are cleaned up and ready. Make it more iterative. You might have to hit these pages more than once, but make sure to leave them better each time.

When a new feature rolls in, b/c you are going to get more than what is currently in your pipe line, incorporate them into the clean up effort. When you release a new feature, release new cleaned up code at the same time.

Will this take some time? Yes. Yes it will. I've been with my current company for 3 years and the web client application I've been cleaning up isn't done. But, we have had numerous major releases, and sold it to many different clients. It now works on more platforms, and it is getting easier and easier to make new pages and features for. If we had of decided to start from scratch and release when done, well, it's still be a work in progress, and we would have no major releases or clients to show for it.


答:
First of all a NoSQL database is a database that does not use an SQL interface. What all NoSQL databases have in common is that they do not use an SQL interface. Did I just repeat myself? Yes, but there is nothing else I can say about NoSQL databases as a group. Anything else being said about NoSQL databases around the internet is either wrong for some members of the group, or likely to become so at some point in the future with the release of a new database or a feature upgrade of an existing one.

All this to say that asking if a NoSQL database is a good choice for a particular job is really not an answerable question since different NoSQL databases have hugely different characteristics.

In the scenario that you describe the biggest issue would definitely be that you are pounding Facebook with 8000 HTTP requests per second, but let's ignore that and focus on the quite common issue of having a large amount of tiny data pieces.

Data handling

All other things being equal, what is the performance difference between fetching an 8 byte string and a 16 byte string from a database? It is insignificant, and barring some obscure counterexample that is true for any database, SQL or not, the overhead of everything else that goes on in a request dwarfs the time it takes to copy 8 more bytes. If you want to shift data through a database fast then sorting it into big blocks that fit your use case is one of the most significant thing you can do, often way more important than what database software you use.

Of course there are cases where your use does not fit having big chunks of data, in some cases a caching strategy where data is kept both in the original split form and in chunks may work well, in other cases there is not a lot to do but keeping the small pieces separated.

Data manipulation

Databases are slow, that is to say, if you implement a data manipulation function in a common program, for instance taking a lot of small strings and joining them into one, and you implement similar functionality through a database request, then the database version will typically take 100 to 1000 times as long to do the operation. The exact figure of course depend on the database, some databases will not be able to do it, so you'd have to write a program that fetch all the data, perform the operation, and then write the result to the database, which is also a pretty slow method.

In general, don't do on the database what you could reasonably do to the data before it's written to the database.

What database to choose

Once you have taken all these considerations, what requirements for a database do you have left? Did you manage to come up with a structure that doesn't need any of the fancy/slow features offered by some databases? If you did then an SQL database may be like a Swiss knife with a dull blade, lots of cool features, but not particularly good at what you need it for. Some of the NoSQL databases are simply faster and better when you only need the simple features, others fit the job just as bad as an SQL database.

The big question

Despite being written last in this post it is the question you should ask before all the other questions that I mentioned. Do you actually need a database?

It is a pretty common assumption that when you handle a significant amount of data, you should use a database. But with a modern computer you can store several gigabytes of data in application memory. This gives you fast and easy access, and the good tools for manipulation are right at hand. The one thing that it does not give you is persistence, if the program crash of there is a power loss the data is lost. In a lot of cases that is however perfectly acceptable, your example has data with a life span of ~5 minutes, it doesn't need persistence, it doesn't need a database.

Title: Why is NoSQL better for this scenario?

Body:
Hypothetical scenario: Let's say we are downloading JSON from Facebook with details of a user's friend's checkins, posts, etc... These come in as one document per friend per activity, so with 8 activities a user with 300 friends will cause our system to make 2400 requests to Facebook, downloading 2400 JSON documents.

Let's say we want to merge these 2400 documents together, sort the activities by date_created descending and then page through them in a sort of pseudo newsfeed. Please do not comment on the wisdom of recreating a facebook newsfeed in this way.

Let's also suppose that we want to re-download all of this data whenever we are notified that it has changed by Facebook. (FB has an update service you can subscribe to for users of your app). For argument sake let's assume all of the data has to be refreshed every 5 minutes, and further assume we want to be able to support 1000 simultaneous users, and that the average JSON document size is 25kb.

I am curious as to how NoSQL techniques would be better than parsing the JSON on ingestion into a relational database? To me it seems like map/reduce are just synonyms for parse/aggregate and that both approaches will require the same thing to occur. What advantages would I get from using NoSQL?


问:
How can I deal with a team member who dislikes making comments in code?
One of my team members consistently avoids making comments in his code.

His code is not self-documenting, and other programmers have a difficult time understanding his code.

I have asked him several times to comment his code, however he just gives excuses or claims that he will do it later. His concern is that adding comments will take too much time and delay the projects.

What argument can I present to him to convince him to properly document his code?

On that note, am I wrong to focus on the code comments or is this indicative of a larger problem which should be addressed?

答:
Get code review software, and use it well.

We use Kiln, and we love it. We have a policy that every changeset must be reviewed (though we allow devs to raise/approve reviews for themselves on tags and conflict-less merges (though most of us use rebaseif); this way we can quickly spot changesets without reviews).

Code that is not clear is reason for a code review to be rejected. It doesn't matter whether the fix is comments or clearer code, but the reviewer must be able to understand it. Some devs prefer to rewrite the code, but others (myself included) often find it easier to express intention in comments (code can easily show what it does, but it's harder to show what it should do).

If there is ever question about the clarity of code, the reviewer always wins. Of course the author understands it, because they wrote it. It needs to be clear to another person.

By using software like Kiln, no changeset gets overlooked. Everybody in my dev team much prefers it this way. Code review software has had a huge impact on both our code quality, and application quality :-)

It's easy for devs to get defensive with rejected reviews when first introducing software, but in my experience, it doesn't take them long to realise things are better this way and embrace it :-)

Edit: Also worth noting, we try not to have devs explain cryptic code verbally or in comments in the review. If something isn't clear, the best place to explain it is in the code (in comments, or by refactoring), then add the new changesets to the same review.


答:
How much business logic is hiding in this application? Do you have the
  full specs at the start? All the requirements changes over the past
  decade? All the bugs that have been fixed? All the bugs that are still
  open? Comprehensive regression testing suite?

To which was answered...

How bad does the design have to be to justify a rewrite? This design
  is pretty bad. There is tons of business logic hiding in the
  application. No specs, no logs of requirements changes, no list of bug
  fixes, no list of open bugs, no test suite, no documentation. And the
  guy who originally wrote it is now in upper management.

You've got a application that is a decade old, with no documentation of what it really should do, what was done to fix it, or what it isn't doing right.

There are two approaches.

The first is to slowly rewrite it from within.  Go in, find a module, figure out exactly what it does and what it should do, and replace it.  This is a gradual process.  It is likely the best approach.  It isn't something that management tends to like (I have found that management tends to like big projects that look big and have big releases).  Replacing something from the inside that doesn’t look like it is doing anything doesn't get accolades.

The other approach is to go and throw away the original and start over.  The question is "how long will this take?" is one of the first questions that is asked.  For this, one can get a reasonable estimate.

Given no documentations, a complete rewrite, such find out how many lines of code the application has and toss it into the COCOMO II model.  This works on the assumption that it will take about as many lines of code to write the new code as is there existing now.  See how big it is.

The question of is this a good idea for the business to undertake isn't one that as programmers we should make.  We have opinions on it, and may think this is a terrible waste of time or that this is something that would be great fun to do (I strongly suggest reading Death March to get some perspective on this) - but we are not the ones that make the calls for the business.

Identify the time frame that this will take, and let the business decide if there is a justifiable return on investment.

Remember, there is a third option - leave it like it is.

Title: How should I go about "overhauling" a large legacy application?

Body:
Possible Duplicate:

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

For my next project, I've been tasked with "overhauling" a large legacy web application with many parts.  It is a JSP application written in 2004 and it is used heavily by my company.

This application was designed badly in that there is no separation of concerns; no service layer, no DAO layer, no MVC structure.  Just a bunch of JSP files loaded with scriptlets containing logic and database queries mixed in with HTML.  It's a mess.

My boss has defined "overhaul" as basically rewriting the entire thing using the technologies we use for our more recent applications, which are:

Maven

Spring

JPA (w/Hibernate)

JSF

AND add a bunch of new features.

My question is: How do I go about this?  What should be my strategy for completely redoing a large application that is currently in use AND add a bunch of features?

Should I rewrite the existing application first and get it working with the updated technologies and THEN worry about adding new features afterward?  Or should I go about it like I'm creating a whole new application and implement the new features WITH the old features?

Has anyone done this successfully?  If so, what strategies were instrumental to your success?

Edit: More info from comments:

How bad does the design have to be to justify a rewrite? This design is pretty bad. There is tons of business logic hiding in the application. No specs, no logs of requirements changes, no list of bug fixes, no list of open bugs, no test suite, no documentation. And the guy who originally wrote it is now in upper management.