答:
So...  Let me suggest a refactoring:

```<code>public void CheckHistory(int months)
{
    var endDate = DateTime.Today.AddMonths(months);
    Dictionary<Order, bool> orders = new Dictionary<Order, bool>();

    foreach (var kvp in this.Orders)
    {
        orders.Add(kvp.Key, kvp.Key.Date < endDate);
    }
    this.OrderHistories = orders;
}
</code>```

Nice, right?  Well, maybe nice, but not right.  Because I (let's pretend inadvertently) flipped the direction of the inequality operator.  Would your test have caught that?  Actually (I think) no, because the number before & after is the same, and you're only testing that the count is 1.  So you should probably think about enhancing it a little bit.  But in terms of the value of having the unit test, of having that kind of test coverage: Yes, it's valuable, because it lets you refactor safely.

Title: Help in ensuring unit tests are meaningful

Body:
I've just written a unit test for this function, which loops through a collection of dates and sets properties equal to true or false depending on whether they're before or after a given comparison date:

```<code>public void CheckHistory(int months)
{
    var endDate = DateTime.Today.AddMonths(months);
    Dictionary<Order, bool> orders = new Dictionary<Order, bool>();

    foreach (var kvp in this.Orders)
    {
        if (kvp.Key.Date >= endDate)
        {
            orders.Add(kvp.Key, true);
        }
        else
        {
            orders.Add(kvp.Key, false);
        }
    }
    this.OrderHistories = orders;
}
</code>```

So here's the test I wrote:

```<code>public void Assert_CheckHistory_SelectsCorrectDates()
{
    MyViewModel vm = GetVmWithMockRepository();
    vm.OrderHistories = new Dictionary<OrderHistory, bool>();

    OrderHistory ohOld = new OrderHistory();
    ohOld.MailingDate = DateTime.Today.AddMonths(-12);
    vm.OrderHistories.Add(ohOld, false);

    OrderHistory ohNew = new OrderHistory();
    ohNew.MailingDate = DateTime.Today.AddMonths(-3);
    vm.OrderHistories.Add(ohNew, false);

    vm.CheckOrderHist(-6);

    int selectedOrders = vm.OrderHistories.Where(o => o.Value == true).Count();
    Assert.AreEqual(1, selectedOrders, "Unexpected number of selected Order Histories");
}
</code>```

Nothing wrong there. Test passes and all is good with the world.

However, I'm haunted by a nagging feeling that I'm not actually testing anything useful, and am just writing tests for the sake out it.

I get this a lot. A creeping paranoia that the tests I'm writing are incomplete in the sense that while they cover the lines of code in the target function, they don't really trap any likely problems and are therefore just a maintenance overhead.

Is that sample test worthwhile? Is even a badly-designed test worth worthwhile over no test at all? And most of all are there any principles to help programmers identify whether a test is useful or not, or to guide them in constructing useful tests in the future?

To be clear, I'm adding tests to an existing application. Going test-first in true TDD style isn't possible.

Body:
So...  Let me suggest a refactoring:

public void CheckHistory(int months)
{
    var endDate = DateTime.Today.AddMonths(months);
    Dictionary<Order, bool> orders = new Dictionary<Order, bool>();

    foreach (var kvp in this.Orders)
    {
        orders.Add(kvp.Key, kvp.Key.Date < endDate);
    }
    this.OrderHistories = orders;
}

Nice, right?  Well, maybe nice, but not right.  Because I (let's pretend inadvertently) flipped the direction of the inequality operator.  Would your test have caught that?  Actually (I think) no, because the number before & after is the same, and you're only testing that the count is 1.  So you should probably think about enhancing it a little bit.  But in terms of the value of having the unit test, of having that kind of test coverage: Yes, it's valuable, because it lets you refactor safely.


问:
Help in ensuring unit tests are meaningful
I've just written a unit test for this function, which loops through a collection of dates and sets properties equal to true or false depending on whether they're before or after a given comparison date:

```<code>public void CheckHistory(int months)
{
    var endDate = DateTime.Today.AddMonths(months);
    Dictionary<Order, bool> orders = new Dictionary<Order, bool>();

    foreach (var kvp in this.Orders)
    {
        if (kvp.Key.Date >= endDate)
        {
            orders.Add(kvp.Key, true);
        }
        else
        {
            orders.Add(kvp.Key, false);
        }
    }
    this.OrderHistories = orders;
}
</code>```

So here's the test I wrote:

```<code>public void Assert_CheckHistory_SelectsCorrectDates()
{
    MyViewModel vm = GetVmWithMockRepository();
    vm.OrderHistories = new Dictionary<OrderHistory, bool>();

    OrderHistory ohOld = new OrderHistory();
    ohOld.MailingDate = DateTime.Today.AddMonths(-12);
    vm.OrderHistories.Add(ohOld, false);

    OrderHistory ohNew = new OrderHistory();
    ohNew.MailingDate = DateTime.Today.AddMonths(-3);
    vm.OrderHistories.Add(ohNew, false);

    vm.CheckOrderHist(-6);

    int selectedOrders = vm.OrderHistories.Where(o => o.Value == true).Count();
    Assert.AreEqual(1, selectedOrders, "Unexpected number of selected Order Histories");
}
</code>```

Nothing wrong there. Test passes and all is good with the world.

However, I'm haunted by a nagging feeling that I'm not actually testing anything useful, and am just writing tests for the sake out it.

I get this a lot. A creeping paranoia that the tests I'm writing are incomplete in the sense that while they cover the lines of code in the target function, they don't really trap any likely problems and are therefore just a maintenance overhead.

Is that sample test worthwhile? Is even a badly-designed test worth worthwhile over no test at all? And most of all are there any principles to help programmers identify whether a test is useful or not, or to guide them in constructing useful tests in the future?

To be clear, I'm adding tests to an existing application. Going test-first in true TDD style isn't possible.

答:
To quote the "Way of Testivus",

A bad test is better than no test

Making sure that your test tells you that the code works is the point of the test.  When you are writing tests for code that has already been written, you are setting things up so that you can refactor it and be confident that you have not broken any current functionality.  If the test fails for no apparent reason, then the test is bad and should be fixed.  As long the test ensures the functionality of your application, the test has some value.

Writing these tests gives you confidence in your ability to refactor that code later on.  Because if you have done it right, the test will still pass.  You are giving yourself the confidence to change that code and not have to worry about breaking any old functionality.

Uncle Bob had a recent blog entry regarding this:

If you have a test suite that you trust so much that you are willing to deploy the system based solely on those tests passing; and if that test suite can be executed in seconds, or minutes, then you can quickly and easily clean the code without fear.

Your example test isn't all that good but it gives you more confidence that any changes you make will not affect the functionality.  You want to check that for a given state the method will output a specific response.  You trying to test what the code does rather than what the code is.  For legacy code like this, you will end up with tests that are more "functional" rather than "unit".

Does having this test give you more confidence that any changes to the application did not result in the code being broken?  If not, then your test is not useful and you should get rid of it or change it.  Untested code will paralyze any useful changes that you can make later.

"We can't make that change because we don't know everywhere that it is being used!"  Your tests make that argument moot.  You know that the code all works because all the tests pass.

Tests also do not ensure bug-free code.  Your code may still have bugs but when they are discovered and you add a new test duplicating it.  You ensure that that bug NEVER happens again because then that test will fail.  And as long as you are running your tests often, this bug will always be checked for.

ContentLicense: CC BY-SA 3.0


问:
Mimicking a bluetooth disconnection
I've written a program to control a bluetooth device. I'm trying to test cases when the bluetooth disconnects, i.e. if its out of range.

Physically taking the device out of range is one possibility, but its quite cumbersome and I have to go outside my office to achieve this.

What can I do to trigger a disconnection? Is there, for example, an interferer I can setup, say with an Android phone, that would make the connection drop? Or limit the Bluetooth transmit power? Any other possibilities?

答:
There are quite a few ways to trigger a disconnect. I guess you are mostly interested in triggering a sudden loss of connection, not a graceful disconnect.

Some things that I have used in the past:

Take the device out of range

Remove the battery/power source (without doing a normal power down -> a sudden loss of power)

Put the device in a shielded box/cage of Faraday

Bluetooth was designed to work in a frequency band with a lot of interference/noise, so it is unlikely you will be able to reliably trigger a disconnect that way.

Title: Mimicking a bluetooth disconnection


问:
Should all foreign table references use foreign key constraints
Closely related to: https://softwareengineering.stackexchange.com/q/45447/48651

I asked a question on SO and it led me to ask this here.

If I'm faced with a choice of having a circular reference or just not enforcing the restraint, which is the better choice?

In my particular case I have customers and addresses. I want an address to have a reference to a customer and I want each customer to have a default billing address id and a default shipping address id.

I might query for all addresses that have a certain customer ID or I might query for the address with the ID that matches the default shipping or billing address ids.

I'm not sure yet how the constraints (or lack of) will effect the system as my application and it's data age.

答:
Should all foreign table references use foreign key constraints?

Short answer "No" or "Not necessarily"

Long answer.
Consider how your data relates to each other and in what circumstances you want to prevent a change. (Like not letting an address get deleted if it is still assigned to another entity.) Let that guide you in deciding IF you should use the FK constraint.


问:
Is it reasonable for programmers to be sprinting the whole year round?
It feels like it is not enough for working programmers just to "walk" 5 to 8 hours a day, and "quick walk" is not enough, but they have to "sprint", every day, year after year.  For the company, it makes a lot of sense because to get the most out of workers, sprinting all day long, day after day is better than people who merely walk the whole day.

Here I am comparing our "sprints" to normal day life of walking vs sprinting.  While we can sprint 100 meter a few times or even two dozen time a day, for a total of 15 seconds x 25, can anybody sprint the whole day long for 5 hours, and day after day?

What I mean is, doesn't it make more sense to sprint for 3 months, and then get back to normal, when people can just "walk" or "quick walk", being productive, for the rest of the 9 months in a year?  Or sprint for 3 months, get back to normal for 3 months, and then sprint for another 3 months and back to normal for another 3 months?

It sure make a lot of sense to the company, because if people can sprint the whole year, then the company can get a lot of things done, burn out people, and just later replace the burned out people by other fresher people (possibly replaceable contractors) -- and it is such a nice term to use too -- we have people sprinting the whole year round -- we are getting the "maximum" output -- so the directors now can have reasons to get promoted to be vice presidents.

I really wonder, should sprints really be year round?  I think in the old days, when companies such as Microsoft made people work 60 hours per week, some people described them as a velvet sweat shop.  But if we begin to say, we are just having sprints (and not mentioning that it is sprints for 3 weeks, and then another one immediately following, and it just repeats again and again the whole year round), then it sounds like a very justified thing to do.

答:
One of the basic agile tenants is to work at a manageable pace:

Agile processes promote sustainable development.

  The sponsors, developers, and users should be able

  to maintain a constant pace indefinitely.

--Agile Manifesto

In other words: the pace at which teams work during sprint should be maintainable indefinitely. The name "Sprint" in no way implies going faster than normal!


答:
First, if you find yourself building a system where table A references table B and table B references table A, that often implies that you've violated normalization rules in building your data model.  Very, very occasionally, you may do this because you've measured and benchmarked and the denormalization solves a particular performance problem.  The vast majority of the time, though, it means that you really want to reconsider the data model.

In this case, I'd strongly suggest reconsidering the data model.  A customer has one or more addressed.  An address does not have a customer.  It doesn't make data model sense for an address table to have a reference to a customer or a vendor table.  It may make sense for a customer table to have a reference to an address table but it would generally make more sense to build a mapping table between the customer and address tables (and between vendor and address) as outlined in your StackOverflow question.

If you are building an OLTP system, I'd strongly suggest creating foreign keys to enforce any referential integrity constraints that your data has.  If you don't, I can guarantee that someone will eventually create data inconsistencies (orphaned children, references to non-existent children, etc.)  Yes, creating foreign keys adds some overhead from a performance standpoint.  But assuming you care about the data making sense, you'll have to check those constraints somewhere and it's unlikely that you can do it more efficiently than the database can.

Title: Should all foreign table references use foreign key constraints

Body:
Closely related to: https://softwareengineering.stackexchange.com/q/45447/48651

I asked a question on SO and it led me to ask this here.

If I'm faced with a choice of having a circular reference or just not enforcing the restraint, which is the better choice?

In my particular case I have customers and addresses. I want an address to have a reference to a customer and I want each customer to have a default billing address id and a default shipping address id.

I might query for all addresses that have a certain customer ID or I might query for the address with the ID that matches the default shipping or billing address ids.

I'm not sure yet how the constraints (or lack of) will effect the system as my application and it's data age.


问:
Dealing with similar objects with different method signatures
I am fairly new to OO design and have problems with the design of some software and looking for a pattern or a combination of patterns that could help me solving my problem.

I have a type that has a collection of different geometric shapes (say lines, rectangles, and cubes). I actually even have composites of these shapes.
Each shape has one or more values. A value is a coordinate (between one-dimensional for lines and three-dimensional for cubes).

All types of shapes have two methods that are essential. A method for adding values and a method for getting all values of a shape. E.g. Cube.AddValue(new Value3D{X=4,Y=7,Z=11}) or Line.AddValue(new Value1D{X=42}) respectively Cube.GetValues() would return a collection of Value3D and Line.GetValues() would return a collection of Value1D.

Since these methods have fundamentally different signatures, I can't just derive from a single interface to store all of these different objects in one collection. Splitting the collection into multiple separate collections, one for each type would be possible, but not desirable since they belong together (domain wise).

I've considered using three-dimensional values for all shapes and just ignoring Y/Z for lines/rectangles, but that isn't really nice and would actually violate the O and L in SOLID (a 4th dimension is possibly needed in the future).

Another possibility would probably be to use a generic Interface like IShape<T> where T is Value*D. This interface would look like:

```<code>public interface IShape<T> {
    public IEnumerable<T> GetValues();
    public void AddValue(T value);
}
</code>```

But this would require another, non-generic interface INonGenericShape {} because I can't use a generic interface without specifying the type. I would end up with something like this:

```<code>public class SomeShape{
    private IList<INonGenericShape> _shapes = new List<INonGenericShape>();
}
</code>```

But then I could as well use System.Object, since IShape does not provide any valuable information. So here I am, not knowing how to solve this (storing the objects in a single collection for consumers of that class). Can anyone provide some idea or insight?

答:
The answer is simply, these aren't similar objects. Inheritance is about shared behaviour, not shared values. Just because these objects are made up of points doesn't mean they are related in terms of behaviour.

Leaving aside that getters and setters aren't really behaviour and should be avoided if at all possible*, even in this case the getters and setters are doing different things, as hinted by the different signatures. This should make it clear, these objects do not share behaviour beyond the most meaningless sense of storing points.

(this is a good example of why to avoid getters and setters, as they can cloud the true behaviour of an object, and make it appear that unrelated objects are related because they all have getter and setter methods)


问:
Why would Square inheriting from Rectangle be problematic if we override the SetWidth and SetHeight methods?
If a Square is a type of Rectangle, than why can't a Square inherit from a Rectangle? Or why is it a bad design?

I have heard people say:

If you made Square derive from Rectangle, then a Square should be
  usable anywhere you expect a rectangle

What is the problem here? And why would Square be usable anywhere you expect a rectangle? It would only be usable if we create the Square object, and if we override the SetWidth and SetHeight methods for Square than why would there be any issue?

If you had SetWidth and SetHeight methods on your Rectangle base class
  and if your Rectangle reference pointed to a Square, then SetWidth and
  SetHeight don't make sense because setting one would change the
  other to match it. In this case Square fails the Liskov Substitution
  Test with Rectangle and the abstraction of having Square inherit from
  Rectangle is a bad one.

Can someone explain the above arguments? Again, if we over-ride SetWidth and SetHeight methods in Square, wouldn't it resolve this issue?

I have also heard/read:

The real issue is that we are not modeling rectangles, but rather
  "reshapable rectangles" i.e., rectangles whose width or height can be
  modified after creation (and we still consider it to be the same
  object). If we look at the rectangle class in this way, it is clear
  that a square is not a "reshapable rectangle", because a square cannot
  be reshaped and still be a square (in general). Mathematically, we
  don't see the problem because mutability doesn't even make sense in a
  mathematical context

Here I believe "re-sizeable" is the correct term. Rectangles are "re-sizeable" and so are squares. Am I missing something in the above argument? A square can be re-sized like any rectangle.

答:
What LSP says is that anything that inherits from Rectangle must be a Rectangle. That is, it should do whatever a Rectangle does.

Probably the documentation for Rectangle is written to say that the behaviour of a Rectangle named r is as follows:

r.setWidth(10);
r.setHeight(20);
print(r.getWidth());  // prints 10
```

If your Square doesn't have that same behaviour then it doesn't behave like a Rectangle. So LSP says it must not inherit from Rectangle. The language can't enforce this rule, because it can't stop you doing something wrong in a method override, but that doesn't mean "it's OK because the language lets me override the methods" is a convincing argument for doing it!

Now, it would be possible to write the documentation for Rectangle in such a way that it doesn't imply that the above code prints 10, in which case maybe your Square could be a Rectangle. You might see documentation that says something like, "this does X. Furthermore, the implementation in this class does Y". If so then you have a good case for extracting an interface from the class, and distinguishing between what the interface guarantees, and what the class guarantees in addition to that. But when people say "a mutable square is not a mutable rectangle, whereas an immutable square is an immutable rectangle", they're basically assuming that the above is indeed part of the reasonable definition of a mutable rectangle.

Body:
What LSP says is that anything that inherits from Rectangle must be a Rectangle. That is, it should do whatever a Rectangle does.

Probably the documentation for Rectangle is written to say that the behaviour of a Rectangle named r is as follows:

r.setWidth(10);
r.setHeight(20);
print(r.getWidth());  // prints 10

If your Square doesn't have that same behaviour then it doesn't behave like a Rectangle. So LSP says it must not inherit from Rectangle. The language can't enforce this rule, because it can't stop you doing something wrong in a method override, but that doesn't mean "it's OK because the language lets me override the methods" is a convincing argument for doing it!

Now, it would be possible to write the documentation for Rectangle in such a way that it doesn't imply that the above code prints 10, in which case maybe your Square could be a Rectangle. You might see documentation that says something like, "this does X. Furthermore, the implementation in this class does Y". If so then you have a good case for extracting an interface from the class, and distinguishing between what the interface guarantees, and what the class guarantees in addition to that. But when people say "a mutable square is not a mutable rectangle, whereas an immutable square is an immutable rectangle", they're basically assuming that the above is indeed part of the reasonable definition of a mutable rectangle.


问:
Writing in C for Performance?
I know I have quite frequently heard that C typically has a performance advantage over C++. I didn't really think anything else of it until I realized that MSVC doesn't even seem to support the newest standard of C, but the newest it supports it C99 (as far as I know).

I was planning on writing a library with some code to render in OpenGL so I could reuse it. I was planning to write the library in C since any performance increase is welcome when it comes to graphics.

But would it really be worth it? The code using the library would likely be written in C++ and I prefer to code in C++ generally.

However, if it would produce even a small difference in performance, I would likely go with C.

It may also be noted that this library would be something that I would make to work across Windows/OS X/Linux, and I would likely compile everything natively (MSVC for Windows, Clang or GCC for OS X, and GCC for Linux...or possibly Intel's compilers for everything).

I've looked around and I've found some benchmarks and such, but everything I've seen has dealt with GCC rather than MSVC and Clang. Also, the benchmarks don't mention the standards of the languages used. Anyone have any thoughts on this?

EDIT: I just wanted to share my viewpoint on this question after a couple years more experience. I ended up writing the project I was asking this question for in C++. I started another project around the same time in C as we were looking to get out any small amount of performance we could and needed the project to be linkable in C. A couple months ago, I reached the point where I really needed maps and advanced string manipulation. I knew of the abilities for this in the C++ standard library and eventually came to the conclusion that those structures in the standard library would likely outperform and be more stable than maps and strings I could implement in C in a reasonable amount of time. The requirement to be linkable in C was easily satisfied by writing a C interface to the C++ code, which was done quickly with opaque types. Rewriting the library in C++ seemed to go much faster than when writing it in C and was less prone to bugs, especially memory leaks. I was also able to use the standard library threading library, which has been much easier than using platform-specific implementations. In the end, I believe writing the library in C++ led to great benefits with possibly a small performance cost. I haven't benchmarked the C++ version yet, but I believe that it may even be possible that I have gained some performance by using standard library data structures than ones I wrote.

答:
C doesn't have any performance advantage compared to C++ if you do the same things in both languages. You can take any old C code written by any decent C programmer and turn it into valid and equivalent C++ code, which will run just as fast (unless both you and your compiler know what the "restrict" keyword does and you use it effectively, but most people don't).

C++ can have have hugely different performance, either slower or faster, if (1) you use the standard C++ library to do things that can be done much faster and easier without using the library, or (2) if you use the standard C++ library to do things much easier and faster than by reimplementing the library in bad C.

Now one important consideration: Much more important than the language is how much time I spend on making the implementation fast. I would say it is easier to creat working C++ code, and then you have more time to make it fast. And C++ makes it easier to put performance critical things into some class so that ugly complex and fast speed-optimised code isn’t visible to the caller. And with more time spent on optimisations, your C++ code can run substantial faster.

Title: Writing in C for Performance?

ContentLicense: CC BY-SA 4.0


问:
jQuery - When to Bind Event Listeners?
I'm building a medium-sized "single-page" JavaScript application using jQuery. If you include all possible functionality of the application, there are 134 click bindings.

Since most of the content is dynamically loaded, I can't just do this:

$(element).click(function() { ... });

Instead, I'm doing this:

$(document).on('click', selector, function() { ... });

Currently, I'm binding all of these on $(document).ready. But is that bad practice? Is this a speed issue?

The alternative would be to bind the event listeners every time the content is loaded, for example:

```<code>$('#content').html(...);
$('#newcontent').click(function() { ... });
</code>```

The problem with that is it's difficult to organize. What advice can you give me?

答:
What is best to do really depends on the details of the application, and will vary depending on the specifics of each application.

I find it is easier to follow the logic of an application with a single:

```<code>$(top).on('click', selector, function() { ... });
</code>```

rather than have to discover that various part of the application add handlers as they update the part of the page they are responsible for. Note I've used top rather than document, because (like user12415 pointed out) it is better to use an element which is only as wide as needed rather than document itself.

I some cases, trying to add the handlers on directly on the elements themselves rather than use delegation can cause a significant performance hit or require stronger coupling between parts than what is desirable. I have an editing application where I use delegation to handle all click events on hyperlinks. This application has an editing core that provides the base functionality but uses modes to change editing behavior depending on what data is being edited. For instance, a mode could provide a facility to turn all instances of a word into a hyperlink to the same word in Wikipedia. The core cannot predict how a mode will change the document. So without delegation, the core would have to check every transformation to see whether it added a hyperlink, which is costly. A mode could turn plain text into hyperlinks as the text is being keyed in. So this would mean performing the check for every keystroke. Very costly! Or the mode would have to have a way to tell the core that it added to the document something that the core cares about. This is error prone. ("Oops! Forgot to tell the core.") Delegation is the sane option here.

Title: jQuery - When to Bind Event Listeners?

Body:
What is best to do really depends on the details of the application, and will vary depending on the specifics of each application.

I find it is easier to follow the logic of an application with a single:

$(top).on('click', selector, function() { ... });

rather than have to discover that various part of the application add handlers as they update the part of the page they are responsible for. Note I've used top rather than document, because (like user12415 pointed out) it is better to use an element which is only as wide as needed rather than document itself.

I some cases, trying to add the handlers on directly on the elements themselves rather than use delegation can cause a significant performance hit or require stronger coupling between parts than what is desirable. I have an editing application where I use delegation to handle all click events on hyperlinks. This application has an editing core that provides the base functionality but uses modes to change editing behavior depending on what data is being edited. For instance, a mode could provide a facility to turn all instances of a word into a hyperlink to the same word in Wikipedia. The core cannot predict how a mode will change the document. So without delegation, the core would have to check every transformation to see whether it added a hyperlink, which is costly. A mode could turn plain text into hyperlinks as the text is being keyed in. So this would mean performing the check for every keystroke. Very costly! Or the mode would have to have a way to tell the core that it added to the document something that the core cares about. This is error prone. ("Oops! Forgot to tell the core.") Delegation is the sane option here.


问:
Project Organization
I have been having a discussion with a colleague about the best way to organize a (C#)project after he reorganized a project I had been working on from something that looked like this:

To something that looks like this:

I tend to sway towards having a few big projects as opposed to many smaller projects, but I am open to new ideas and I would love for some input on this. Does anyone have experience with either of these approaches either really working out, or completely falling apart a few years down the line?

答:
A benefit of having many smaller, cohesive projects is reuse. If you have a project B that needs project A for 5% of the things, perhaps that 5% of things should be split out into its own project C which B should depend on instead, if it is really an independent feature or logical grouping of code. Part of the "interface segregation principal" is that a class should not be forced to rely on an interface for methods it does not care about, i.e. interfaces should be small and cohesive. You can think of this project refactoring as an extension of that.

On the other hand, being practical trumps good design and project organization. If you dont think that splitting up your projects to allow easier refactoring or reuse by other projects in the future will be beneficial (ex. you dont expect your project to get reused), then time (i.e. money) shouldnt be spend doing that refactoring if it is non-trivial.

Title: Project Organization


答:
I see that you stumble upon a common issues when doing testing.

A teacher of mine was often joking what usually happens in the lab for software engineering - a student creates 3-4 test cases and if they don't break the application it was alright and they were ready for the next assignment.

A common misconception about testing is that it is supposed to cover test cases that do not break your software. It is actually the exact opposite - with testing you try to break your application and see what happens.

Another problem is the way test cases are defined and their number. For 5 cases that your application passes there are maybe 10000000 ones that break it. Of course since we have a limited time to spend on testing we don't need to and it is actually in most cases impossible to cover all test cases for a certain problem (especially the more complex ones).

That is why tools such as QuickCheck were created. With QuickCheck (available not only for Haskell, which it was originally created for, but also for many other languages) you define the logic that a certain function has to fulfill and then you generated as many test cases as you want to. This is how testing should be done.

From your code I will assume that you are using C#. There is no QuickCheck for C# (sadly) but you have the concept of invariants and contracts plus Pex, which enhances the whole unit testing experience a lot.


问:
How to show to management that unit testing is cheaper in the long run than manual testing?
In the company I work for there is a requirement that all the code should be covered by a test of any kind because they want to have as few user reported defects as possible.

With this is mind I decided to put a policy that the code should be unit tested to C0 (100% coverage of each line, not each condition).

Now others say that this is more expensive that doing manual test.

Intuitively I would say that this is wrong as each time you do a change you have to retest everything manually and this is probably more effort than just executing the tests and updating the ones that need to be updated but I don't find a way to justify myself with numbers, papers or other information.

Can you give me some good points to proof my approach to the people I report to?

EDIT: Thanks to all that helped on the question. I see that there were some key points missing on it:

This is a new product that we started developing one year ago with testing in mind so we use DI everywhere and everything is prepared for testing.

We already have a commercial product that allows us to reach a 100% coverage as we can mock almost everything, including .Net classes so we can truly isolate classes (JustMock).

We have tools to calculate testing coverage.

We are not removing testers and manual testing. We are removing manual testing done by developers. We have a separate SQ team but management wants that the number of bugs that reach the SQ team is as small as possible so developers must reach 100% coverage by any mean before delivering code to the SQ team. So what I did was to replace developer manual testing with automated testing (unit and integration tests) and that's what management wants to revert.

The question is not the same as the "duplicated" one as I already have a 100% coverage requirement.

答:
Do some back of the envelope math to figure out where the break-even point is.

If it takes x hours for a manual tester that gets paid $y/hr to run through a manual test and the manual test has to be run z times per year, the cost of the manual test is x * y * z per year.  If it takes n hours for someone making $m/hr to automate that test, that's a one-time cost of n*m.  Then figure out how long it takes for the one-time investment in building the automated test (n*m) to outweigh the (x*y*z) annual cost of the manual test.

Most of the time, building the automated test is a no-brainer.  It's a bit more expensive as a one-time cost but it saves the recurring cost of running the manual test.  And that's before you account for the fact that manual tests are generally less reliable since humans are fallible and will occasionally leave out steps.  Occasionally, though, you'll find tests that you want to run occasionally that are hard to automate and easier to just have a human run manually before major releases.


答:
Most of the industry specialists agree that unit testing helps and reduces defect rate; there have been studies based on multiple projects that show this. You can find concrete results of these studies in software engineering books; take a look for example in Steve McConnell's Code Complete at chapter 20.3 Relative Effectiveness of Quality Techniques.

On the critical side, you're making an assumption that might not hold true in all the cases:

it really depends on your application, on the domain type (I can't see how you can release a complex game for example without any manual testing)

it depends if you're at the beginning with the application and change lots of things or you already have a pretty stable application.

maybe your application has a short life-span and investing much in automated testing is not worth it

it depends on the workforce; maybe the human resources in your area in manual testing are much more cheaper than developers or testers that know how to code

Having 100% unit test code coverage doesn't make sense (in most of the cases) because:

It does not guarantee you're application is bug free; there still are integration issues, performance issues, security issues etc.  The most important reason of unit tests I believe it to be the assurance of refactoring code without breaking it up; not a replacement for other types of issues.

It's extremely difficult to reach. Basically unit tests show you that you have working separate units, but your applications have many interconnected units. The correctness of the application also depends on how these units are interconnected.

See a much better argument by Joel Spolsky .

To sum up it's a very good idea to add unit tests if you don't have any; but it's a bad idea to fully replace manual testing with 100% line coverage in unit tests.

Title: How to show to management that unit testing is cheaper in the long run than manual testing?

Body:
In the company I work for there is a requirement that all the code should be covered by a test of any kind because they want to have as few user reported defects as possible.

With this is mind I decided to put a policy that the code should be unit tested to C0 (100% coverage of each line, not each condition).

Now others say that this is more expensive that doing manual test.

Intuitively I would say that this is wrong as each time you do a change you have to retest everything manually and this is probably more effort than just executing the tests and updating the ones that need to be updated but I don't find a way to justify myself with numbers, papers or other information.

Can you give me some good points to proof my approach to the people I report to?

EDIT: Thanks to all that helped on the question. I see that there were some key points missing on it:

This is a new product that we started developing one year ago with testing in mind so we use DI everywhere and everything is prepared for testing.

We already have a commercial product that allows us to reach a 100% coverage as we can mock almost everything, including .Net classes so we can truly isolate classes (JustMock).

We have tools to calculate testing coverage.

We are not removing testers and manual testing. We are removing manual testing done by developers. We have a separate SQ team but management wants that the number of bugs that reach the SQ team is as small as possible so developers must reach 100% coverage by any mean before delivering code to the SQ team. So what I did was to replace developer manual testing with automated testing (unit and integration tests) and that's what management wants to revert.

The question is not the same as the "duplicated" one as I already have a 100% coverage requirement.


答:
For what it's worth, I tend to write my libraries in C++11 for the enhanced feature set. I like being able to take advantage of things like shared pointers, exceptions, generic programming, and other C++ only features. I like C++11 because I've found that a good bit of it is supported on all of the platforms I care about. Visual Studio 2013 has a lot of the core language features and library implementations ready to go and supposedly is working on adding the remainder. As you well know, Clang and GCC both support the entire feature-set as well.

With that said, I recently read about a really great strategy regarding library development that I think is directly relevant to your query. The article is titled "A C error handling style that plays nice with C++ exceptions" Stefanu Du Toit refers to this strategy as an "hourglass" pattern. The first paragraph of the article:

I've written a lot of library code using what I call an "hourglass"
pattern: I implement a library (in my case, typically, using C++),
wrap it in a C API which becomes the only entry point to the library,
then wrap that C API in C++ or some other language(s) to provide a
rich abstraction and convenient syntax. When it comes to native
cross-platform code, C APIs provide unparalleled ABI stability, and
portability to other languages via FFIs. I even restrict the API to a
subset of C that I know is portable to a wide variety of FFIs and
insulates the library from leaking changes in internal data structures
— expect more on that in future blog posts.

Now to address your primary concern: performance.

I would suggest, like many of the other answers here, that writing code in either language would work just as well on a performance standpoint. From a personal standpoint, I find writing correct code in C++ to be easier due to the language features, but I think that's a personal preference. Either way, compilers are really smart and tend to write better code than you anyways. That's to say that the compiler will likely optimize your code better than you could.

I know a lot of programmers say this, but the first thing you should do is write your code, then profile it and make optimizations where your profiler suggests you do. Your time will be much better spent producing features and then optimizing it once you can see where your bottlenecks are.

Now for some fun readings about how language features and optimizations can really work in your favor:

std::unique_ptr has zero overhead

constexp allows for compile-time computation

move semantics prevent unnecessary temporary objects

Title: Writing in C for Performance?

Body:
I know I have quite frequently heard that C typically has a performance advantage over C++. I didn't really think anything else of it until I realized that MSVC doesn't even seem to support the newest standard of C, but the newest it supports it C99 (as far as I know).

I was planning on writing a library with some code to render in OpenGL so I could reuse it. I was planning to write the library in C since any performance increase is welcome when it comes to graphics.

But would it really be worth it? The code using the library would likely be written in C++ and I prefer to code in C++ generally.

However, if it would produce even a small difference in performance, I would likely go with C.

It may also be noted that this library would be something that I would make to work across Windows/OS X/Linux, and I would likely compile everything natively (MSVC for Windows, Clang or GCC for OS X, and GCC for Linux...or possibly Intel's compilers for everything).

I've looked around and I've found some benchmarks and such, but everything I've seen has dealt with GCC rather than MSVC and Clang. Also, the benchmarks don't mention the standards of the languages used. Anyone have any thoughts on this?

EDIT: I just wanted to share my viewpoint on this question after a couple years more experience. I ended up writing the project I was asking this question for in C++. I started another project around the same time in C as we were looking to get out any small amount of performance we could and needed the project to be linkable in C. A couple months ago, I reached the point where I really needed maps and advanced string manipulation. I knew of the abilities for this in the C++ standard library and eventually came to the conclusion that those structures in the standard library would likely outperform and be more stable than maps and strings I could implement in C in a reasonable amount of time. The requirement to be linkable in C was easily satisfied by writing a C interface to the C++ code, which was done quickly with opaque types. Rewriting the library in C++ seemed to go much faster than when writing it in C and was less prone to bugs, especially memory leaks. I was also able to use the standard library threading library, which has been much easier than using platform-specific implementations. In the end, I believe writing the library in C++ led to great benefits with possibly a small performance cost. I haven't benchmarked the C++ version yet, but I believe that it may even be possible that I have gained some performance by using standard library data structures than ones I wrote.


问:
Have objects delivered in terms of code reuse?
I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?</p>

答: If it is have they delivered on their promise of code reuse so far?  Yes, if the programs written with OOP in mind apply design patterns wisely.  Otherwise, mostly no.  But looking at the popularity of large scale non trivial programs that Adobe systems, Google and the like write with C++ or Java or other OOP languages, I would say OOP has a long way to go before it phases out.  That time will be far better suited to ask this question and could help in providing ground work for a new paradigm.</p>

ContentLicense: CC BY-SA 2.5


问:
Refactoring a live system that is tightly coupled with improper data models and business logic in the front-end

Scenario

This was a project that I once had to maintain. After reading Working Effectively with Legacy Code, I started to think how I would refactor this system in a live environment, if I had to (thankfully, I didn't).

The system was a legacy system without documentation and extremely tightly coupled. Database relationships were incorrectly modelled - i.e. objects that were meant to be many-to-one were mapped as one-to-one. Using "duplication" allowed for "pseudo-many-to-one" relationships. Business logic was stored as JavaScript solely on the front-end. Data was tightly coupled to Presentation data.

As an example, a Question object could not exist without a Table Cell object. The database had a table call "TableCell" to store inline CSS for each cell which was mapped one-to-one with a "Question" object.

The system was a horrendous mess and eventually lead to loss of data and a complete re-write in the end. In total the project was about 350K LOC.

As a side note, the reason why the system was re-written (or needed refactoring) was that it was to be exposed to the Internet, but we were able to modify the business logic using the Chrome Debugger to elevate roles, inject code, and execute all sorts of undesired functions.

Question

The book used examples where the logic was placed in the middle tier. However, what happens when the business logic is placed in the front-end? From my point of view the refactor process would have to go this way:

Refactor the front-end JavaScript to understand the business logic

Refactor the middle-tier to include validation

Refactor the database to decouple the data models

Migrate the data

Refactor the middle-tier to decouple the data models

Refactor the front-end to reflect the changes in the data models.

I have read Techniques to re-factor garbage and maintain sanity? and it is helpful, but it doesn't address the order in which refactoring should occur for this specific scenario. This process seems to add a lot of redundancy as the front-end and middle-tier are refactored twice in the live system.

What is a more efficient way to refactor such a system while keeping the system live?

答:
The scenario you are talking about (and Working Effectively with Legacy Code as well) probably doesn't allow you to follow such a long term plan.  It's nice to know where you would like to get to, but typically in a live system most refactoring takes place in small steps in service of a particular bug fix or new feature.

The order of refactoring is therefore significantly determined by what business needs are high enough priority to work on.  However, for each story you work on, you will have to decide how much refactoring to take on and how to approach it, and you may well be able to slip some non (directly) business driven refactoring in as well.

When you have a choice you would give top (but not absolute) priority to not breaking things, and second priority to getting pieces of the system under test.  Both of these are higher priority than clean design, since you can clean up the design much more effectively if the system is under test.

For your specific example it's hard to predict in advance what order you would end up refactoring.  My guess is that it would mostly work down from the UI - once the UI dealt with the middle tier via a more reasonable API you would probably separate the business logic farther from the database so that you could refactor the DB and migrate data.  Hopefully by then the changed data model wouldn't be visible to the UI and wouldn't require UI changes.

But this process would probably be happening somewhat in parallel with different parts of the application, and in some of those cases might end up going in a different order.

Refactoring a live system is usually necessarily too much an opportunistic and bottom-up process to know in advance what the order will end up being.


问:
Javascript MVC application design (canvas)
I'm having difficulty grasping how to structure/architect a canvas application using an MVC like approach in Javascript. UI will be fairly fluid and animated, the games fairly simplistic but with heavy emphasis on tweening and animation. I get how MVC works in principle but not in practice. I've googled the buggery out of this, read an awful lot, and am now as confused as I was when I started.

Some details about the application area:

multi screen game framework - multiple games will sit within this framework
common UI "screens" include: settings, info, choose difficulty, main menu etc.

multiple input methods

common UI elements such as top menu bar on some screens

possibility of using different rendering methods (canvas/DOM/webGL)

At the moment I have an AppModel, AppController and AppView. From here I was planning to add each of the "screens" and attach it to the AppView. But what about things like the top menu bar, should they be another MVC triad? Where and how would I attach it without tightly coupling components?

Is it an accepted practice to have one MVC triad within another? i.e. can I add each "screen" to the AppView? Is "triad" even an accepted MVC term?!

My mind is melting under the options... I feel like I'm missing something fundamental here. I've got a solution already up and running without using an MVC approach, but have ended up with tightly coupled soup - logic and views and currently combined. The idea was to open it up and allow easier change of views (for e.g. swapping out a canvas view with a DOM based view).

Current libraries used: require.js, createJS, underscore, GSAP, hand rolled MVC implementation

Any pointers, examples etc., particularly with regards to the actual design of the thing and splitting the "screens" into proper M, V or C would be appreciated.

...or a more appropriate method other than MVC

[NB, if you've seen this question before it's because I asked it in 2 other incorrect stackexchange communities... my brain has stopped functioning]

答:
MVC has been covered in so many places so there shouldn't be much to re-iterate here. Essentially you want your object graph, helpers, and logic to be contained in the model tier. The views will be the screens that get pushed out to fill the dynamic part of the page (and may contain a light amount of logic and helpers). And the controller, which be a lightweight implementation to serve the screens based on what was available from the object graphs, helpers, and logic.

Model

This should be where the meat of the application sits. It can be tiered out into a service layer, a logic layer, and an entity layer. What does this mean for your example?

Entity layer

This should house the definitions of your game's models and internal behaviors. For example, if you had a game for minesweeper, this would be where the board and square definitions were along with how they change their internal state.

```<code>function Location(x,y){
 this.x = x;
 this.y = y;
}
function MineTile(x,y){
 this.flagged = false;
 this.hasMine = false;
 this.pristine = true;
 this.location = new Location(x,y);
}
MineTile.prototype.expose = function(){
 if( this.hasMine ) return false;
 this.pristine = false;
 return this.location;
};
</code>```

So the MineTile will know its internal state, such as if it is showing or was examined (this.pristine), if it was one of the tiles that has a mine (this.hasMine) but will not determine if it was supposed to have a mine. That will be up to the logic layer. (To go even further into OOP, MineTile could inherit from a generic Tile).

Logic layer

This should house the complex ways that the application will interact with changing modes, keeping state, etc. So this would be where a mediator pattern would be implemented in order to maintain the state of the current game. This would be where the game logic resided for determining what happens during a game over for example, or for setting up which MineTiles will have a mine. It would make calls into the Entity layer to get instantiated levels based on logically determined parameters.

```<code>var MineSweeperLogic = {
 construct: function(x,y,difficulty){
  var mineSet = [];
  var bombs = 7;
  if( difficulty === "expert" ) bombs = 15;
  for( var i = 0; i < x; i++ ){
   for( var j = 0; i j < y; j++ ){
    var mineTile = new MineTile(i,j);
    mineTile.hasMine = bombs-- > 0;
    mineSet.push(mineTile);
   }
  }
  return mineSet;
 },
 mineAt: function(x,y,mineSet){
  for( var i = 0; i < mineSet.length; i++ )
   if( mineSet[i].x === x && mineSet[i].y === y ) return mineSet[i];
 }
};
</code>```

Service layer

This will be where the controller has access to. It will have access to the logic layer for building the games. A high level call may be made into the service layer in order to retrieve a fully instantiated game or a modified game state.

```<code>function MineSweeper(x,y,difficulty){
 this.x = x;
 thix.y = y;
 this.difficulty = difficulty;
 this.mineSet = MineSweeperLogic.construct(x,y,difficulty);
}
MineSweeper.prototype.expose = function(x,y){
 return MineSweeperLogic.mineAt(x,y,this.mineSet).expose();
}
</code>```

Controller

Controllers should be light weight, essentially this is what is exposed as the client to the model. There will be many controllers, so structuring them will become important. Controller function calls will be what the javascript calls hit based on UI events. These should expose the behaviors available in the service layer and then populate or in this case modify views for the client.

```<code>function MineSweeperController(ctx){
 var this.context = ctx;
}
MineSweeperController.prototype.Start = function(x,y,difficulty){
 this.game = new MineSweeper(x,y,difficulty);
 this.view = new MineSweeperGameView(this.context,this.game.x,this.game.y,this.game.mineSet);
 this.view.Update();
};
MineSweeperController.prototype.Select = function(x,y){
 var result = this.game.expose(x,y);
 if( result === false ) this.GameOver();
 this.view.Select(result);
};
MineSweeperController.prototype.GameOver = function(){
 this.view.Summary(this.game.FinalScore());
};
</code>```

View

The views should be organized relative to the controller's behaviors. They will probably be the most intensive part of your application since it deals with canvasing.

```<code>function MineSweeperGameView(ctx,x,y,mineSet){
 this.x = x;
 this.y = y;
 this.mineSet = mineSet;
 this.context = ctx;
}
MineSweeperGameView.prototype.Update = function(){
 //todo: heavy canvas modification
 for(var mine in this.mineSet){}
 this.context.fill();
}
</code>```

So now you have your entire MVC setup for this one game. Or at least, a bare bones example, writing the whole game out would have been excessive.

Once this is all done, there will need to be a global scope for the application somewhere. This will hold the lifetime of your current controller, which is the gateway to all of the MVC stack in this scenario.

```<code>var currentGame;
var context = document.getElementById("masterCanvas").getContext('2d');
startMineSweeper.click = function(){
 currentGame = new MineSweeperController(context);
 currentGame.Start(25,25,"expert");
};
</code>```

Using MVC patterns are very powerful, but do not worry too much about adhering to every nuance of them. In the end, it is the game experience that will determine if the application is a success :)

For consideration: Don't Let Architecture Astronauts Scare You by Joel Spolsky

Body:
MVC has been covered in so many places so there shouldn't be much to re-iterate here. Essentially you want your object graph, helpers, and logic to be contained in the model tier. The views will be the screens that get pushed out to fill the dynamic part of the page (and may contain a light amount of logic and helpers). And the controller, which be a lightweight implementation to serve the screens based on what was available from the object graphs, helpers, and logic.

Model

This should be where the meat of the application sits. It can be tiered out into a service layer, a logic layer, and an entity layer. What does this mean for your example?

Entity layer

This should house the definitions of your game's models and internal behaviors. For example, if you had a game for minesweeper, this would be where the board and square definitions were along with how they change their internal state.

function Location(x,y){
 this.x = x;
 this.y = y;
}
function MineTile(x,y){
 this.flagged = false;
 this.hasMine = false;
 this.pristine = true;
 this.location = new Location(x,y);
}
MineTile.prototype.expose = function(){
 if( this.hasMine ) return false;
 this.pristine = false;
 return this.location;
};

So the MineTile will know its internal state, such as if it is showing or was examined (this.pristine), if it was one of the tiles that has a mine (this.hasMine) but will not determine if it was supposed to have a mine. That will be up to the logic layer. (To go even further into OOP, MineTile could inherit from a generic Tile).

Logic layer

This should house the complex ways that the application will interact with changing modes, keeping state, etc. So this would be where a mediator pattern would be implemented in order to maintain the state of the current game. This would be where the game logic resided for determining what happens during a game over for example, or for setting up which MineTiles will have a mine. It would make calls into the Entity layer to get instantiated levels based on logically determined parameters.

var MineSweeperLogic = {
 construct: function(x,y,difficulty){
  var mineSet = [];
  var bombs = 7;
  if( difficulty === "expert" ) bombs = 15;
  for( var i = 0; i < x; i++ ){
   for( var j = 0; i j < y; j++ ){
    var mineTile = new MineTile(i,j);
    mineTile.hasMine = bombs-- > 0;
    mineSet.push(mineTile);
   }
  }
  return mineSet;
 },
 mineAt: function(x,y,mineSet){
  for( var i = 0; i < mineSet.length; i++ )
   if( mineSet[i].x === x && mineSet[i].y === y ) return mineSet[i];
 }
};

Service layer

This will be where the controller has access to. It will have access to the logic layer for building the games. A high level call may be made into the service layer in order to retrieve a fully instantiated game or a modified game state.

function MineSweeper(x,y,difficulty){
 this.x = x;
 thix.y = y;
 this.difficulty = difficulty;
 this.mineSet = MineSweeperLogic.construct(x,y,difficulty);
}
MineSweeper.prototype.expose = function(x,y){
 return MineSweeperLogic.mineAt(x,y,this.mineSet).expose();
}

Controller

Controllers should be light weight, essentially this is what is exposed as the client to the model. There will be many controllers, so structuring them will become important. Controller function calls will be what the javascript calls hit based on UI events. These should expose the behaviors available in the service layer and then populate or in this case modify views for the client.

function MineSweeperController(ctx){
 var this.context = ctx;
}
MineSweeperController.prototype.Start = function(x,y,difficulty){
 this.game = new MineSweeper(x,y,difficulty);
 this.view = new MineSweeperGameView(this.context,this.game.x,this.game.y,this.game.mineSet);
 this.view.Update();
};
MineSweeperController.prototype.Select = function(x,y){
 var result = this.game.expose(x,y);
 if( result === false ) this.GameOver();
 this.view.Select(result);
};
MineSweeperController.prototype.GameOver = function(){
 this.view.Summary(this.game.FinalScore());
};

View

The views should be organized relative to the controller's behaviors. They will probably be the most intensive part of your application since it deals with canvasing.

function MineSweeperGameView(ctx,x,y,mineSet){
 this.x = x;
 this.y = y;
 this.mineSet = mineSet;
 this.context = ctx;
}
MineSweeperGameView.prototype.Update = function(){
 //todo: heavy canvas modification
 for(var mine in this.mineSet){}
 this.context.fill();
}

So now you have your entire MVC setup for this one game. Or at least, a bare bones example, writing the whole game out would have been excessive.

Once this is all done, there will need to be a global scope for the application somewhere. This will hold the lifetime of your current controller, which is the gateway to all of the MVC stack in this scenario.

var currentGame;
var context = document.getElementById("masterCanvas").getContext('2d');
startMineSweeper.click = function(){
 currentGame = new MineSweeperController(context);
 currentGame.Start(25,25,"expert");
};

Using MVC patterns are very powerful, but do not worry too much about adhering to every nuance of them. In the end, it is the game experience that will determine if the application is a success :)

For consideration: Don't Let Architecture Astronauts Scare You by Joel Spolsky


答:
It's not about efficiency, it's about maintaining a working system.  I like to compare refactoring to mountain climbing.  You never remove the previous safety until the next one is in place.  Yes, it's laborious.  Yes, it feels like it takes longer, but the consequences of any mistakes are much smaller.

Also, you generally want to think about refactoring in terms of vertical slices.  Do the minimum necessary to improve one small part throughout all tiers.  For example, instead of tackling the entire database at once, pick one table or even one field and go through all six steps, then repeat for another table.  You will learn things each time through that will make things easier on subsequent rounds, so make your feedback cycle as short as possible.

As a side effect, short cycles make it easier to get buy in from management.  "Remember how much my changes sped up the invoice page?  I want to do the same thing for the shopping cart, which should also make this new feature you want much quicker to add and more robust."

Title: Refactoring a live system that is tightly coupled with improper data models and business logic in the front-end

Body:
Scenario

This was a project that I once had to maintain. After reading Working Effectively with Legacy Code, I started to think how I would refactor this system in a live environment, if I had to (thankfully, I didn't).

The system was a legacy system without documentation and extremely tightly coupled. Database relationships were incorrectly modelled - i.e. objects that were meant to be many-to-one were mapped as one-to-one. Using "duplication" allowed for "pseudo-many-to-one" relationships. Business logic was stored as JavaScript solely on the front-end. Data was tightly coupled to Presentation data.

As an example, a Question object could not exist without a Table Cell object. The database had a table call "TableCell" to store inline CSS for each cell which was mapped one-to-one with a "Question" object.

The system was a horrendous mess and eventually lead to loss of data and a complete re-write in the end. In total the project was about 350K LOC.

As a side note, the reason why the system was re-written (or needed refactoring) was that it was to be exposed to the Internet, but we were able to modify the business logic using the Chrome Debugger to elevate roles, inject code, and execute all sorts of undesired functions.

Question

The book used examples where the logic was placed in the middle tier. However, what happens when the business logic is placed in the front-end? From my point of view the refactor process would have to go this way:

Refactor the front-end JavaScript to understand the business logic

Refactor the middle-tier to include validation

Refactor the database to decouple the data models

Migrate the data

Refactor the middle-tier to decouple the data models

Refactor the front-end to reflect the changes in the data models.

I have read Techniques to re-factor garbage and maintain sanity? and it is helpful, but it doesn't address the order in which refactoring should occur for this specific scenario. This process seems to add a lot of redundancy as the front-end and middle-tier are refactored twice in the live system.

What is a more efficient way to refactor such a system while keeping the system live?


问:
Suggested setup for angularJS development in Visual Studio 2013
I am starting with AngularJS.  The back end will be Web API (which is new to me as well) and I'd like to use just one IDE, so I'm trying to figure out how to setup a project in Visual Studio 2013 for AngularJS. I'd like to keep it as a separate project, to keep it loosely coupled to the API (or keep the UI decoupled from the Web API).  I'm having a hard time figuring out how to get this setup. So....

What project type is best for a pure AngularJS (pure HTML 5) project?

Is is suggested to use Grunt? Or is MS Build better to handle build tasks? I thinking here linting, minify, concatenating files into a single distribution file, maybe copying to a web server.

How do you run tests? Is there a plugin to run Jasmin tests? Do you just run Karma separately?

Are there any good templates for AngularJS? Any that use ngBoilerplate?

Any help would be appreciated.

答:
We had the same choices to make.

We decided to :

make the whole build process not depend on visual studio. We chose use tools that are considered mainstream in angular development world. This way getting support by the community is easier.

use visual studio extensions when available to enhance the experience when possible

How :

use grunt and karma. We scaffolded a project using yeoman angular and used this as a template to setup our own build process. Ours is almost as-is.

install the Web Essentials 2013 extension. The extension uses the same .jscs and .jshintrc that your grunt build uses. We decided to let Web Essentials 2013 extension handle the .less files on save so that index.html can refer to main.css and no build process is required.

make sure our visual studio editor settings are aligned with our .jscs and .jshintrc formatting rules (spacing, line ending, etc).

Also:

we run karma watch (or grunt watch) on the command-line for our tests.

attaching to running karma tests from visual studio works fine, you have to run your tests with IE. But we use the Chrome dev tools more often than not.

we don't use the jasmine web runner at all. karma has all you need.

to make things easy our app files are in /static/ inside our WebAPI project. This way you don't need another server to serve your static files.

you can use NTVS to debug grunt or karma or any other tool included in your build process, from Visual Studio.

integration with our CI (CCNet) was simple, just invoke grunt ci where ci is a task that does the build and then runs the tests using junit style reporters instead of console type reporters.

we also made sure that running the build process is optional. The build process bundles stuff in a dist folder. We run integrated tests on this folder but at dev-time, we run on raw js files (not minified or concatenated). The yeoman angular template got us there easily.

I hope this helps


问:
.properties files in regular src folder okay?
I work on a Java project with a suggested structure (separate src folders for java files and resource files).

After moving the message / text related properties files to that folder, the externalize strings mechanism in Eclipse does not work as before.

Usually when hovering over the key string in a getString("") call, the tooltip showed the content of the properties file with the default locale. That has been extremely helpful for me personally. It seems as if that feature only works if the properties file is in the same source folder as the Java code that manages the BUNDLE_NAME stuff.

Can I make a strong case for moving the properties file back to the src-folder, or should they be kept separate from the java source files? Anything else that I can try to get the feature to work again with the new structure?

答:
Don't let your tools (IDEs, frameworks, build tools, etc) dictate how you organise your code.  Don't put your properties files where eclipse wants them and don't put them where your packaging tool would like them.

Organise your code such that it is obvious what your application does and so that code and resources are as close to the things they depend on as possible. If you want to change feature foo it you should be able to find it and all of its dependencies close together not intermingled with bar. You shouldn't have to search or rely on your ide to find what you're looking for.

If your tools don't support this approach then change your tools.


问:
Scrum Daily meeting: Punctuality over Full team presence?
My understanding is that a Daily Scrum meeting should be very quick, hosted in a friendly way and that it requires all the team members present. Because it is objective is to have everyone up to date with what everybody else is doing.

I like Scrum Daily Meetings that are held like that.

In my latest project our Daily Scrums are more like a Status Update meeting. Although the position is that we are holding Scrums and practicing proper Agile.

We are a distributed team, in 2 different countries, and the people that is in the same Country are not in the same office. As consequence we have virtual Scrums.

The problem is that our meetings always start on time, many people calls before the actual start time, so they actually start at the very first second of the meeting. Without any tolerance for small delays.

For example the last time we were on the phone and the person coordinating the meeting checked if everyone was on, and we said one of our team members was not on yet but he was calling. And I was told to start sharing without waiting for my team member.

Also everyone has a lot of meetings, and sometimes they are back to back with the Scrum meeting, so it is understandable if they arrive during the first or second minute of the meeting.

Is that the normal for teams practicing Daily Scrums? It is the first time that happens to me.

I can not find any bibliography directly about it. Although the presence of all team members is stressed, it is stressed also that the meetings should always start at the same time. But I imagine there can be a small delay tolerance.

I even read on a blog someone suggesting that the Scrum Master can place penalties if someone arrives "5 seconds" late. I thought the Scrums were supposed to be friendly, and having a penalty like that seems counter productive.

What is the recommended approach in a situation like this?

答:
Is this how Scrum works?

I would suggest to you that daily meetings are too often for any business activity, unless your team is especially productive (meaning they can produce large swaths of functionality in very short time periods).

If you do decide to have daily tag-ups, they should last no longer than 15 to 20 minutes, and yes, everyone needs to be on time or they don't participate.  Tag ups are for the benefit of the team members, not the scrum master; penalties for missing daily meetings should be handled in the same fashion as any other tardiness would.

In short, I don't see anything special here.  I do think that daily meetings of any kind border on micro-management, but if you do decide to do them, you need to do them properly.


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答: Let the customer, marketing or management pick a date and then try to work backwards to an imaginary schedule</p>


答:
Like with any agile practice, scrum teams can decide this for themselves.  If it bothers you, you should bring it up in your retrospective and try to come to a solution that everyone is happy with.  Perhaps other team members feel the same way, but think that's "just how scrum is done."

That being said, in my scrum meetings I start on the second unless three or more people are missing.  For a meeting that everyone is required to attend every day, I feel it is disrespectful of everyone's time to do otherwise.  When I'm the one that shows up late, my team starts without me.  If we have time at the end, we go back to the tasks of people who came late.

I have been less strict about punctuality in the past, and what happened is people who showed up on time got tired of their time being wasted, so they started trying to guess when the meeting would actually start, and show up then instead, which had a snowball effect.

For a daily meeting, it's not the end of the world if someone occasionally misses part of it.  Hopefully it isn't the only communication you're doing throughout the day.

Title: Scrum Daily meeting: Punctuality over Full team presence?

Body:
My understanding is that a Daily Scrum meeting should be very quick, hosted in a friendly way and that it requires all the team members present. Because it is objective is to have everyone up to date with what everybody else is doing.

I like Scrum Daily Meetings that are held like that.

In my latest project our Daily Scrums are more like a Status Update meeting. Although the position is that we are holding Scrums and practicing proper Agile.

We are a distributed team, in 2 different countries, and the people that is in the same Country are not in the same office. As consequence we have virtual Scrums.

The problem is that our meetings always start on time, many people calls before the actual start time, so they actually start at the very first second of the meeting. Without any tolerance for small delays.

For example the last time we were on the phone and the person coordinating the meeting checked if everyone was on, and we said one of our team members was not on yet but he was calling. And I was told to start sharing without waiting for my team member.

Also everyone has a lot of meetings, and sometimes they are back to back with the Scrum meeting, so it is understandable if they arrive during the first or second minute of the meeting.

Is that the normal for teams practicing Daily Scrums? It is the first time that happens to me.

I can not find any bibliography directly about it. Although the presence of all team members is stressed, it is stressed also that the meetings should always start at the same time. But I imagine there can be a small delay tolerance.

I even read on a blog someone suggesting that the Scrum Master can place penalties if someone arrives "5 seconds" late. I thought the Scrums were supposed to be friendly, and having a penalty like that seems counter productive.

What is the recommended approach in a situation like this?


答:
No, its not ok to put property files into the source directory.  Some build environments could get rather unhappy with such a structure.  While yes, it may work, and the source directory may be in the class path for you in Eclipse, the best option is to have the resources in a separate directory.

Think of the build process.  This is typically 'build all the files from the source directory and put the resulting class files in another directory (target, or dist)'.  When there are property files (and other resources) mixed in there, the build gets more complex having to select another set of files to get copied to the build directory.

A much easier approach is to have source in one spot and resources in another.  This is actually the preferred directory structure that maven requires (with some directories left out):

```
src/main/java
src/main/resources
src/main/webapp
src/test/java
src/test/resources
```

This allows the tests (JUnit or TestNG) to be able to use a separate set of resources rather than the main resources and makes testing much easier.

Likewise, the webapp directory is handled specially when building a .war file.

Keeping the properties separate makes for an easier build process, a cleaner identification of the files that are needed to be part of the class path, and an easier test environment for overriding those files that are part of the main class path for testing.

Title: .properties files in regular src folder okay?

Body:
I work on a Java project with a suggested structure (separate src folders for java files and resource files).

After moving the message / text related properties files to that folder, the externalize strings mechanism in Eclipse does not work as before.

Usually when hovering over the key string in a getString("") call, the tooltip showed the content of the properties file with the default locale. That has been extremely helpful for me personally. It seems as if that feature only works if the properties file is in the same source folder as the Java code that manages the BUNDLE_NAME stuff.

Can I make a strong case for moving the properties file back to the src-folder, or should they be kept separate from the java source files? Anything else that I can try to get the feature to work again with the new structure?

Body:
No, its not ok to put property files into the source directory.  Some build environments could get rather unhappy with such a structure.  While yes, it may work, and the source directory may be in the class path for you in Eclipse, the best option is to have the resources in a separate directory.

Think of the build process.  This is typically 'build all the files from the source directory and put the resulting class files in another directory (target, or dist)'.  When there are property files (and other resources) mixed in there, the build gets more complex having to select another set of files to get copied to the build directory.

A much easier approach is to have source in one spot and resources in another.  This is actually the preferred directory structure that maven requires (with some directories left out):

src/main/java
src/main/resources
src/main/webapp
src/test/java
src/test/resources

This allows the tests (JUnit or TestNG) to be able to use a separate set of resources rather than the main resources and makes testing much easier.

Likewise, the webapp directory is handled specially when building a .war file.

Keeping the properties separate makes for an easier build process, a cleaner identification of the files that are needed to be part of the class path, and an easier test environment for overriding those files that are part of the main class path for testing.


问:
MVC: my controller seems useless half of the time. Is this a problem?
Often when I design a program with MVC, the controller is useless half of the time.

What I mean is this: something happens on the view (e.g. a button click). The view then notifies the controller. The controller then directly delegates to the model and does nothing else because it has nothing to do.

For example:

User presses button 'Color Blue' > view tells controller controller.colorBlue() > controller tells model model.colorBlue() > model colors something blue.

In this example, the controller seems useless. It adds nothing. The view might as well have talked straight to the model.

The other half of the time, however, the controller does do some kind of mediation between the view and model.

My question is this: how common is this in MVC structures? Is it reasonable that half the time my controller seems unnecessary? Or is this a problem? Is this common? How should I approach this?

If my question isn't clear enough, please say so.

答:
You're underestimating the importance of having a layer of abstraction between your User Interface and your Model.  The Controller fulfills this function 100 percent of the time.

Your example model.colorBlue() is a bit specious.  In a real model, this would probably be a CRUD method.  So your button might be a Create Customer button, your controller method would be CreateCustomer() and your Model would be CreateCustomer().  Sure, you're just passing through the call.

But what if you needed to change the way the model works?  If your View were calling your model directly, your application will break if you change the Model.  Controller methods provide an "access point" for your View; you can make a simple modification to the controller method, perhaps by changing the Model call to CreateCustomerWithVerification(), and everything still works.

The same reasoning applies for having a Service Layer.  Instead of simply having CRUD methods in your model, you should have business actions.  That way, you keep business logic out of your controllers, and make it possible to use the Model somewhere else, perhaps in a WPF application.

Think of the Controller as a "Switchyard."  It should be a go-between, mediating requests between your UI and your Model, but controller methods should have as little logic in them as possible.


问:
What is the best practice for refactoring a static method in order to make it more testable?
Let's say you have a static method that looks something like this:

```<code>public static bool Foo()
{
    var bar = new Bar();
    //do some stuff here
}
</code>```

This method as it stands can be a real headache to unit test.

What is the best practice to refactor this so that it can be testable, without turning it into an instance method or changing the method signature?

答:
Actually, you have quite a lot of options. I ran into a similar problem today and figured that it all depends on how hard it is to instantiate an object of type Bar.

Bar is easily instantiable

If Bars constructor doesn't have any Parameters or all of them are available somehow you may do the following:

Add a parameter of type Bar to Foos signature (we will fix the signature change later):

```<code>public static bool Foo(Bar bar)
{
    // ...
    var baz = bar.Baz();
    bar.Quxx(42);
    // more stuff
}
</code>```

Create an overloaded version of Foo without the Bar parameter and let it create the instance and pass it along:

```<code>public static bool Foo()
{
    return Foo(new Bar());
}
</code>```

Extract an interface IBar and use it in the signature of the new Foo method. Use the compiler errors to find out which methods and properties you need to pull up into the interface:

```<code>public interface IBar
{
    object Baz();

    void Quxx(int q);
}

public class Bar : IBar
{
    // Implementations of Baz, Quxx, and other stuff
}

public static class SomeStaticClass
{
    public static bool Foo()
    {
        return Foo(new Bar());
    }

    public static bool Foo(IBar bar)
    {
        // ...
        var baz = bar.Baz();
        bar.Quxx(42);
        // more stuff
    }
}
</code>```

Use your favourite mocking technique/framework to test the Foo method. It is still a static method and you don't need to change its callers.

It is really hard to instantiate a Bar object

But what if Bars constructor has some weird parameters. Maybe we need to pass values we compute inside of Foo. I found the following approach to be quite elegant.

We need some way to invoke Bars constructor in the production code, but want to supply some mock in testing code, so we have to introduce some indirection. Let's use the factory pattern and create a BarFactory that creates the Bar instance for us. We then pass the factory instance to the static method:

```<code>public class Bar
{
    public Bar(Baz baz, Quxx quxx)
    {
        // do stuff with baz and quxx, launch a nuclear bomb, etc.
    }
}

public class BarFactory
{
    public Bar CreateBar(Baz baz, Quxx quxx)
    {
        return new Bar(baz, quxx);
    }
}

public static class SomeStaticClass
{
    public static bool Foo(BarFactory factory)
    {
        // compute baz and quxx
        var bar = factory.CreateBar(baz, quxx);
        // use bar
    }

    public static bool Foo()
    {
        return Foo(new BarFactory());
    }
}
</code>```

As in item 3 in the above case we can now extract the IBar interface and let the compiler help us to pull up only the members we need.

Now we can extract an interface for the factory, too. The final code will look like this:

```<code>public interface IBar
{
    // IBars methods
}

public class Bar : IBar
{
    public Bar(Baz baz, Quxx quxx)
    {
        // do stuff with baz and quxx, launch a nuclear bomb, etc.
    }
}

public interface IBarFactory
{
    IBar CreateBar(Baz baz, Quxx quxx);
}

public class BarFactory : IBarFactory
{
    public IBar CreateBar(Baz baz, Quxx quxx)
    {
        return new Bar(baz, quxx);
    }
}

public static class SomeStaticClass
{
    public static bool Foo(IBarFactory factory)
    {
        // compute baz and quxx
        var bar = factory.CreateBar(baz, quxx);
        // use bar
    }

    public static bool Foo()
    {
        return Foo(new BarFactory());
    }
}
</code>```

Create mocks for IBarFactory and IBar and use them in your tests. You will have preserved Foos signature and it is still static.

Body:
Actually, you have quite a lot of options. I ran into a similar problem today and figured that it all depends on how hard it is to instantiate an object of type Bar.

Bar is easily instantiable

If Bars constructor doesn't have any Parameters or all of them are available somehow you may do the following:

Add a parameter of type Bar to Foos signature (we will fix the signature change later):

public static bool Foo(Bar bar)
{
    // ...
    var baz = bar.Baz();
    bar.Quxx(42);
    // more stuff
}

Create an overloaded version of Foo without the Bar parameter and let it create the instance and pass it along:

public static bool Foo()
{
    return Foo(new Bar());
}

Extract an interface IBar and use it in the signature of the new Foo method. Use the compiler errors to find out which methods and properties you need to pull up into the interface:

public interface IBar
{
    object Baz();

    void Quxx(int q);
}

public class Bar : IBar
{
    // Implementations of Baz, Quxx, and other stuff
}

public static class SomeStaticClass
{
    public static bool Foo()
    {
        return Foo(new Bar());
    }

    public static bool Foo(IBar bar)
    {
        // ...
        var baz = bar.Baz();
        bar.Quxx(42);
        // more stuff
    }
}

Use your favourite mocking technique/framework to test the Foo method. It is still a static method and you don't need to change its callers.

It is really hard to instantiate a Bar object

But what if Bars constructor has some weird parameters. Maybe we need to pass values we compute inside of Foo. I found the following approach to be quite elegant.

We need some way to invoke Bars constructor in the production code, but want to supply some mock in testing code, so we have to introduce some indirection. Let's use the factory pattern and create a BarFactory that creates the Bar instance for us. We then pass the factory instance to the static method:

public class Bar
{
    public Bar(Baz baz, Quxx quxx)
    {
        // do stuff with baz and quxx, launch a nuclear bomb, etc.
    }
}

public class BarFactory
{
    public Bar CreateBar(Baz baz, Quxx quxx)
    {
        return new Bar(baz, quxx);
    }
}

public static class SomeStaticClass
{
    public static bool Foo(BarFactory factory)
    {
        // compute baz and quxx
        var bar = factory.CreateBar(baz, quxx);
        // use bar
    }

    public static bool Foo()
    {
        return Foo(new BarFactory());
    }
}

As in item 3 in the above case we can now extract the IBar interface and let the compiler help us to pull up only the members we need.

Now we can extract an interface for the factory, too. The final code will look like this:

public interface IBar
{
    // IBars methods
}

public class Bar : IBar
{
    public Bar(Baz baz, Quxx quxx)
    {
        // do stuff with baz and quxx, launch a nuclear bomb, etc.
    }
}

public interface IBarFactory
{
    IBar CreateBar(Baz baz, Quxx quxx);
}

public class BarFactory : IBarFactory
{
    public IBar CreateBar(Baz baz, Quxx quxx)
    {
        return new Bar(baz, quxx);
    }
}

public static class SomeStaticClass
{
    public static bool Foo(IBarFactory factory)
    {
        // compute baz and quxx
        var bar = factory.CreateBar(baz, quxx);
        // use bar
    }

    public static bool Foo()
    {
        return Foo(new BarFactory());
    }
}

Create mocks for IBarFactory and IBar and use them in your tests. You will have preserved Foos signature and it is still static.


问:
Serpent Algorithm thats implement Cipher
How must i change the Standard Implemplementation of the Serpent Algorithm that i can use it with the javax.crypto.CipherInputStream or javax.crypto.CipherOutputStream?

I must implement/extends the Cipher class and when i do it, what must i change?

The Original Implementation of the Serpent Algorithm is here http://www.cl.cam.ac.uk/~rja14/serpent.html

Exist a Implementation of the Serpent Algorithm that's implement Cipher? I found the Java implementation of the Algorithm on the Page of its Creator. The Problem in this is: i can't use it with javax.crypto.CipherInputStream or javax.crypto.CipherOutputStream.

I try to use the ObjectOutputStream to write a Configuration File, but i would like to encrypt it with the Serpent Algorithm. The same is with the reading of this Configuration file.

I don't want to use API's like the BouncyCastle and flexiprovider because they create a to heavy boilerplate which i don't need.

What is the best practice to use a finished (final and tested) Algorithm that dont extends/implements Cipher and it should be used in javax.crypto.CipherXxxStream?

答:
Here is a walkthrough of how to implement a cipher for Java: Writing your own JCA extensions - a full cipher

The key points from the article are:

Create key classes

We will create a Caesar cipher implementation. You could also do ROT13 with it. As ciphers are about encryption/decryption we need some keys. Our key class will be very simple as we just need to store an offset for shifting our letters later on.

Start by creating a new Java Project named com.example.jce.cipher.

Implement the cipher

Ciphers are implemented extending CipherSpi (as all JCA extensions extend a WhateverSpi class).

Create a JCE provider

As for the digest, we need to usa a provider to register our digest in the JRE.

Using our provider

Create a new Java project com.example.jce.cipher.consumer. Create a subfolder libs and store your signed JAR file there. Then add this JAR to the Java Build Path.

Now everything is in place to use our cipher.

The article also mentions that you must have a certificate from Oracle to sign your cipher or the process cannot be completed.


问:
Use of MIT-Licensed OSS with GPL Dependencies
I have been assigned to audit third-party dependencies for one of my company's products to make sure we aren't in danger of running afoul of any licenses. This is probably a job for a lawyer, but such is life when you work at a small company.

At my company, we are using CS2J, an open-source project, to translate C# to Java. CS2J is itself MIT-licensed, and we use it in two ways. First, we use it as an internal tool to translate our source code from one language to another. Second, it comes with a support library (a jar file) that the translated files reference. We package this support library with our main distribution.

It turns out that the support library depends on JavaMail, a GPL-licensed product. (There's technically another license option, but it has the same copyleft clause.) I believe at one time it had something other than a GPL license, but that is no longer the case.

We had been planning on to ship the support library (CS2JSupport.jar) and JavaMail (mail.jar) as its dependency. I have a few questions:

Is CS2J allowed to be licensed under the MIT license in the first place if it's distributed with a GPL dependency?

If we are shipping mail.jar as a dependency of our dependency, does that mean the copyleft applies to us? Or does it just apply to CS2J?

We have a close relationship with the CS2J author. If we asked the CS2J author to make available a CS2JSupport.jar that had mail.jar included inside the jar, then is CS2JSupport simply a derivative work of mail.jar? And since the derivative work is covered under the MIT license instead of the GPL license, would that exempt my company from the copyleft even if we wouldn't be exempt in the situation described in #2?

答:
According to the JavaMail project's "JavaMail License" page, "[m]ost of the JavaMail source code is licensed under the CDDL license and the GPLv2 with Classpath Exception license".  The key point is that last bit - the "Classpath Exception".  That exception, common for Java libraries, is stated at the end of the license, where it says:

"CLASSPATH" EXCEPTION TO THE GPL VERSION 2

Certain source files distributed by Sun Microsystems, Inc. are subject
  to the following clarification and special exception to the GPL
  Version 2, but only where Sun has expressly included in the particular
  source file's header the words

"Sun designates this particular file as subject to the "Classpath"
  exception as provided by Sun in the License file that accompanied this
  code."

Linking this library statically or dynamically with other modules is
  making a combined work based on this library. Thus, the terms and
  conditions of the GNU General Public License Version 2 cover the whole
  combination.

As a special exception, the copyright holders of this library give you
  permission to link this library with independent modules to produce an
  executable, regardless of the license terms of these independent
  modules, and to copy and distribute the resulting executable under
  terms of your choice, provided that you also meet, for each linked
  independent module, the terms and conditions of the license of that
  module.? An independent module is a module which is not derived from
  or based on this library.? If you modify this library, you may extend
  this exception to your version of the library, but you are not
  obligated to do so.? If you do not wish to do so, delete this
  exception statement from your version.

Note that last paragraph - you can use the JavaMail library and "distribute the resulting executable under terms of your choice".  No copyleft here.