问:
The value of an updated specification
I'm at the tail end of a large project (around 5 months of my time, > 60,000 lines of code) on which I was the only developer.  The specification documents for the project were designed well early on, but as always happens during development, some things have changed.  For example:

Bugs were discovered and fixed in ways that don't correspond well with the spec

Additional needs were discovered and dealt with

We found areas where the spec hadn't thought far enough ahead and had to change some implementation

Etc.

Through all this, the spec was not kept updated, because we were lean on resources (I know that's a questionable excuse).  I'm hoping to get the spec updated soon when we have time, but it's a matter of convincing management to spend the effort.  I believe it's a good idea, but I need some good reasoning; I can't speak from very much experience because I'm only a year and a half out of school.

So here are my questions:

What value is there in keeping an updated spec?

How often should the spec be updated?  With every change made that might affect it, just at the end of development, or something in between?

EDIT to clarify: this project was internal, so no external client was involved.  It's our product.

答:
It depends.

Keeping the spec updated during development has a lot of benefits, including:

implementers, usability testers, QE, doc, etc. always know where to go for the current agreed-upon design

outside observers (e.g. managers or stakeholders) can see what you're intending to do

the team has something to look back at to figure out if things changed during implementation. Obviously this requires a version-controlled spec.

most importantly, it forces you to write down things. The process of writing things down reveals a lot of hidden assumptions.

But not every change needs to be reflected in the spec. Just like what level of detail to put in the spec in the first place, some things are just too minor. This is a judgment call, and the team will have to settle on a practice here.

Updating the spec is also extra work, of course, and so it's important to make sure that extra work is adding value. If you find yourself routinely updating the spec with no one using the result, then that's a warning flag (and might mean changing your team practices rather than holding off on spec updates).

The longer the project, the more important it is to update the spec. One hour feature? Probably can get away with just implementing it. One week? Update that spec from time to time. One month? Definitely worth it to check in repeatedly.

Finally, the larger the team, the more valuable it is to have a written spec. BUT--larger teams have a harder time of maintaining context, so the spec might not be able to stand allone: it might get misinterpreted by folks who don't understand what it all means. So it's only one piece of the puzzle.

Title: The value of an updated specification


问:
Which of these algorithms is best for my goal?
I have created a program that restricts the mouse to a certain region based on a black/white bitmap. The program is 100% functional as-is, but uses an inaccurate, albeit fast, algorithm for repositioning the mouse when it strays outside the area.

Currently, when the mouse moves outside the area, basically what happens is this:

A line is drawn between a pre-defined static point inside the region and the mouse's new position.

The point where that line intersects the edge of the allowed area is found.

The mouse is moved to that point.

This works, but only works perfectly for a perfect circle with the pre-defined point set in the exact center. Unfortunately, this will never be the case. The application will be used with a variety of rectangles and irregular, amorphous shapes. On such shapes, the point where the line drawn intersects the edge will usually not be the closest point on the shape to the mouse.

I need to create a new algorithm that finds the closest point to the mouse's new position on the edge of the allowed area. I have several ideas about this, but I am not sure of their validity, in that they may have far too much overhead.

While I am not asking for code, it might help to know that I am using Objective C / Cocoa, developing for OS X, as I feel the language being used might affect the efficiency of potential methods.

My ideas are:

Using a bit of trigonometry to project lines would work, but that would require some kind of intense algorithm to test every point on every line until it found the edge of the region... That seems too resource intensive since there could be something like 200 lines that would have each have to have as many as 200 pixels checked for black/white....

Using something like an A* pathing algorithm to find the shortest path to a black pixel; however, A* seems resource intensive, even though I could probably restrict it to only checking roughly in one direction. It also seems like it will take more time and effort than I have available to spend on this small portion of the much larger project I am working on, correct me if I am wrong and it would not be a significant amount of code (>100 lines or around there).

Mapping the border of the region before the application begins running the event tap loop. I think I could accomplish this by using my current line-based algorithm to find an edge point and then initiating an algorithm that checks all 8 pixels around that pixel, finds the next border pixel in one direction, and continues to do this until it comes back to the starting pixel. I could then store that data in an array to be used for the entire duration of the program, and have the mouse re-positioning method check the array for the closest pixel on the border to the mouse target position.

That last method would presumably execute it's initial border mapping fairly quickly. (It would only have to map between 2,000 and 8,000 pixels, which means 8,000 to 64,000 checked, and I could even permanently store the data to make launching faster.) However, I am uncertain as to how much overhead it would take to scan through that array for the shortest distance for every single mouse move event... I suppose there could be a shortcut to restrict the number of elements in the array that will be checked to a variable number starting with the intersecting point on the line (from my original algorithm), and raise/lower that number to experiment with the overhead/accuracy tradeoff.

Please let me know if I am over thinking this and there is an easier way that will work just fine, or which of these methods would be able to execute something like 30 times per second to keep mouse movement smooth, or if you have a better/faster method.

I've posted relevant parts of my code below for reference, and included an example of what the area might look like. (I check for color value against a loaded bitmap that is black/white.)

```<code>//
// This part of my code runs every single time the mouse moves.
//

CGPoint point = CGEventGetLocation(event);

float tX = point.x;
float tY = point.y;

if( is_in_area(tX,tY, mouse_mask)){

    // target is inside O.K. area, do nothing
}else{

CGPoint target;

//point inside restricted region:
float iX = 600; // inside x
float iY = 500; // inside y

// delta to midpoint between iX,iY and tX,tY
float dX;
float dY;

float accuracy = .5; //accuracy to loop until reached

do {
    dX = (tX-iX)/2;
    dY = (tY-iY)/2;

    if(is_in_area((tX-dX),(tY-dY),mouse_mask)){

        iX += dX;
        iY += dY;
    } else {

        tX -= dX;
        tY -= dY;
    }

} while (abs(dX)>accuracy || abs(dY)>accuracy);

    target = CGPointMake(roundf(tX), roundf(tY));
    CGDisplayMoveCursorToPoint(CGMainDisplayID(),target);

}
</code>```

Here is "is_in_area(int x, int y)" :

```<code>bool
is_in_area(NSInteger x, NSInteger y, NSBitmapImageRep *mouse_mask){

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSUInteger pixel[4];
    [mouse_mask getPixel:pixel atX:x y:y];

    if(pixel[0]!= 0){
        [pool release];
        return false;
    }
    [pool release];
    return true;
}
</code>```

答:
Assuming you have a reliable way to gather a discrete number of (x, y) points describing the border of your image, I would try using a combination of your first and third methods.

In which case, this is a classic example of computational geometry:

http://en.wikipedia.org/wiki/Closest_pair_problem#Planar_case

EDIT

Since one of your points is fixed, you may even be able to reduce the runtime to O(n) by just linearly stepping over your border points, computing the distance, e.g. distance = sqrt((x1-x2)^2 + (y1-y2)^2), and keeping track of the point who produced the minimum.

Perhaps there is some clever way to optimize the search over your border points?

All analytical methods I can imagine rely on your border points being representative of some continuous function, which they are not necessarily.

EDIT2

Of course, you should not be going into this search algorithm whatsoever unless your is_in_area routine fails.

ContentLicense: CC BY-SA 3.0


问:
Modern programming language with intuitive concurrent programming abstractions
I am interested in learning concurrent programming, focusing on the application/user level (not system programming). I am looking for a modern high level programming language that provides intuitive abstractions for writing concurrent applications. I want to focus on languages that increase productivity and hide the complexity of concurrent programming.

To give some examples, I don't consider a good option writing multithreaded code in C, C++, or Java because IMHO my productivity is reduced and their programming model is not intuitive. On the other hand, languages that increase productivity and offer more intuitive abstractions such as Python and the multiprocessing module, Erlang, Clojure, Scala, etc. would be good options.

What would you recommend based on your experience and why?

EDIT: Thanks everybody for your interesting answers. It's hard to make a conclusion without actually trying since there are many good candidates: Erlang, Clojure, Scala, Groovy, and perhaps Haskell. I voted the answer with the most convincing arguments, but I'll try all the good candidates before deciding which one to pick :)

答:
You could try D.  It offers three models.  I recommend either the first or second.

std.concurrency.  If you use this module for all your concurrency needs, then a combination of the language and the standard library enforces isolation between threads.  Threads primarily communicate via message passing, with limited support for shared memory in a way that favors "safety first" and disallows low-level data races.  Unfortunately the documentation of std.concurrency needs improvement, but the model is documented in a free chapter of Andrei Alexandrescu's book, "The D Programming Language".

std.parallelism.  This module is designed specifically for multicore parallelism rather than general-case concurrency.  (Concurrency and parallelism are not the same thing, though concurrency is necessary to implement parallelism.)  Since the whole point of parallelism is performance, std.parallelism doesn't make any isolation guarantees because they would make writing efficient parallel code difficult.  However, it does abstract away a lot of error-prone low-level details so that it's very hard to screw up if you're parallelizing workloads that you've manually verified are mutually independent.

core.thread is a low-level wrapper over OS-specific threading APIs.  Both std.concurrency and std.parallelism use it under the hood, but I would only recommend using it if you're writing your own concurrency library or find some ridiculous corner case that can't be done well in either std.parallelism or std.concurrency.  No one should use something this low-level for day-to-day work.


问:
Throwing and catching exceptions in the same function/method
I've written a function that asks a user for input until user enters a positive integer (a natural number). Somebody said I shouldn't throw and catch exceptions in my function and should let the caller of my function handle them.

I wonder what other developers think about this. I'm also probably misusing exceptions in the function. Here's the code in Java:

```<code>private static int sideInput()
{
    int side = 0;
    String input;
    Scanner scanner = new Scanner(System.in);

    do {
        System.out.print("Side length: ");
        input = scanner.nextLine();
        try {
            side = Integer.parseInt(input);
            if (side <= 0) {
                // probably a misuse of exceptions
                throw new NumberFormatException();
            }
        }
        catch (NumberFormatException numFormExc) {
            System.out.println("Invalid input. Enter a natural number.");
        }
    } while (side <= 0);

    return side;
}
</code>```

I'm interested in two things:

Should I let the caller worry about exceptions? The point of the function is that it nags the user until the user enters a natural number. Is the point of the function bad? I'm not talking about UI (user not being able to get out of the loop without proper input), but about looped input with exceptions handled.

Would you say the throw statement (in this case) is a misuse of exceptions? I could easily create a flag for checking validity of the number and output the warning message based on that flag. But that would add more lines to the code and I think it's perfectly readable as it is.

The thing is I often write a separate input function. If user has to input a number multiple times, I create a separate function for input that handles all formatting exceptions and limitations.

答:
This is a bad use of exceptions. To begin with, a non-positive number is not a format exception.

Why use exceptions at all? If you know what input is not allowed, just don't break out of the loop until you get valid input from the user, something like the following:

```<code>while (true)
{
   // Get user input.
   String input = scanner.nextLine();

   try
   {
      side = Integer.parseInt(input);

      break;
   }
   catch (NumberFormatException ex)
   {
      // Inform user of invalid input.
      System.out.println("Invalid input. Enter a natural number.");
   }
}
</code>```

Body:
This is a bad use of exceptions. To begin with, a non-positive number is not a format exception.

Why use exceptions at all? If you know what input is not allowed, just don't break out of the loop until you get valid input from the user, something like the following:

while (true)
{
   // Get user input.
   String input = scanner.nextLine();

   try
   {
      side = Integer.parseInt(input);

      break;
   }
   catch (NumberFormatException ex)
   {
      // Inform user of invalid input.
      System.out.println("Invalid input. Enter a natural number.");
   }
}


问:
Is it out of line to give unsolicited constructive criticism to a programmer?
I recently started work at new office that uses a proprietary program written by a solo developer. He's occasionally around as part-time tech support, but the company has signed off on this software and he's no longer being paid to develop it.

As a user of his software there are many issues that leap out to me as a source of concern:

very simple to directly view the DB as a low-privilege user

passwords stored as plaintext

dictionary admin passwords

app uses the DB root account

DB doesn't meet 1NF (eg. appointment1, appointment2, etc.)

I feel like these are serious issues and that if I were him I'd want them pointed out to me, but I'm not a qualified programmer (I'm a social worker) and I don't know if it would be rude of me to just buttonhole him and start blabbering about salted hashes and normal forms, especially when this is no longer a paid task of his.

Is it out of line? If not, how would you broach it?

Edit - more info prompted by comments:

The application holds sensitive data.

It's for internal use, but it's running on lots of machines in several cities and many visitors come through our offices.

My concerns are for the developer's future projects as well as this specific one.

答:
Don't bring it up to him. Bring it up to your bosses.

--- edit ---

Oh, and do so in writing, in an e-mail (with receipt acknowledgment on if your mail server supports it.) Keep the e-mail and all subsequent acknowledgments and receipts (print them and scan them on pdf... and keep both the pdfs and print outs.)

Because blowing the lid on the issues you just mentioned could backfire you. After all, they were written under your bosses' noses, so they are partially responsible for it (or someone up the food chain.)

That means that there is the distinctive possibility that your professional and ethical efforts to raise severe issues might not be welcomed by someone above you. So keep record of all conversations related to this issue.

For, if things hit the fan because of the security concerns, you have a record that you did your part. And by documenting everything (including the security issues), you can cover your ass when the spin doctors come into place.

ContentLicense: CC BY-SA 2.5


答:
The point of an exceptions is that it allows a method to tell that caller that entered a state where it could not continue normally, without forcing you to embed an error code in the return value.

In your case, your method knows exactly what to do when the input is not greater than 0. The only reason you are saving lines here is because you happen to be throwing the same exception you would get if the input was not a number. However, the exception you are throwing does not properly represent why your code does not like the input. If someone else were to come along and see this code, they would have to spend extra time trying to see exactly how things are working.

Title: Throwing and catching exceptions in the same function/method

Body:
I've written a function that asks a user for input until user enters a positive integer (a natural number). Somebody said I shouldn't throw and catch exceptions in my function and should let the caller of my function handle them.

I wonder what other developers think about this. I'm also probably misusing exceptions in the function. Here's the code in Java:

```<code>private static int sideInput()
{
    int side = 0;
    String input;
    Scanner scanner = new Scanner(System.in);

    do {
        System.out.print("Side length: ");
        input = scanner.nextLine();
        try {
            side = Integer.parseInt(input);
            if (side <= 0) {
                // probably a misuse of exceptions
                throw new NumberFormatException();
            }
        }
        catch (NumberFormatException numFormExc) {
            System.out.println("Invalid input. Enter a natural number.");
        }
    } while (side <= 0);

    return side;
}
</code>```

I'm interested in two things:

Should I let the caller worry about exceptions? The point of the function is that it nags the user until the user enters a natural number. Is the point of the function bad? I'm not talking about UI (user not being able to get out of the loop without proper input), but about looped input with exceptions handled.

Would you say the throw statement (in this case) is a misuse of exceptions? I could easily create a flag for checking validity of the number and output the warning message based on that flag. But that would add more lines to the code and I think it's perfectly readable as it is.

The thing is I often write a separate input function. If user has to input a number multiple times, I create a separate function for input that handles all formatting exceptions and limitations.


问:
How does throwing an ArgumentNullException help?
Let's say I have a method:

```<code>public void DoSomething(ISomeInterface someObject)
{
    if(someObject == null) throw new ArgumentNullException("someObject");
    someObject.DoThisOrThat();
}
</code>```

I've been trained to believe that throwing the ArgumentNullException is "correct" but an  "Object reference not set to an instance of an object" error means I have a bug.

Why?

I know that if I was caching the reference to someObject and using it later, then it's better to check for nullity when passed in, and fail early.  However, if I'm dereferencing it on the next line, why are we supposed to do the check?  It's going to throw an exception one way or the other.

Edit:

It just occurred to me... does the fear of the dereferenced null come from a language like C++ that doesn't check for you (i.e. it just tries to execute some method at memory location zero + method offset)?

答:
I've been trained to believe that throwing the ArgumentNullException is "correct" but an "Object reference not set to an instance of an object" error means I have a bug. Why?

Suppose I call method M(x) that you wrote. I pass null. I get an ArgumentNullException with the name set to "x". That exception unambiguously means that I have a bug; I should not have passed null for x.

Suppose I call a method M that you wrote. I pass null. I get a null deref exception. How the heck am I supposed to know whether I have a bug or you have a bug or some third party library that you called on my behalf has a bug? I know nothing about whether I need to fix my code or call you up to tell you to fix yours.

Both exceptions are indicative of bugs; neither should ever be thrown in production code.  The question is which exception communicates who has the bug better to the person doing the debugging?  Null deref exception tells you almost nothing; argument null exception tells you a lot. Be kind to your users; throw exceptions that enable them to learn from their mistakes.


答:
Exceptions are pretty nightmarish things, they bring more complexities than they solve.

Firstly, if you don't catch your exceptions, the caller can only do on error resume next, that is, after one week, even you won't know what your function can throw, and what to do with it:

```<code>{
    ...
}
catch(OutOfMemory, CorruptedMemory, BadData, DanglingPointers, UnfinishedCommit)
{
    Console.WriteLine("Nothing to see here, move on.");
    Console.WriteLine("The app is very stable, see, no crashing!");
}
</code>```

Basically, if you catch them, you have to have a very good understanding about contracts, and exception guarantees. That rarely happens in a real world. And also your code will be hard to read.

Also, the funny thing is that if you really have any chance of handling exceptions you need real RAII language, which is sort of humorous, since Java and .NET is all about exceptions...

Repeating this one more time, but...:

Link

Link

http://www.joelonsoftware.com/items/2003/10/13.html

Body:
Exceptions are pretty nightmarish things, they bring more complexities than they solve.

Firstly, if you don't catch your exceptions, the caller can only do on error resume next, that is, after one week, even you won't know what your function can throw, and what to do with it:

{
    ...
}
catch(OutOfMemory, CorruptedMemory, BadData, DanglingPointers, UnfinishedCommit)
{
    Console.WriteLine("Nothing to see here, move on.");
    Console.WriteLine("The app is very stable, see, no crashing!");
}

Basically, if you catch them, you have to have a very good understanding about contracts, and exception guarantees. That rarely happens in a real world. And also your code will be hard to read.

Also, the funny thing is that if you really have any chance of handling exceptions you need real RAII language, which is sort of humorous, since Java and .NET is all about exceptions...

Repeating this one more time, but...:

Link

Link

http://www.joelonsoftware.com/items/2003/10/13.html

ContentLicense: CC BY-SA 4.0


问:
How can I permute pairs across a set?
I am writing a bet settling app in C# and WinForms. I have 6 selections, 4 of them have won. I know that using the following formula from Excel:

```<code>=FACT(selections)/(FACT(selections-doubles))/FACT(doubles)
</code>```

This is coded into my app and working well: I can work out how many possible doubles (e.g., AB, AC, AD, AE, BC, BD, BE, etc.) need to be resolved.

But what I can't figure out is how to do the actual calculation. How can I efficiently code it so that every combination of A, B, C, and D has been calculated?

All my efforts thus far on paper have proved to be ugly and verbose: is there an elegant solution to this problem?

答:
In LINQ you could do something like:</p>

```<code>string[] items = new[] { "A", "B", "C", "D" };
var pairs = from firstIndex in Enumerable.Range(0, items.Length)
            from secondIndex in Enumerable.Range(firstIndex + 1, items.Length - firstIndex - 1)
            select new {First = items[firstIndex], Second = items[secondIndex]};
foreach(var pair in pairs)
    Console.WriteLine("{0},{1}", pair.First, pair.Second);
</code>```

Title: How can I permute pairs across a set?

Body:
In LINQ you could do something like:

string[] items = new[] { "A", "B", "C", "D" };
var pairs = from firstIndex in Enumerable.Range(0, items.Length)
            from secondIndex in Enumerable.Range(firstIndex + 1, items.Length - firstIndex - 1)
            select new {First = items[firstIndex], Second = items[secondIndex]};
foreach(var pair in pairs)
    Console.WriteLine("{0},{1}", pair.First, pair.Second);


问:
Is using Javascript/JQuery for layout and style bad practice?
Many, but not all, HTML layout problems can be solved with CSS alone.

For those that can't, JQuery (on document load) has become very popular.*

As a result of its ease, many developers are quick to use JQuery or Javascript for layout and style — even without understanding whether or not the problem can be solved with CSS alone.

This is illustrated by responses to questions like this one.

Is this bad practice?  What are the arguments for/against? Should someone who sees this in practice attempt to persuade those developers otherwise?

If so, what are the best responses to arguments in favor of JQuery saying it's "so easy"?

* Example: Layouts that wish to use vertical layout flow of some kind often run into dead ends with CSS alone — this would include layouts similar to Pinterest, though I'm not sure that's actually impossible with CSS.

答:
If the problem can be solved using CSS, it shouldn't be solved in Javascript, and it's a definitely bad practice to do so:

I guess no one has JS disabled nowadays, but NoScript is probably not completely negligible

Harder to debug and maintain

Probably will introduce a noticeable and ugly effect when JS loads and "fixes" the layout

Of course, there are things which cannot be achieved in CSS alone. In that case, of course, JS is the right solution if you strictly need it.


问:
How large is ok for a Class?
I’m a long time developer (I’m 49) but rather new to object oriented development. I’ve been reading about OO since Bertrand Meyer’s Eiffel, but have done really little OO programming.

The point is every book on OO design starts with an example of a boat, car or whatever common object we use very often, and they start adding attributes and methods, and explaining how they model the state of the object and what can be done with it.

So they usually go something like "the better the model the better it represents the object in the application and the better it all comes out".

So far so good, but, on the other hand, I’ve found several authors that give recipes such as “a class should fit in just a single page” (I would add “on what monitor size?" now that we try not to print code!).

Take for example a PurchaseOrder class, that has a finite state machine controlling its behavior and a collection of PurchaseOrderItem, one of the arguments here at work is that we should use a PurchaseOrder simple class, with some methods (little more than a data class), and have a PurchaseOrderFSM “expert class” that handles the finite state machine for the PurchaseOrder.

I would say that falls in the “Feature Envy” or “Inappropriate Intimacy” classification of Jeff Atwood's Code Smells post on Coding Horror. I’d just call it common sense. If I can issue, approve or cancel my real purchase order, then the PurchaseOrder class should have issuePO, approvePO and cancelPO methods.

Doesn’t that goes with the “maximize cohesion” and “minimize coupling” age old principles that I understand as cornerstones of OO?

Besides, doesn’t that helps toward the maintainability of the class?

答:
Say what you need in 300 lines

Note: this rule of thumb assumes you're following the 'one class per file' approach which is in its own right a good maintainability idea

It's not an absolute rule, but if I see over 200 lines of code in one class I'm suspicious.  300 lines and warning bells come on.  When I open up someone else's code and find 2000 lines, I know it's refactoring time without even reading the first page.

Mostly this comes down to maintainability.  If you object is so complex that you can't express its behavior in 300 lines, it's going to be very difficult for someone else to understand.

I'm finding that I'm bending this rule in the Model -> ViewModel -> View world where I am creating a 'behavior object' for a UI page because it often takes more than 300 lines to describe the complete series of behaviors on a page.  However I'm still new to this programming model and finding good ways of refactoring/reusing behaviors between pages/viewmodels which is gradually reducing the size of my ViewModels.

Title: How large is ok for a Class?


答:
HTML CSS and JavaScript are a nicely bundled MVC framework. HTML is the model, all your data belongs there, with some nice hooks for the view and controller. CSS is the View, all your styles belong there, possibly with some free-floating styles that can be applied by the controller. JavaScript is the Controller, all your interactions belong there, making use of hooks into the model and view (classes & ID's).

I talk about MVC too often.

Title: Is using Javascript/JQuery for layout and style bad practice?

Body:
Many, but not all, HTML layout problems can be solved with CSS alone.

For those that can't, JQuery (on document load) has become very popular.*

As a result of its ease, many developers are quick to use JQuery or Javascript for layout and style — even without understanding whether or not the problem can be solved with CSS alone.

This is illustrated by responses to questions like this one.

Is this bad practice?  What are the arguments for/against? Should someone who sees this in practice attempt to persuade those developers otherwise?

If so, what are the best responses to arguments in favor of JQuery saying it's "so easy"?

* Example: Layouts that wish to use vertical layout flow of some kind often run into dead ends with CSS alone — this would include layouts similar to Pinterest, though I'm not sure that's actually impossible with CSS.


答:
Just a legal aspect: Never.

When the spec is part of a contract, you should never change the spec. I would add notes, addendum, or change document or something similar.

At the end you may define a revised spec. The customer should give the ok during the  acceptance procedure.

Title: The value of an updated specification

Body:
I'm at the tail end of a large project (around 5 months of my time, > 60,000 lines of code) on which I was the only developer.  The specification documents for the project were designed well early on, but as always happens during development, some things have changed.  For example:

Bugs were discovered and fixed in ways that don't correspond well with the spec

Additional needs were discovered and dealt with

We found areas where the spec hadn't thought far enough ahead and had to change some implementation

Etc.

Through all this, the spec was not kept updated, because we were lean on resources (I know that's a questionable excuse).  I'm hoping to get the spec updated soon when we have time, but it's a matter of convincing management to spend the effort.  I believe it's a good idea, but I need some good reasoning; I can't speak from very much experience because I'm only a year and a half out of school.

So here are my questions:

What value is there in keeping an updated spec?

How often should the spec be updated?  With every change made that might affect it, just at the end of development, or something in between?

EDIT to clarify: this project was internal, so no external client was involved.  It's our product.


问:
Is JSF really ready to deliver high performance web applications?
I have heard a lot of good about JSF but as far as I know people also had lots of serious complains with this technology in the past, not aware of how much the situation has improved. We are considering JSF as a probable technology for a social network project. But we are not aware of the performance scores of JSF neither we could really come across any existing high performance website that had been using JSF. People complain about its performance scalability issues.

We are still not very sure if we are doing the right thing by choosing jsf, and thus would like to hear from you all about this and take your inputs into consideration.

Is it possible to configure JSF to satisfy the high performance needs of social networking service ? Also till what extent is it possible to survive with the current problems in JSF. What exactly are its problems ?

I am not  worried about the development complexities with JSF what others usually complain about because as per my personal experience I believe that's not at all true, but I am more concerned about what performance and scalability issues. And please don't just abuse it on its old issues linked to previous versions. I just care about the present state whatever had been its past.

答:
All the theoretical in the world can say JSF is wonderful, but just take a look at what your pages look like.  It produces massive piles of javascript and other crap that are going to severely handicap your ability to add in modules like jQuery or clean use of CSS.  Not saying it can't be done, but at what cost.

Personal experience with a relatively small project and medium complexity.  A disaster. It was a mess dealing with all the callbacks and you can't mix in other technologies easily.  We had a huge bug that turned out to be caused when using JSTL mixed in with JSF.  We never were able to use all the jQuery stuff due to the fact that EVERY link is a javascript callback.

Run away and run away fast.

Also when you say scale, what kind of scale are you talking about.  Number of pages, number of users, number of requests per second, number of features.  The answers to these may help you.  Also when someone tells you it needs to scale ask them to what degree and how fast.  The answer will help you tremendously.  If you are talking google scale in a week or are you talking about 1000 users and 10000 page views per day in a year.

Almost any framework, short of you typing in responses real time in the background, will scale to meet 99.999% of the use cases.


答:
What about Clojure? You can use Swing for example but enjoying Clojure concurrent programming facility?  Clojure has a pretty well Java integration.

Also, have you considered Java 7 Fork/Join framework?

Title: Modern programming language with intuitive concurrent programming abstractions

Body:
I am interested in learning concurrent programming, focusing on the application/user level (not system programming). I am looking for a modern high level programming language that provides intuitive abstractions for writing concurrent applications. I want to focus on languages that increase productivity and hide the complexity of concurrent programming.

To give some examples, I don't consider a good option writing multithreaded code in C, C++, or Java because IMHO my productivity is reduced and their programming model is not intuitive. On the other hand, languages that increase productivity and offer more intuitive abstractions such as Python and the multiprocessing module, Erlang, Clojure, Scala, etc. would be good options.

What would you recommend based on your experience and why?

EDIT: Thanks everybody for your interesting answers. It's hard to make a conclusion without actually trying since there are many good candidates: Erlang, Clojure, Scala, Groovy, and perhaps Haskell. I voted the answer with the most convincing arguments, but I'll try all the good candidates before deciding which one to pick :)


问:
Where do you put scenarios on a scrum board?
So traditional scrum board looks something like this

```<code>Backlog       |       Story    notStarted   inprogress    Done
story 1               Story1   tasks
Story 2               Story2   tasks
Story ..
Story n
Epic  x
Epic  x+1
</code>```

However in general a story has many scenarios and when working with BDD you want to write each scenario for a story as Given, when and then. Also the scenarios don't belong in the notstarted column, inprogess or Done as a scenario is not a task.

So you realize that a scenario/s should have their own column between "story" and "notstarted", as a scenario can have many task to be considered done.

If you are going to build your task from scenarios then why would you need the story on the scrum board in the first place, maybe they should be left in the backlog.

Some people put scenarios on the back of each story.

This is a on going debate in my team and I wanted to see if anyone has solved this differently.

Cheers!

答:
Scenarios are intended to let you have conversations. With scenarios, you stand a good chance of finding areas of requirements that you weren't even thinking about.

Writing things down makes your brain write them down too, and then you stop questioning. If you're writing down a scenario, it should be because:

It wasn't obvious, and you want people who come after you to understand it too

You want to be sure that you really understand the behavior of the system, and talk through an example with someone knowledgeable.

Stop worrying about the columns on the board, and think about how you actually interact with your business stakeholders and analysts.

If there's no gap in conversations, you're part of the same phase, and you don't need to differentiate this on the board.

If there's a gap, does it happen before or after you want to start work? There's no reason why business people can't talk to you before hand about the scenarios they want to play. They're not a phase of work being done; they're just an illustration of the behavior you're looking for (before you code) and a test that the behavior is there (after you code). Scenarios are a great way to question your understanding, and your business expert's translation, of requirements.

If you find for any reason that conversations with your business analyst and tester happen in a different phase to actually coding the work, try and make it closer. Ask them what it should look like and knock the GUI up, then get their feedback. Take on board what they're saying and make that the next thing you do. It'll take longer from your perspective, but the quick feedback means that whatever you produce will be ready for production in a usable form, without the knowledge of how you produced it or how you will fix any bugs degrading over time.

In short, don't worry about writing the scenarios down until you've worked out which ones are valuable by talking to people. Good luck.


问:
How to credit other authors in an open source project
I have a pet project that I am planning to release as open source at some point in the not-too-distant future. A couple of the files use or are mostly code that was taken from a project released under the New BSD License. While I have changed it to fit my needs and added some small stuff, the algorithm and the functionality is basically exactly the same.

I want to make sure that the author of the code gets credit and that the license is not broken, but I also want to make the reader aware that this is not the code as it was orignally released.

How should I approach this? Should I isolate the code as much as possible and just retain the original license? Maybe put all the files that contain foreign code in their own folder and add a readme explaining what has been added/removed?

There must have been tons of projects using other open source code. What is the standard approach to this?

答: If the files you use have (had) a header stating their origin, keep them. If they don't have, add one. You could also add an AUTHORS file to your project where you list all authors and all projects you took code from. If the code you use has a different license, it might also be good to add an extra license file for that. For instance, if you use source code of the fooBar project, add a file COPYING.fooBar to your project that contains the license of fooBar.


问:
Why do some languages recommend using spaces rather than tabs?
Maybe I'm alone in this, but few things annoy me like people indenting using spaces rather than tabs. How is typing SpaceSpaceSpaceSpace easier and more intuitive than typing Tab? Sure, tab width is variable, but it's much more indicative of indentation space than spaces. The same thing goes for backspacing; backspace once or four times?

Why do languages like Python recommend using spaces over tabs?

答:
In Python indentation controls the program flow and so is vital.

If you take code formatted with tabs and copy it so that the tabs are changed or lost the structure of the code is destroyed. Spaces are always spaces = much safer.

If  the wear and tear on your space bar worries you, your editor can probably be set to convert tabs to spaces automatically.


答:
Consistency, primarily.

Also, something occasionally comes along that actually uses the whitespace - like Python:  Tell me, what's going to happen if I run the following code snippet?

```<code>def foo():
    print "a"
    print "b"
</code>```

 Answer: You'll get an IndentationError, because those two print statements aren't indented at the same level - and so not part of the same code block. (The first one uses a tab, the second all spaces)

Then there's the frustrating cases when one developer's editor has tabs set to 8 spaces, and another has them set to 4 and someone's using 5 for some odd reason...  It may look perfectly normal on one workstation, but then when it's checked in to SVN and someone else updates, they'll see a horrid, horrid mess.

So those are two really good reasons to always be consistent, whether it be spaces or tabs.

But, spaces allow for far more control over the indentation than tabs, and don't require any special configuration in the editors for it to work.  (Although it can be made easier - for example, in vim, just use set expandtab to insert spaces whenever you hit tab)

EDIT: And amusingly enough, the site seems to have normalized my tabs into spaces so that the browser can display it correctly.  Click on "edit" to view the original, tabs included  ;)

Title: Why do some languages recommend using spaces rather than tabs?

Body:
Maybe I'm alone in this, but few things annoy me like people indenting using spaces rather than tabs. How is typing SpaceSpaceSpaceSpace easier and more intuitive than typing Tab? Sure, tab width is variable, but it's much more indicative of indentation space than spaces. The same thing goes for backspacing; backspace once or four times?

Why do languages like Python recommend using spaces over tabs?

Body:
Consistency, primarily.

Also, something occasionally comes along that actually uses the whitespace - like Python:  Tell me, what's going to happen if I run the following code snippet?

def foo():
    print "a"
    print "b"

 Answer: You'll get an IndentationError, because those two print statements aren't indented at the same level - and so not part of the same code block. (The first one uses a tab, the second all spaces)

Then there's the frustrating cases when one developer's editor has tabs set to 8 spaces, and another has them set to 4 and someone's using 5 for some odd reason...  It may look perfectly normal on one workstation, but then when it's checked in to SVN and someone else updates, they'll see a horrid, horrid mess.

So those are two really good reasons to always be consistent, whether it be spaces or tabs.

But, spaces allow for far more control over the indentation than tabs, and don't require any special configuration in the editors for it to work.  (Although it can be made easier - for example, in vim, just use set expandtab to insert spaces whenever you hit tab)

EDIT: And amusingly enough, the site seems to have normalized my tabs into spaces so that the browser can display it correctly.  Click on "edit" to view the original, tabs included  ;)


答:
Another reason to consider is what if some processing occurs before the null object is used?

Say you have a data file of associated company IDs (Cid) and person IDs (Pid).  It's saved as a stream of number pairs:

Cid Pid Cid Pid Cid Pid Cid Pid Cid Pid

And this VB function write the records to the file:

```<code>Sub WriteRecord(Company As CompanyInfo, Person As PersonInfo)
    Using File As New StringWriter(DataFileName)
        File.Write(Company.ID)
        File.Write(Person.ID)
    End Using
End Sub
</code>```

If Person is a null reference, the line File.Write(Person.ID) will throw an exception.  The software can catch the exception and recover, but this leaves a problem.  A company ID has been written without an associated person ID.  If fact, when you next call this function, your going to put a company ID where the previous person ID was expected.  As well as that record being incorrect, every subsequent record will have a person ID followed by a company ID, which is the wrong way around.

Cid Pid Cid Pid Cid Cid Pid Cid Pid Cid

By validating the parameters at the start of the function, you prevent any processing from occuring when the method is guaranteed to fail.

Title: How does throwing an ArgumentNullException help?

Body:
Let's say I have a method:

```<code>public void DoSomething(ISomeInterface someObject)
{
    if(someObject == null) throw new ArgumentNullException("someObject");
    someObject.DoThisOrThat();
}
</code>```

I've been trained to believe that throwing the ArgumentNullException is "correct" but an  "Object reference not set to an instance of an object" error means I have a bug.

Why?

I know that if I was caching the reference to someObject and using it later, then it's better to check for nullity when passed in, and fail early.  However, if I'm dereferencing it on the next line, why are we supposed to do the check?  It's going to throw an exception one way or the other.

Edit:

It just occurred to me... does the fear of the dereferenced null come from a language like C++ that doesn't check for you (i.e. it just tries to execute some method at memory location zero + method offset)?

Body:
Another reason to consider is what if some processing occurs before the null object is used?

Say you have a data file of associated company IDs (Cid) and person IDs (Pid).  It's saved as a stream of number pairs:

Cid Pid Cid Pid Cid Pid Cid Pid Cid Pid

And this VB function write the records to the file:

Sub WriteRecord(Company As CompanyInfo, Person As PersonInfo)
    Using File As New StringWriter(DataFileName)
        File.Write(Company.ID)
        File.Write(Person.ID)
    End Using
End Sub

If Person is a null reference, the line File.Write(Person.ID) will throw an exception.  The software can catch the exception and recover, but this leaves a problem.  A company ID has been written without an associated person ID.  If fact, when you next call this function, your going to put a company ID where the previous person ID was expected.  As well as that record being incorrect, every subsequent record will have a person ID followed by a company ID, which is the wrong way around.

Cid Pid Cid Pid Cid Cid Pid Cid Pid Cid

By validating the parameters at the start of the function, you prevent any processing from occuring when the method is guaranteed to fail.


答:
This is a good discussion about indentation and whitespace in Python; from the article:

[I]t can be a good idea to avoid tabs alltogether, because the semantics of tabs are not very well-defined in the computer world, and they can be displayed completely differently on different types of systems and editors. Also, tabs often get destroyed or wrongly converted during copy & paste operations, or when a piece of source code is inserted into a web page or other kind of markup code.

As to your argument about pressing the spacebar or backspace key 2 or more times, since most source code editors will insert a configurable number of spaces with a single press of the tab key, and similarly un-indent, there are no more keys pressed when using spaces for indentation.

For myself, I prefer spaces because the code is always displayed with the same amount of indentation, whether I'm viewing it in an IDE, or less, or Notepad; i.e. spaces are more portable.


问:
Avoiding bloated Domain Objects
We're trying to move data from our bloated Service layer into our Domain layer using a DDD approach. We currently have a lot of business logic in our services, which is spread out all over the place and doesn't benefit from inheritance.

We have a central Domain class which is the focus of most of our work - a Trade. The Trade object will know how to price itself, how to estimate risk, validate itself, etc. We can then replace conditionals with polymorphism. Eg: SimpleTrade will price itself one way, but ComplexTrade will price itself another.

However, we are worried that this will bloat the Trade class(s). It really should be in charge of its own processing but the class size is going to increase exponentially as more features are added.

So we have choices:

Put processing logic in Trade class. Processing logic is now polymorphic based on the type of the trade, but Trade class is now has multiple responsibilites (pricing, risk, etc) and is large

Put processing logic into other class such as TradePricingService. No longer polymorphic with the Trade inheritance tree, but classes are smaller and easier to test.

What would be the suggested approach?

答:
One possible solution I have used in a similar case, is the adapter design pattern (the referenced page contains lots of sample code). Possibly in combination with the delegation design pattern for easy access to the main methods.

Basically, you divide the Trader functionality into a number of disjunct areas - e.g. handling of prices, risks, validation all could be different areas. For each area, you can then implement a separate class hierarchy that handles that exact functionality in the different needed variants - all the a common interface for each area. The main Trader class is then reduced to the most basic data and references to a number of handler objects, that can be constructed when needed. Like

```<code>interface IPriceCalculator {
  double getPrice(ITrader t);
}
interface ITrader {
  IPriceCalculator getPriceCalculator();
}
class Tracer implements ITrader {
  private IPriceCalculator myPriceCalculator = null;
  IPriceCalculator getPriceCalculator() {
    if (myPriceCalculator == null)
      myPriceCalculator = PriceCalculatorFactory.get(this);
    return myPriceCalculator;
  }
}
</code>```

One major advantage to this approach, is that the possible combinations of e.g. prices and ricks are completely separated and can thus be combined as needed. This is rather difficult with the single-threaded inheritance of most programming languages. The decision of which combination to use can even be calculated very late :-)

I usually try to keep the adapter classes - e.g. the sub-classes of IPriceCalculator above - stateless. I.e. these classes should not contain any local data if possible, to reduce the number of instances that has to be created. So I usually provide the main adapted object as an argument in all methods - like in getPrice(ITrader) above.

OwnerDisplayName: djcredo

Title: Avoiding bloated Domain Objects

Body:
One possible solution I have used in a similar case, is the adapter design pattern (the referenced page contains lots of sample code). Possibly in combination with the delegation design pattern for easy access to the main methods.

Basically, you divide the Trader functionality into a number of disjunct areas - e.g. handling of prices, risks, validation all could be different areas. For each area, you can then implement a separate class hierarchy that handles that exact functionality in the different needed variants - all the a common interface for each area. The main Trader class is then reduced to the most basic data and references to a number of handler objects, that can be constructed when needed. Like

interface IPriceCalculator {
  double getPrice(ITrader t);
}
interface ITrader {
  IPriceCalculator getPriceCalculator();
}
class Tracer implements ITrader {
  private IPriceCalculator myPriceCalculator = null;
  IPriceCalculator getPriceCalculator() {
    if (myPriceCalculator == null)
      myPriceCalculator = PriceCalculatorFactory.get(this);
    return myPriceCalculator;
  }
}

One major advantage to this approach, is that the possible combinations of e.g. prices and ricks are completely separated and can thus be combined as needed. This is rather difficult with the single-threaded inheritance of most programming languages. The decision of which combination to use can even be calculated very late :-)

I usually try to keep the adapter classes - e.g. the sub-classes of IPriceCalculator above - stateless. I.e. these classes should not contain any local data if possible, to reduce the number of instances that has to be created. So I usually provide the main adapted object as an argument in all methods - like in getPrice(ITrader) above.

OwnerDisplayName: Tonny Madsen


答:
If you're going Domain Driven, consider treating your Trade class as an aggregate root and break its responsibilities out into other classes.

You don't want to end up with a Trade subclass for each combination of price and risk, so a Trade may contain Price and Risk objects (composition). The Price and Risk objects do the actual calculations, but aren't visible to any class except Trade. You get to reduce the size of Trade, while not exposing your new classes to the outside world.

Try to use composition to avoid large inheritance trees. Too much inheritance can lead to situations where you try to shoehorn in behaviour that doesn't really fit the model. It's better to pull those responsibilities out into a new class.

Title: Avoiding bloated Domain Objects

Body:
We're trying to move data from our bloated Service layer into our Domain layer using a DDD approach. We currently have a lot of business logic in our services, which is spread out all over the place and doesn't benefit from inheritance.

We have a central Domain class which is the focus of most of our work - a Trade. The Trade object will know how to price itself, how to estimate risk, validate itself, etc. We can then replace conditionals with polymorphism. Eg: SimpleTrade will price itself one way, but ComplexTrade will price itself another.

However, we are worried that this will bloat the Trade class(s). It really should be in charge of its own processing but the class size is going to increase exponentially as more features are added.

So we have choices:

Put processing logic in Trade class. Processing logic is now polymorphic based on the type of the trade, but Trade class is now has multiple responsibilites (pricing, risk, etc) and is large

Put processing logic into other class such as TradePricingService. No longer polymorphic with the Trade inheritance tree, but classes are smaller and easier to test.

What would be the suggested approach?

OwnerDisplayName: Terry Wilcox


问:
what to do with your bin directory
To get off my noob status i am following the Learn python the hard way course. </p>

<p>I really like it but at one point it says make a bin directory. In all games and other programs i saw to a bin directory but what does it do? </p>

答:
I don't know in what context it was mentioned in the course, but the bin directory is usually (almost always) where the binaries/executable files are located.

It is the directory which usually doesn't go under source control, and gets rewritten every time upon each new build.

I hold no sentimental value towards it.

Title: what to do with your bin directory


答: My experience is developers rarely take criticism well (who does?). Thats why there are so many heated religious arguments about anything to do with programming (best language, platform, framework). So I would just bring it up in casual conversation as you mention you have been looking at the system. </p>

Title: Is it out of line to give unsolicited constructive criticism to a programmer?

Body:
I recently started work at new office that uses a proprietary program written by a solo developer. He's occasionally around as part-time tech support, but the company has signed off on this software and he's no longer being paid to develop it.

As a user of his software there are many issues that leap out to me as a source of concern:

very simple to directly view the DB as a low-privilege user

passwords stored as plaintext

dictionary admin passwords

app uses the DB root account

DB doesn't meet 1NF (eg. appointment1, appointment2, etc.)

I feel like these are serious issues and that if I were him I'd want them pointed out to me, but I'm not a qualified programmer (I'm a social worker) and I don't know if it would be rude of me to just buttonhole him and start blabbering about salted hashes and normal forms, especially when this is no longer a paid task of his.

Is it out of line? If not, how would you broach it?

Edit - more info prompted by comments:

The application holds sensitive data.

It's for internal use, but it's running on lots of machines in several cities and many visitors come through our offices.

My concerns are for the developer's future projects as well as this specific one.


问:
How to "back track"?
I find that I start projects and, due to my lack of experience, find that old database structures and huge blocks of code are inefficient and memory-costly. However, by the time I realize a re-design of the entire project is needed, the project has grown to such a size that it is simply too late to go back and modify the project in its current state and requires a completely new project file and the whole shebang.

How should I prevent ruts such as this one, where it is too late to go back and modify the current project to fit specifications modified far down the road from the creation of the project?

(Apologies in advance for confusing grammar, it's been a long day here... as you can probably tell.)

答:
I seem to identify two common problems:

Shifting requirements

Bad database design.

What seems strange to me is that you have thorough performance problems which imply large rewrites- that is extremely unusual. If you are not profiling, when you find a performance problem it is common to try and solve the performance problems blindly, which is unlikely to work and very, very frustrating (the feeling you get is that you have rewritten everything, but things are still slow- this normally means that you haven't rewritten the important part). If you learn to use a profiler, you will find easily the true performance problems in your code and you will probably solve them easily.

Now, once that is solved, let's address the rest.

Shifting requirements are often unavoidable and often very costly. Database model design is vital.

What can you do:

Learn and practise database modelling. Learn from your mistakes. Read some books. One I would recommend which might work for you is The Data Model Resource Book, which contains typical database models for business applications. It is not a substitute for modelling theory, but it will come in handy

Devote more time to requirements gathering. Clients seldom can describe their data model in detail on their own- you need to help them- examples from the book I mentioned earlier might come in handy.

Keep your database as normalized as possible. Normalized database designs are "simpler"- although they might involve extra tables, they tend to be much easier to refactor

Use the single-responsibility principle, DRY... and other, least important software design principles :) It will drive you towards smaller, easier-to-refactor code.

Title: How to "back track"?


问:
Which tasks should a beginner, intermediate and advanced rails developer be able to complete?
I have been programming ROR for about a year now, and I think I am ready to start working on a project for someone else. The problem is that job postings for contractors don't really tell you which specific tasks you should be able to do at different experience levels (in rails and other technologies), so I don't know where to pitch myself. I think I am somewhere between junior and mid-level, but who knows? So my question is:

Which actual tasks should an junior programmer be able to do at, say, $35 an hour, which actual tasks should an intermediate programmer be able to do at, lets say, $75 an hour, and which actual tasks should an advanced programmer be able to do at, oh say, $140 an hour?

One or two examples should suffice.

答:
There is an other way to think out your hourly (at least in my head):

under expenses come:
what if i did an other job (difference) ? And costs in way of living, (10$ coffee per hour 0.10$ living in house)

under income come:
How much would you pay to do the job (minus is possible to). Last thing calculates the hearthcosts.

this way you can make a table and figure out the best option or price you ask.

But as the pro above me said: Calculating in projectsizes is way easier

OwnerDisplayName: raouldeveloper


问:
The value of an updated specification
I'm at the tail end of a large project (around 5 months of my time, > 60,000 lines of code) on which I was the only developer.  The specification documents for the project were designed well early on, but as always happens during development, some things have changed.  For example:

Bugs were discovered and fixed in ways that don't correspond well with the spec

Additional needs were discovered and dealt with

We found areas where the spec hadn't thought far enough ahead and had to change some implementation

Etc.

Through all this, the spec was not kept updated, because we were lean on resources (I know that's a questionable excuse).  I'm hoping to get the spec updated soon when we have time, but it's a matter of convincing management to spend the effort.  I believe it's a good idea, but I need some good reasoning; I can't speak from very much experience because I'm only a year and a half out of school.

So here are my questions:

What value is there in keeping an updated spec?

How often should the spec be updated?  With every change made that might affect it, just at the end of development, or something in between?

EDIT to clarify: this project was internal, so no external client was involved.  It's our product.

答:
Bugs were discovered and fixed in ways that don't correspond well with the spec

Additional needs were discovered and dealt with

We found areas where the spec hadn't thought far enough ahead and had to change some implementation

All of these cases should have sparked an RFI (Request for Information) back to the consultant/client - and no work should have been done until an amended specification was returned.

What value is there in keeping an updated spec?

How often should the spec be updated? With every change made that might affect it, just at the end of development, or something in between?

Covering your backside

If the changes were made to the software without any such amendment to the spec, then when you deliver the project you are now open to the client pointing and saying "this project isn't within specification" (this has happened on at least one project I've been on - thankfully, we had the RFIs and change documents to argue the point). You have to have the paper trail to support your change.

Having a clear change process helps in other ways - one project (not software) I was involved with had the client complain when their system was broken. We actually pulled out the specification, and the (several) documented RFIs which showed clearly that we considered the specification to need amendment, and the responses from the client saying 'just do it like we said'. The client ended up having to pay for the original project, and then a second project to patch up the original problems (suffice to say, they didn't ignore RFIs the second time round).

Changes to Costs

There's one last advantage to reviewing and updating the specification continuously - some changes will incur a major time impact on the development. This means that there may be an additional cost to bear by the client (which was the motivation for the above-mentioned client ignoring the RFIs). Since the original project timeline and price was based on the original spec - running through a change process will ensure that the client is aware of increases in time and price needed for various changes.

Title: The value of an updated specification


问:
Can the customer be a SCRUM Product Owner in a project?
I just had a discussion with a colleague about the Product Owner role: In a project where a customer organization has brought in a sofware developing organization (supplier), can the role of Product Owner be successfully held by the customer organization, or should it always be held by the supplier?

I always imagined, that the PO was the supplier organizations guy. The guy that ensured that the customer is happy, and continously fed with new and high-businessvalue functionality, but still an integral part of the developer organization. However, maybe I have viewed the PO role too much like the waterfall project manager.

My colleague made me think: If the customer organization is mature and proffessional enough, why not let a person from their camp prioritize the backlog?? That would put the PO role much closer to the business, thus being (in theory) better to assess the business value of backlog items. To me, that is an intriguing thought. But what are the implication of such a setup???

I look forward to your input.

答:
What has @Thomas Owens described is common explanation of PO. I agree with it as a nice theory but practice is in my experience often far away. Why? Because:

Willing participant - at least for duration of the project PO is fulltime job. This can be serious problem for most customers. When working with 5-7 member team, PO can easily spend half a day by discussing user stories currently developed by the team (remember user story is only promise of future communication) and half a day by maintaining and refining product backlog to define user stories for upcoming sprints. IMHO PO should also verify completed user stories during the sprint as the necessary step to make them "done" and ready for review meeting where these completed features will be presented to customer and stakeholders (not to PO!).

Moreover PO can be considered as a real job position (in the same way as Scrum Master is). In such case you cannot expect to get good skilled PO at 99% of customers.

Financial responsibility - PO has financial responsibility for the project. Even in Scrum somebody has the responsibility and because there is usually no product manager or project manager the responsiblity usually is on PO. Financial responsibility means responsibility for success of the project, for correct implementation and understanding of customer needs, expectations and requirements. This can look like ideal situation for PO on customer side but delivery organization needs somebody involved in the project with financial responsiblity as well.

Scrum is not a standardized approach - it is just a blueprint with many variants. Because of that you can find projects where PO is from customer side or where PO is from delivery organization. Once you have PO from customer side make sure that he really does his job. I have seen the situations where official PO was from customer side but at the end it was only empty title to satisfy management expectation from delivery organization and most of his job was performed by some team member who secretly played his proxy. That was obviously bad because the result of the sprint was often dependent on proxy's understanding to customers business needs!

From my experience with customers (this can be only local) once any customer really demands to have his own PO it also means they are going to lead the project themselves - they don't look for delivery organization to lead the project. They look for organization which can sell them developers = not delivering implementation but a workforce.


答:
Spaces should always be used, because tabs alone aren't sufficiently flexible for many styles, and intermixing tabs and spaces (nearly) always produces an absolute mess.

For an example of one style that generally needs spaces, consider something like:

```<code>call_some_function(parameter1,
                   parameter2,
                   parameter3,
                   parameter4,
                   parameter5,
                   parameter6,
                   parameter7);
</code>```

Unless you're willing to re-name all your functions to be an exact multiple of the tab size (minus one for the parenthesis) tabs alone simply won't do this.

As to mixing tabs and spaces, you almost immediately run into a serious problem: tabs are not consistently expanded the same way. Some software treats a tab as equivalent to a specific number of spaces. Other software will expand a tab modulo a specific number of spaces -- e.g., an item after a tab will always start at a column number that's a multiple of (say) 8.

Even if you can ensure against spaces getting mixed with your tabs, you still have a problem: tabs also play poorly with variable-width fonts. This problem arises when (for example) you want aligned trailing comments:

```<code>a.m = 9;   // this is the slope
a.i = 4;   // this is the intensity
a.x = 1;   // this is the x-intercept
</code>```

As they stand right now, those all line up perfectly. Viewed with a variable width font, however, things get ugly. With spaces, the comments may (often will) get slightly mis-aligned. With tabs, however, the misalignment often becomes quite radical:

```<code>a.m = 9;          // this is the slope
a.i = 4;  // this is the intensity
a.x = 1;          // this is the x-intercept
</code>```

Suddenly the small difference in width between the 'i' and the 'm' or 'x' in our variable-width font has been magnified to an entire tab stop.

The bottom line is that almost any change in how you view code with tabs, no matter how seemingly trivial, can and usually will produce an unreadable mess.

To answer your other questions: other have already pointed it out, but I can't imagine anybody in a programming editor (or much of anything else) actually using the space bar to insert the spaces, so your question about: "typing spacespacespacespace" is irrelevant because nobody does that to anyway. Likewise with back-spacing: it's hard to imagine an editor that would require pressing BkSpc four times to go to a previous tab stop, so (again) the question is irrelevant.

Bottom line: tabs are fine if you (and only you) will ever look at your code, and you only ever do so with a single editor that you never reconfigure (at all!) Those conditions, however, are so close to impossible to enforce that there's only one reasonable answer: never use tabs at all.

Body:
Spaces should always be used, because tabs alone aren't sufficiently flexible for many styles, and intermixing tabs and spaces (nearly) always produces an absolute mess.

For an example of one style that generally needs spaces, consider something like:

call_some_function(parameter1,
                   parameter2,
                   parameter3,
                   parameter4,
                   parameter5,
                   parameter6,
                   parameter7);

Unless you're willing to re-name all your functions to be an exact multiple of the tab size (minus one for the parenthesis) tabs alone simply won't do this.

As to mixing tabs and spaces, you almost immediately run into a serious problem: tabs are not consistently expanded the same way. Some software treats a tab as equivalent to a specific number of spaces. Other software will expand a tab modulo a specific number of spaces -- e.g., an item after a tab will always start at a column number that's a multiple of (say) 8.

Even if you can ensure against spaces getting mixed with your tabs, you still have a problem: tabs also play poorly with variable-width fonts. This problem arises when (for example) you want aligned trailing comments:

a.m = 9;   // this is the slope
a.i = 4;   // this is the intensity
a.x = 1;   // this is the x-intercept

As they stand right now, those all line up perfectly. Viewed with a variable width font, however, things get ugly. With spaces, the comments may (often will) get slightly mis-aligned. With tabs, however, the misalignment often becomes quite radical:

a.m = 9;          // this is the slope
a.i = 4;  // this is the intensity
a.x = 1;          // this is the x-intercept

Suddenly the small difference in width between the 'i' and the 'm' or 'x' in our variable-width font has been magnified to an entire tab stop.

The bottom line is that almost any change in how you view code with tabs, no matter how seemingly trivial, can and usually will produce an unreadable mess.

To answer your other questions: other have already pointed it out, but I can't imagine anybody in a programming editor (or much of anything else) actually using the space bar to insert the spaces, so your question about: "typing spacespacespacespace" is irrelevant because nobody does that to anyway. Likewise with back-spacing: it's hard to imagine an editor that would require pressing BkSpc four times to go to a previous tab stop, so (again) the question is irrelevant.

Bottom line: tabs are fine if you (and only you) will ever look at your code, and you only ever do so with a single editor that you never reconfigure (at all!) Those conditions, however, are so close to impossible to enforce that there's only one reasonable answer: never use tabs at all.


问:
Use open-source programs in your company?
Is there any cons of making your employees use open-source programs in your company?

I am planning to start a bussiness and I wonder why companies usually work with proprietary software, as Microsoft Word to quote the most famous one. Why do not they use Open Office (or Libre Office) etc.?

From my point of view, you can save a lot of money and help the open-source community by, for instance, giving them part of your benefits in form of donations.

I do not know any (medium-big) company that does this. Probably you could give me some examples, just to prove that this model of open-source usage/collaboration works rocks.

答:
There is nothing wrong in using open-source software in your company, it's free, you can adapt it to your needs and sometimes it has more support or documentation than a paid one. The only thing you should have in mind is if the project is relatively new and/or the support it has, as there can be flaws or lack of help if something don't work.

In the case of LibreOffice vs. Microsoft Office it is a matter of how many people use each one and the incompatibilities that appear when opening one format in another.

Eclipse IDE, Intellij IDEA (Community Edition), mySQL, Inkscape and Notepad++ are some widely known open-source projects. Check more open-source projects here.

And, at least for starting a business, well chosen open-source software is more than a good choice to alleviate your initiall budget.


问:
Is COBOL still worth learning?
Does learning COBOL still make sense?</p>

答: We write new Cobol code every day, and we are on a constant lookout for new programmers.  The supply is too small around here.</p>

Title: Is COBOL still worth learning?


答:
Your question definitely makes me think of the Strategy Pattern.  Then you can swap in various trading/pricing strategies, similar to what you're calling a TradePricingService.

I definitely think the advice you'll get here is to use composition instead of inheritance.

Title: Avoiding bloated Domain Objects


问:
Modern programming language with intuitive concurrent programming abstractions
I am interested in learning concurrent programming, focusing on the application/user level (not system programming). I am looking for a modern high level programming language that provides intuitive abstractions for writing concurrent applications. I want to focus on languages that increase productivity and hide the complexity of concurrent programming.

To give some examples, I don't consider a good option writing multithreaded code in C, C++, or Java because IMHO my productivity is reduced and their programming model is not intuitive. On the other hand, languages that increase productivity and offer more intuitive abstractions such as Python and the multiprocessing module, Erlang, Clojure, Scala, etc. would be good options.

What would you recommend based on your experience and why?

EDIT: Thanks everybody for your interesting answers. It's hard to make a conclusion without actually trying since there are many good candidates: Erlang, Clojure, Scala, Groovy, and perhaps Haskell. I voted the answer with the most convincing arguments, but I'll try all the good candidates before deciding which one to pick :)

答:
I'm learning about Haskell right now, and reading this paper has convinced me that Haskell is a good option for concurrent programming. Because it's purely functional (the type system knows whether a function does any input, output, or reading/modification of global state), it can do things like Software Transactional Memory (summed up very nicely in the above paper) which behaves similarly to transactions in databases - you get a bunch of nice things like atomicity with only a little extra sugar. AFAIK, Haskell threads are very light-weight too.
In addition to these things, the fact that Haskell is purely functional lets even simple tasks be run in parallel with little more than a single keyword (par). source</p>


答:
There is also another factor, usually ignored. Some software packages become eventually de-facto standard, even to the point of becoming part of the colloquial language: "a top-model photoshoped her picture", "you don't know anything about stackoverflow, then google it", "please tell me what you think and don't just copy-n-paste what you heard from the TV yesterday", or even older such as "hoover the floor". At the moment you start a business you'd just buy them without considering alternatives.

There is also the "Let me go Back" principle (I'm such a fanboy). Choosing an alternative solution might cause problems. (Personal true story follows) Once I had to fill an application for a company that (although was not a Microsoft only shop) had an application in MS-word with it's forms. OpenOffice corrupted the document after saving it. My application processing got delayed and almost lost the deadline. I remember having to find a friend with a windows PC in the middle of the night, when I saw my document there, I realised that it was unreadable for the HR-person on the other end... I asked the HR at some point why do they force me to use a windows-based PC and product. They were very polite to say to me that I was the first one that ever complained...

update: another story after the comment of @TrevorPowell, this time from the mid-90s. It's long and boring.

Back then we used floppy drives (1.44 MB per disk). This meant that for any file that was bigger than 1.44 Mb, you needed two disks to store it. But to get it to someone else safely you needed 4, the reason why was that FDs (acronym) used to fail a lot, so a second copy should be available. For bigger amounts of data you needed ZIP drives (100MB per drive). Now if the 1.46 file could be compressed to something less than 1.44, you magically needed only two (one and backup) disks. That's why compressing was so popular. At some point zip was bundled in Windows, at that time I needed to print a large Quark XPress file which would fit into 6 floppies compressed with... RAR. I remember when I showed up to print shops with 12 floppies as a kid, to get an offer, most shop owners threw me out: Where is the zip-drive (100MB). For them it was zip or one floppy. Few of those that would look at the floppies, stopped talking to me because they did not knew what a RAR was or believed that a R00 (extension) was a virus. Once one asked his "IT" guy to come, he knew what was rar but would not install it in his machines.
You can imagine that after that, I went to a friend with a... CD-writer (very rare commodity then) and we burned the uncompressed file to a cd-rom...
That was the most acceptable way to do it back then, it did the trick.

Title: Use open-source programs in your company?

Body:
Is there any cons of making your employees use open-source programs in your company?

I am planning to start a bussiness and I wonder why companies usually work with proprietary software, as Microsoft Word to quote the most famous one. Why do not they use Open Office (or Libre Office) etc.?

From my point of view, you can save a lot of money and help the open-source community by, for instance, giving them part of your benefits in form of donations.

I do not know any (medium-big) company that does this. Probably you could give me some examples, just to prove that this model of open-source usage/collaboration works rocks.


问:
How to Implement Restricted Access to Application Features
I'm currently developing a web application, that provides some 'service' to the user. The user will have to select a 'plan' according to which she/he will be allowed to perform application specific actions but up to a limit defined by the plan.

A Plan will also limit access to certain features, which will not be available at all for some plans.

As an example : say there are 3 plans, 2 actions throughout the application

users in plan-1 can perform action-1 3 times, and they can't perform
action-2 at all

users in plan-2 can perform action-1 10 times, action-2 5 times

users in plan-3 can perform action-1 20 times, action-2 10 times

So I am looking for the best way to get this done, and my main concerns besides implementing it, are the following(in no particular order)

maintainability/changeability : the number of plans, and type of features/actions will change in the final product

industry standard/best practice : for future readiness

efficiency : of course, I want fast code!!

I have never done anything like this before, so I have no clue about how do I go about implementing these functionalities. Any tips/guides/patterns/resources/examples?

I've read a little about ACL, RBAC, are they the patterns that I need to follow?

Really, any sort of feedback will help.

答:
In my own experience, this can really turn into a maintenance nightmare as things change - the maintainability will be the main issue.

I wouldn't worry too much about optimization - leave that for late in the game, as the code to filter features shouldn't run any slower than any of your other code - not likely to become a bottleneck.

For maintainability, I have a few pointers:

Build one program with a lot of switches.

Keep all feature availability as granular as possible, with each feature able to be disabled individually.  You can then build the plans as filters to decide what features are disabled, but that logic is separate and laid on top.

In the program, you should always be checking if the feature is available (simple yes/no) and NEVER if any particular plan is available.  So, feature availability is determined at run time by a boolean list for the current account, and the list is set at some point based on the plan selected, but the plan and the feature checks are NEVER crossed - each stays on it's own side of the list.

If possible, block feature access as early/macro as possible.  For example, if a feature occupies a few lines of code on a controller/class, it's sort of a pain in the butt to maintain.  If it occupies a full "page" of the site (however that breaks down in your architecture) it's much easier to block access (with page level privileges), or even access to a 'section' however that breaks down.  That way,  you're just blocking access to part of the site, rather than showing a different page with almost-the-same functionality to different users, which is less maintainable.

Try, again if possible, to avoid feature hierarchies, since you won't want to have to worry about access to sub features and that kind of thing.

Also, if possible, try not to have your features overlap.  Keep the lines between features as crisp as possible, so you don't end up disentangling them later with one switched off, but oh, wait, we need part of it.

This doesn't mean you can't have a clump of functionality considered a single feature, just make sure you will NEVER want to break itapart.  If there is any doubt, then make them multiple features.


答:
Like most here we use a mix.  The only potential con you can run into is if you have a mixed shop and some format is incompatible with someone else's tool (ex: my spreadsheet program can't read the spreadsheet you created).

It's all about communication, as long as the company can easily share information with itself then it's a non-issue.  It can become an issue if you have some people using the newest whiz-bang feature of product X, which similar product Y either screws up in presentation or doesn't understand and can't read.

Depending on how big the company is, there is a bonus to using popular tools.  For example, office workers of any flavor can walk in off the street and generally don't need help using excel/word/powerpoint, if you force them into another suite you need to be prepared for a few support calls (even if the operation is the same, they'll still call you because it "looks different").


问:
My Cassandra consultant left me and now I'm thinking about reverting to mysql
I run a middle size community and some time ago I started to develop social capabilities such as follow, status update, wall etc.

For some reason i thought that Cassandra was the right tool for the job so I looked online for a Cassandra developer and I found a very talented one.

Unluckily in the midst of the development the dev left (too much jobs) and so I'm here with a very nice class, a very nice demo, but a lot of fears that I won't be able to handle basic things such as compaction, scaling etc.

My biggest fear is to go online with all this coolness and then having a site inaccessible for hours or days.

The mysql consultant (very talented too) keeps saying me that I should stick with Mysql which I know rather well and in case something's wrong we can manage.

In that case I should take the class made for cassandra and abstract it for Mysql.

My question is this: Should I find another dev/consultant and stick with Cassandra because for social things it is definitely the best tool for the job, or should I listen to the Mysql consultant and revert to Mysql?

About 15k login each day
Average 20 actions per user
Avg 6 followers x user

(These are current statistics, but of course I'd like to increase them as much as possible.)

答:
I am not qualified to judge between MySQL and Cassandra. I know a little MySql but zero about Cassandra.

However I have seen many projects in similar situations. An investment has been made in a new technology which is not working out for whatever reason. At some stage, there is a crunch point where the decision hsa to be made on whether to make a humiliating about turn and abandon the new stuff, or,  soldier on regardless and risk getting it in late over budget, and/or full of bugs.

My experience is that the projects which had the courage to admit defeat on the technology front and put the bushiness's priorities first are much more likely to be successful in the long run.

So my advice would be "Bite the bullet" and stick with MySql. After all MySql worked for Facebook right up until the 2147483646th picture of a cute puppy was posted.


答:
The big problem is the inconsistency of the "tab" width sometimes they are rendered as four spaces sometimes eight. In many editors you can set them to be anything from 1 to 9 spaces.

So this turns a simple WYSWYG editor into a What You See is What someone else MIGHT Get.

Its a particular problem for Python, but its also a problem in any of the "curly brackets" languages as indentation is used to convey meaning to human readers and messed up tabs make the code difficult to read.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
Workstation OS freedom

If you're an open source shop, let your developers choose between Windows, Mac OS X, or their favorite flavor of Linux for their workstation.


问:
FOSS Development: Who develops the OS-specific packages?
I have a couple of FOSS projects. They can be a bit of a pain to get running unless you've got dependencies in place already, which I figure is par for the course for FOSS projects.

We know that each free operating system out there has its own package management systems. A few of them, such as homebrew on Mac OS or AUR on Arch linux are very friendly to community contributions.

What I am wondering is, who exactly is expected to contribute packages? Primarily I am concerned with the case of small or developing projects, since it's pretty standard for the big projects to be put in there by the OS maintainers.

From my perspective, it is something of a chicken-egg problem, because your software will not make its way into a package system if it does not have users, and it is less likely to gain users if it is not easy to install and use.

For the sake of discussion, let's assume that the software in question is actually legitimately useful. I can see where people could create crapware or spam and that should obviously be kept out of any package system.

So, in summary, whose job is this? Is it spammy for a FOSS software dev to put his own work into various OS package repositories?

答:
No, it certainly isn't spammy. Most packages are contributed to OS repositories by their authors, unless the author doesn't make a package for an OS, in which case the users of an OS with users of your software will create one.

Also, you should handle the OS-specific packaging stuff, and have it ready for the package repository maintainer to just 'drop in'.

For example, for Gentoo, you'll write an ebuild file (a fairly concise text file that describes the fetch and build process), then file a bug requesting for the (attached) ebuild to be added to the main portage repository.

OwnerDisplayName: achristi

OwnerDisplayName: Delan Azabani


问:
Throwing and catching exceptions in the same function/method
I've written a function that asks a user for input until user enters a positive integer (a natural number). Somebody said I shouldn't throw and catch exceptions in my function and should let the caller of my function handle them.

I wonder what other developers think about this. I'm also probably misusing exceptions in the function. Here's the code in Java:

```<code>private static int sideInput()
{
    int side = 0;
    String input;
    Scanner scanner = new Scanner(System.in);

    do {
        System.out.print("Side length: ");
        input = scanner.nextLine();
        try {
            side = Integer.parseInt(input);
            if (side <= 0) {
                // probably a misuse of exceptions
                throw new NumberFormatException();
            }
        }
        catch (NumberFormatException numFormExc) {
            System.out.println("Invalid input. Enter a natural number.");
        }
    } while (side <= 0);

    return side;
}
</code>```

I'm interested in two things:

Should I let the caller worry about exceptions? The point of the function is that it nags the user until the user enters a natural number. Is the point of the function bad? I'm not talking about UI (user not being able to get out of the loop without proper input), but about looped input with exceptions handled.

Would you say the throw statement (in this case) is a misuse of exceptions? I could easily create a flag for checking validity of the number and output the warning message based on that flag. But that would add more lines to the code and I think it's perfectly readable as it is.

The thing is I often write a separate input function. If user has to input a number multiple times, I create a separate function for input that handles all formatting exceptions and limitations.

答:
Only catch exceptions if you intend to do something that is relevant to the current method call; i.e cleanup, failure logic etc.  In this case, the catch is merely sending a message to the console, it is not relevant to sideInput method, so therefore it can be handled further up the call chain/stack.

One can get rid of the try/catch here and simply document the method call:

```<code>//Throws NumberFormatException if read input is less than 0
private static int sideInput()
</code>```

One still needs to handle that exception further up the call chain/stack!

Body:
Only catch exceptions if you intend to do something that is relevant to the current method call; i.e cleanup, failure logic etc.  In this case, the catch is merely sending a message to the console, it is not relevant to sideInput method, so therefore it can be handled further up the call chain/stack.

One can get rid of the try/catch here and simply document the method call:

//Throws NumberFormatException if read input is less than 0
private static int sideInput()

One still needs to handle that exception further up the call chain/stack!


答:
I discourage setting a hard "open-source only" rule. There are so many criteria involved in selecting software and it is a mistake to always base a decision on just one factor.

Lets assume that you will be employing, in addition to technical programmers, several non-technical staff members. Secretaries, accountants, human resources, managers, etc. How much time will be wasted when they try to learn Linux and Open Office? Especially when you're hiring business people who have spent half their lives mastering Excel, do you really want those skills to go to waste?

All other things being equal, I would choose open source every time. All other things are never equal.


问:
What is the best way to design a table with an arbitrary id?
I have the need to create a table with a unique id as the PK.  The ID is a surrogate key.  Originally, I had a natural key, but requirement changes have undermined this idea.  Then, I considered adding an auto incrementing identity.  But, this presents problems.

A.  I can't specify my own ID.

B.  The ID's are difficult to reset.

Both of these together make it difficult to copy over this table with new data or move the table across domains, e.g. Dev to QA.  I need to refer to these ID's from the front end, JavaScript...so they must not change.

So, the only way I am aware of to meet all these challenges is to make a GUID ID.  This way, I can overwrite the ID's when I need to or I can generate a new one without concern for order (E.G. an int based id would require I know the last inserted ID).

Is a GUID the best way to accomplish my goals?  Considering that a GUID is a string and joining on a string is an expensive task, is there a better way?

答:
Considering that a GUID is a string and joining on a string is an
  expensive task, is there a better way?

If you make a GUID the PK, it will be a clustered index on the table.  The reason why auto incrementing integer IDs are popular for PKs are that over time, the clustered index fragments very little, so little if any maintenance is needed on the PK.  The index is sequential.

GUIDs will work out fine, provided regular maintenance is done on the index.  If there are large amounts of inserts and deletes on the table, just make sure the process doing those inserts/deletes rebuilds the index after it completes.  Also, over time a GUID index will fragment after many inserts/updates, so just rebuild the index/PK at regular intervals to keep the queries that use it running optimally.