问:
Is there any design pattern except MVC for web?
I want to know are there any design patterns for web besides MVC?

I know there are design patterns as: Registry, Observer, Factory, ActiveRecord ,... and MVC a set of other design patterns and folder structure.

Is there design pattern like MVC is a set of other design patterns?

Edit :
my programming language is PHP.

答:
There are different patterns in software development; MVP, MVVM, MVC, etc. are some of the well-known ones. However, you have to define the specific problem or technology that you are intending to solve or use.

Each of these patterns is good to solve some specific sets of problems. For example, the MVP (Model View Presenter) pattern helps to introduce separation of concerns in ASP.NET WebForms development.  It consists of splitting up the responsibilities for gathering, displaying, and storing data from a web page into separate objects: a Model object, a View object, and a Presenter object.

The most famous general cookbook of design patterns is Gang of Four (GoF) design patterns.

Edit: i suppose that you are more interested in implementing design patterns on .NET platform


问:
When are multimethods useful in practice?
The Common Lisp Object System (CLOS) supports multiple dispatch (multimethods).  When is this a useful feature in practice?  I'm not just looking for an example of hypothetical functionality that would be easier to implement with multiple dispatch[1].  I'm looking for examples of where it's useful in real software, for any value of real that means it would  get written for something other than just an example.

[1] In programming tutorials, are examples contrived more often than not?

答:
An easy to understand example would be arithmetic, where you might have definitions
for

(plus integer integer)
(plus float integer)
(plus integer float)

and so on.

Used carefully, this can be a wonderful mechanism. Used carelessly..well, you get
what you deserve.

ContentLicense: CC BY-SA 3.0


问:
Do you estimate all user stories in iteration zero?
After our product backlog is created and prioritized, are we meant to briefly estimate all the stories in the product backlog?  I assume they have to be in order to create a product burndown chart, however if you have a lot of stories this could take a long time initially.

Additionally, should a user story have acceptance criteria when added to the backlog or are those criteria added when the story transfers from the product backlog to the sprint backlog? It would be harder to estimate without them.

答:
You don't have to estimate the entire backlog. It is ordered so you can estimate the first stories.

If you need to do a release plan and its chart, you will have to estimate enough stories to cover it. So if you want to plan 3 month ahead, then you'll have to estimate at least 3 months worth of stories.

For the management being able to plan at release level is very important.

Estimating stories is generally more quicker than estimating during the release plan and can be done at any time.


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答:
You should work back and forth between the code itself and any design documents.

You can start at code or design, and it doesn't really matter.  Read code until you're well and truly confused, then check out the design docs.  Or, read the design docs to get a high-level picture then look at the code to see what it looks like.  Repeat almost indefinitely as long as you're working with the code.

Be aware that design docs are almost always out of date, and incorrect in many ways.  However, as long as you keep these points in mind, out-of-date docs still help you understand the mind of the author at some point in the past.  Many of the high-level issues and concerns will still be valid, and you will very likely be able to more quickly understand how the code got to where it is, if you even a dated picture of where the author originally thought it was going to go.

As you work through the code and design, create your own documents that describe your understanding of the code today.  Maybe these documents are a simple sketch or two, maybe they're writeups in a wiki, maybe they're something else.  Don't make them too complicated: no 30-page word docs.  Just get your ideas down, which will clarify your own thinking greatly.

ContentLicense: CC BY-SA 2.5


答:
As ElYusubov pointed out, the ASP.Net framework has long had MVP and MVVM patterns, if you are looking for relatively mainstream examples.  One of the main differences between MVC and MVVM is how your entities are updated; MVC is better suited to the traditional stateless or semi-stateless approach of web applications.  The ASP.Net framework tried to work around this by keeping your state embedded in a form (so it could be restored on each request), which made the MVP and MVVM patterns make more sense there.

With HTML5, applications are becoming more and more JavaScript-heavy, with much of their state being on the client.  This may lead to a resurgence in MVVM frameworks, and Knockout JS is one example.

Title: Is there any design pattern except MVC for web?

Body:
I want to know are there any design patterns for web besides MVC?

I know there are design patterns as: Registry, Observer, Factory, ActiveRecord ,... and MVC a set of other design patterns and folder structure.

Is there design pattern like MVC is a set of other design patterns?

Edit :
my programming language is PHP.


答:
Most patterns in the wild are MVC, or some flavor of MVC. After all it makes sense to split up your data (Model), the representation (View) and interaction with it (Controller). If you have a look at MVC as it was founded in the 80's, you will find out it was never meant to be a web framework. Thus i found it to be far overburden in the web.

An other well known pattern would be the Service Oriented Architecture (SOA). Built on that, a modern approach would be to have an MVC (or flavor) on your server, only to expose a service you can work with. On the client side there would be an other MVC styled application, for example an HTML5 and JavaScript powered web application (Twitter or Linked In for example). The client application would use your server side service (the "View" of the server) as its Model. IMHO, this would be state of the art and will probably push server side only MVC aside.


答:
One of the most famous examples is Knockout.js which is a javascript framework which uses the MVVM design pattern.  There is a great article here over on stack overflow comparing the MVC framework Backbone.js vs Knockout.js.

A sidenote is that the MVVM design pattern originated from Microsoft as a specialization of the PM design pattern of Martin Fowler. MVVM is used extensively by WPF applications.


答:
A nice pattern, which I came accross a few weeks ago, is MOVE.
It looks a bit more sophisticated as MVC, but is based on the same principle.
One downside of MVC is your controllers can get really, really big. Using the MOVE pattern, you'll handle this issue, a little bit.

Other patterns, named by the others, are also good alternatives.


答: I'm personally looking into implementing something that uses the idea of Resource Methods Representation, though at this stage it's mostly just an experiment more than anything else.  It does have some compelling points in that it models a HTTP request/response better than MVC (which is meant for long-lived applications running on a single computer as opposed to short-lived request/response sessions).  However, it does have the drawback that if you put methods in your resources for handling GET, POST, PUT, DELETE, etc, then your resources become coupled to the front end.  I'm thinking I'm going to separate that out into another layer. </p>


问:
binary representation in Python and keeping leading zeros
I wanted to use the base64 Python library to encode a sequence of binary digits into base 64. Would it be possible to do it without converting to a string? If not, what is the best way to do it, assuming that my string of 1/0 digits may not be an integer multiple of 8, it may even be an odd number.

In addition, I have the following question: is it possible to assign a specific binary string to a variable? For example,

```<code>x = 0b00010101010
y = 0b1110000
</code>```

I want x to hold the three initial zeros, and I would like to be able to concatenate these to to obtain

```<code>z = 0b000101010101110000
</code>```

答:
Both x and y hold integer values, you just choose to use 0b binary literals to define them.

If you want to combine the two into z, you can easily do so using a shifting operation and binary bitwise operations:

```<code>>>> x = 0b00010101010
>>> y = 0b1110000
>>> z = (x << 7) | y
>>> bin(z)
'0b101010101110000'
</code>```

Do note that python does not track how many bits 'precision' you want to keep on such values; you defined y with 7 bits of information, so I had to shift x to the left 7 times to make room for y. You'd have to track this information yourself.

Your next problem is representing data as base64 as this format requires you to provide it with bytes only. That's chunks of 8 bits of binary data. This means you'll have to align your bits to the 8-bit boundaries and then turn these into bytes (e.g. strings). You won't be able to get around that, I'm afraid.

I'd use the struct module for that, it lets you pack integers and other data-types into bytes with ease:

```<code>>>> import struct
>>> struct.pack('>H', x)
'\x00\xaa'
>>> struct.pack('>H', x).encode('base64')
'AKo=\n'
</code>```

In the above example I've packed the 11-bits x variable as an unsigned short (using the little-endian standard C format), resulting in 2 bytes of information, then encoded that to base64.

The reverse then requires decoding from base64, then an unpack operation:

```<code>>>> foo = struct.unpack('>H', 'AKo=\n'.decode('base64'))[0]
>>> bin(foo)
'0b10101010'
</code>```

Again, Python doesn't track how many bits of information is important to you, you'll have to track that explicitly.

Body:
Both x and y hold integer values, you just choose to use 0b binary literals to define them.

If you want to combine the two into z, you can easily do so using a shifting operation and binary bitwise operations:

>>> x = 0b00010101010
>>> y = 0b1110000
>>> z = (x << 7) | y
>>> bin(z)
'0b101010101110000'

Do note that python does not track how many bits 'precision' you want to keep on such values; you defined y with 7 bits of information, so I had to shift x to the left 7 times to make room for y. You'd have to track this information yourself.

Your next problem is representing data as base64 as this format requires you to provide it with bytes only. That's chunks of 8 bits of binary data. This means you'll have to align your bits to the 8-bit boundaries and then turn these into bytes (e.g. strings). You won't be able to get around that, I'm afraid.

I'd use the struct module for that, it lets you pack integers and other data-types into bytes with ease:

>>> import struct
>>> struct.pack('>H', x)
'\x00\xaa'
>>> struct.pack('>H', x).encode('base64')
'AKo=\n'

In the above example I've packed the 11-bits x variable as an unsigned short (using the little-endian standard C format), resulting in 2 bytes of information, then encoded that to base64.

The reverse then requires decoding from base64, then an unpack operation:

>>> foo = struct.unpack('>H', 'AKo=\n'.decode('base64'))[0]
>>> bin(foo)
'0b10101010'

Again, Python doesn't track how many bits of information is important to you, you'll have to track that explicitly.


问:
Decorators in Python
I am just learning python, and I am currently playing with Tornado framework. I see this class:

```<code>class AuthHandler(BaseHandler, tornado.auth.GoogleMixin):
    @tornado.web.asynchronous
    def get(self):
        if self.get_argument("openid.mode", None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return
        self.authenticate_redirect()
</code>```

I am having trouble grasping what the decorator does there (@tornado.web.asynchronous). Does it overwrite that function?

You can see the full source at https://github.com/facebook/tornado/blob/master/demos/chat/chatdemo.py

答:
You can see the documentation for @tornado.web.asynchronous can be found here http://www.tornadoweb.org/documentation/web.html#tornado.web.asynchronous.

But basically it means that the method will be run asynchronously if possible.

Title: Decorators in Python


答:
Yes, it probably does, but it proprably retains a reference to the original get(self) definition.

Python decorators are nothing more than a callable themselves (a function, or a class instance with a __call__ method). Whatever that callable returns is used as the definition for the decorated function instead.

If I define a simple no-op decorator like this, that means that I replace the original with.... the original:

```<code>def noopDecorator(func):
    return func
</code>```

The @ symbol used for decorators is syntactic sugar, you could also write it as:

```<code>class AuthHandler(BaseHandler, tornado.auth.GoogleMixin):
    def get(self):
        if self.get_argument("openid.mode", None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return
        self.authenticate_redirect()
    get = tornado.web.asynchronous(get)
</code>```

In the case of the tornado asynchronous decorator, the decorator probably returns a deferred handler, to handle the decorated function asynchronously, keeping you, the programmer of a tornado-based application, from having to remember the intricacies of how to do that, time and again. In short, it let's you focus on the details of your application instead.

Title: Decorators in Python

Body:
I am just learning python, and I am currently playing with Tornado framework. I see this class:

```<code>class AuthHandler(BaseHandler, tornado.auth.GoogleMixin):
    @tornado.web.asynchronous
    def get(self):
        if self.get_argument("openid.mode", None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return
        self.authenticate_redirect()
</code>```

I am having trouble grasping what the decorator does there (@tornado.web.asynchronous). Does it overwrite that function?

You can see the full source at https://github.com/facebook/tornado/blob/master/demos/chat/chatdemo.py

Body:
Yes, it probably does, but it proprably retains a reference to the original get(self) definition.

Python decorators are nothing more than a callable themselves (a function, or a class instance with a __call__ method). Whatever that callable returns is used as the definition for the decorated function instead.

If I define a simple no-op decorator like this, that means that I replace the original with.... the original:

def noopDecorator(func):
    return func

The @ symbol used for decorators is syntactic sugar, you could also write it as:

class AuthHandler(BaseHandler, tornado.auth.GoogleMixin):
    def get(self):
        if self.get_argument("openid.mode", None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return
        self.authenticate_redirect()
    get = tornado.web.asynchronous(get)

In the case of the tornado asynchronous decorator, the decorator probably returns a deferred handler, to handle the decorated function asynchronously, keeping you, the programmer of a tornado-based application, from having to remember the intricacies of how to do that, time and again. In short, it let's you focus on the details of your application instead.


问:
Strategy/algorithm to divide pot to chips
I want to split poker pot to chips.

Example:

Pot = $17.500.

I have the endless piles of chips. I have the following types of chips: ChipsTypes = [$1, $5, $10, $25, $100, $500, $1.000, $5.000, $10.000, and so on]. Index starts from 0.

I want to get an array that says which chips I have to take to divide the pot and in which order to have minimum number of denominations and chips after pot-to-chips conversion. For example Result = [7, 5] means that I have to take 3 * $5.000 + 5 * $500 which $17.500.

Is there is any strategy or algorithm that would suit my need?

答:
A brute force approach is to modify @Chad's basic algorithm, but then once you have found a solution, start again but with one less chip in the pile of the biggest denomination left. Then rinse and repeat and throw away which ever result is less desirable. The end condition is where you run out of chip denominations, or you know you will always have more chips.

Simply trying to break chips apart doesn't take into account the divisibility of the chips, they could have no common factor (although they do in the example above).

So assuming you have to split $37 and you have some weird chips sizes:

$22, $10, $7, $1

```
Decrement 22's
22*1 + 10*1 + 7*0 + 1*5  = 37 with 7  chips

Decrement 10's
22*0 + 10*3 + 7*1 + 1*0  = 37 with 4  chips
22*0 + 10*2 + 7*2 + 1*3  = 37 with 7  chips
22*0 + 10*1 + 7*3 + 1*6  = 37 with 10 chips

Decrement 7's
22*0 + 10*0 + 7*5 + 1*2  = 37 with 7  chips
22*0 + 10*0 + 7*4 + 1*9  = 37 with 13 chips
22*0 + 10*0 + 7*3 + 1*16 = 37 with 19 chips
22*0 + 10*0 + 7*2 + 1*23 = 37 with 25 chips
22*0 + 10*0 + 7*1 + 1*30 = 37 with 31 chips
22*0 + 10*0 + 7*0 + 1*37 = 37 with 35 chips
```

Body:
A brute force approach is to modify @Chad's basic algorithm, but then once you have found a solution, start again but with one less chip in the pile of the biggest denomination left. Then rinse and repeat and throw away which ever result is less desirable. The end condition is where you run out of chip denominations, or you know you will always have more chips.

Simply trying to break chips apart doesn't take into account the divisibility of the chips, they could have no common factor (although they do in the example above).

So assuming you have to split $37 and you have some weird chips sizes:

$22, $10, $7, $1

Decrement 22's
22*1 + 10*1 + 7*0 + 1*5  = 37 with 7  chips

Decrement 10's
22*0 + 10*3 + 7*1 + 1*0  = 37 with 4  chips
22*0 + 10*2 + 7*2 + 1*3  = 37 with 7  chips
22*0 + 10*1 + 7*3 + 1*6  = 37 with 10 chips

Decrement 7's
22*0 + 10*0 + 7*5 + 1*2  = 37 with 7  chips
22*0 + 10*0 + 7*4 + 1*9  = 37 with 13 chips
22*0 + 10*0 + 7*3 + 1*16 = 37 with 19 chips
22*0 + 10*0 + 7*2 + 1*23 = 37 with 25 chips
22*0 + 10*0 + 7*1 + 1*30 = 37 with 31 chips
22*0 + 10*0 + 7*0 + 1*37 = 37 with 35 chips


问:
How I identify true error?
I am writing a program to scrap some data from the web. The pages are sequential ( 1,2,3 ... ), but I have no idea when will it stops. I combine a prefix and a integer to make a link for the python urllib to parse on it. For example : 'http://some.domain.com/page' + '1' + '.htm'.

So the request would fail if the link is invalid, however, there could be some other error such as network error, connection timed out which will resolve itself. I could retry a couple of times on these error.

Aside from 'Page not found' error, there could be other error such as 'Internal Server Error' which was thrown when the server is down. There error won't fix themselves. I should probably move on or stop the program.

Back to my program. Because I don't know when is the page index are going to end, so I set the end integer to 9999. The links may run out after some hundreds. I should identify this and send a 'break' to it.

What will you do? Gather all the possible error and put them on the exception line and treat them differently? Now I just stop after 10 failures.

答:
This is what HTTP status codes are for.

The server will return a 3-digit code together with a human-readable text, and you can tailor your exception handling to the 3-digit code. All HTTP-handling libraries should return that code with the exception if they throw one.

A 404 means Page Not Found, so you can abort your program at that moment, you probably reached the highest index number already.

The 50x errors indicate server failures, but a 502, 503 or 504 error can be temporary, so you could retry the same request (with a delay perhaps to let the server recover). The same goes for 408, but that one is seen only rarely and only from proxy servers.

Title: How I identify true error?


答:
Based on your comments in Thomas Owens answer, I would like to add some Points. I agree with his answer!

In the first (few) Sprint(s) it is just not possible to make a good estimate for the project time. Maybe you know the Cone of Uncertainty? It says:

At the beginning of a project, comparatively little is known about the product or work results, and so estimates are subject to large uncertainty.

Especially in Scrum, where you have very big and vague goals/tasks/requirements which will be specified in detail while the project is running.

You probably also know the 4 Keywords: Price, Quality, Time and Features. Standard projects will try to fixate Price, Time and Features. The quality is most likely to suffer this way. Scrum tries to fixate the Quality, by passing the variable to the Features. As you should potentially be able to ship a product after each sprint, features may be dropped or postponed in favour of other, more important ones (from the view of the customer).

Now for the estimation of the project time. You can estimate like Thomas Owens stated - maybe a few more than you expect to finish in a sprint. You may now 'guess' the rest of the work by just taking an average amount of Storypoints for the stories. The total amount of Storypoints is very unreliable, but you have your first 'guess'.

When your next sprint starts, you have estimated another set of stories. Less (or maybe more) tasks are now in your product backlog. Maybe you have already a better idea of what an average story takes. You can update your estimation now. The total amount of storypoints for your product changes. And after the third sprint maybe, you get a good idea of how much it will really take. At least you will see, if its possible to finish all the features with the current setup (based on the velocity).

Edit: forgot to mention: it is maybe better to make the product release chart a BurnUp chart.

Title: Do you estimate all user stories in iteration zero?

Body:
After our product backlog is created and prioritized, are we meant to briefly estimate all the stories in the product backlog?  I assume they have to be in order to create a product burndown chart, however if you have a lot of stories this could take a long time initially.

Additionally, should a user story have acceptance criteria when added to the backlog or are those criteria added when the story transfers from the product backlog to the sprint backlog? It would be harder to estimate without them.


问:
Should I charge a client for mistakes that I made?
After developing a website for a client, I've realized that the load time is too extreme, and some changes need to be made. The extreme load times are attributed to the bloated css/js frameworks that I've been using. Much of the code that was included with these frameworks is not even being used and is slowing the site load time. My plan is to get rid of the css framework and just use a bare bones responsive css framework which is only like 1kb in size, and just add only the code needed. So my question is, should I charge the client for back-stepping and fixing this mistake? </p>

答:
As with most cases, it depends (relation, project, etc.).

If the customer wants the slow performance to be fixed, you can send a bill in my opinion. It's your fault the performance is this slow, true, but every developer makes mistakes and customers most of the time pay for it.
They could have hired a big company with lots of (experienced?) developers who probably wouldn't have made this mistake, but the initial costs would have been much higher. Those devs would have made other mistakes and the customer would also have to suffer for that.

You've delivered a piece of software and they have probably agreed on it.
Now they want it changed, well, that's a request for change, which will cost money. If you initially hadn't used these (bloated) frameworks, the job would have taken a lot more time/money.

If it's a fixed price project, it'll be a fixed in a new (minor) version. Depending on the contract, people can pay for upgrades.

In a different scenario/example, you've chosen a certain IoC/DI framework in your project. After a few months you discover it's performing very slow compared to a different framework. What would you do? I'd let the customer know that I can speed up the system by changing some internals of the system which will cost X dollar. They can decide if they want it or not.

In short: I'd say they have to pay for upgrades on the system, but it really depends on the situation.


问:
What is the term for this type of refactoring
I am sure there is a term for the following bit of refactoring, but I can't remember it and my Google-fu is failing me!

The refactor moves if statements to where they are going to have most impact, for example changing this

```<code>$test = someFunctionThatReturnsABool();
for($x = 0; $x < 10000; $x++) {
    if ($test) {
        echo $x;
    }
}
</code>```

To this

```<code>$test = someFunctionThatReturnsABool();
if ($test) {
    for($x = 0; $x < 10000; $x++) {
        echo $x;
    }
}
</code>```

答:
This is loop-invariant code motion. A good compiler should do it on its own.

...loop-invariant code consists of statements or expressions (in an imperative programming language) which can be moved outside the body of a loop without affecting the semantics of the program. Loop-invariant code motion (also called hoisting or scalar promotion) is a compiler optimization which performs this movement automatically...

If we consider the following code sample, two optimizations can be easily applied.

```<code>for (int i = 0; i < n; i++) {
    x = y + z;
    a[i] = 6 * i + x * x;
}
</code>```

The calculation x = y + z and x * x can be moved outside the loop since within they are loop invariant — they do not change over the iterations of the loop— so the optimized code will be something like this:

```<code>x = y + z;
t1 = x * x;
for (int i = 0; i < n; i++) {
    a[i] = 6 * i + t1;
}
</code>```

This code can be optimized further...

Body:
This is loop-invariant code motion. A good compiler should do it on its own.

...loop-invariant code consists of statements or expressions (in an imperative programming language) which can be moved outside the body of a loop without affecting the semantics of the program. Loop-invariant code motion (also called hoisting or scalar promotion) is a compiler optimization which performs this movement automatically...

If we consider the following code sample, two optimizations can be easily applied.

for (int i = 0; i < n; i++) {
    x = y + z;
    a[i] = 6 * i + x * x;
}

The calculation x = y + z and x * x can be moved outside the loop since within they are loop invariant — they do not change over the iterations of the loop— so the optimized code will be something like this:

x = y + z;
t1 = x * x;
for (int i = 0; i < n; i++) {
    a[i] = 6 * i + t1;
}

This code can be optimized further...


答:
Looks like a variant of Remove Control Flag (pp 245 of Fowler's Refactoring)

A PHP example can be found on DZone.

Title: What is the term for this type of refactoring

Body:
I am sure there is a term for the following bit of refactoring, but I can't remember it and my Google-fu is failing me!

The refactor moves if statements to where they are going to have most impact, for example changing this

```<code>$test = someFunctionThatReturnsABool();
for($x = 0; $x < 10000; $x++) {
    if ($test) {
        echo $x;
    }
}
</code>```

To this

```<code>$test = someFunctionThatReturnsABool();
if ($test) {
    for($x = 0; $x < 10000; $x++) {
        echo $x;
    }
}
</code>```


问:
Should I use switch statements or long if...else chains?
Often when I hear about the switch statement, its put off as a way to replace long if...else chains. But it seems that when I use the switch statement I'm writing more code that I would be just writing if...else. You also have other issues like keeping all variables for all calls in the same scope.

Here's some code that represents the flow I normally write (thanks to diam)

```<code>String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

if (which == 0) {
    comment = "You look so much better than usual.";
} else if (which == 1) {
    comment = "Your work is up to its usual standards.";
} else if (which == 2) {
    comment = "You're quite competent for so little experience.";
} else {
    comment = "Oops -- something is wrong with this code.";
}
</code>```

Then they want me to replace that with this:

```<code>String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

switch (which) {
    case 0:
             comment = "You look so much better than usual.";
    break;
    case 1:
             comment = "Your work is up to its usual standards.";
    break;
    case 2:
             comment = "You're quite competent for so little experience.";
    break;
    default:
             comment = "Oops -- something is wrong with this code.";
}
</code>```

Seems like a lot more code in a much more awkward syntax. But is there really an advantage to using the switch statement?

答:
I agree with Jerry that an array of strings is better for this particular case, but that in general it's better to use a switch/case statement than a chain of elseifs.  It's easier to read, and sometimes the compiler can do a better job of optimizing that way, but there's another benefit as well: it's a heck of a lot easier to debug.

When you hit that switch, you only have to step one time to end up on the right branch, instead of carefully stepping over several if statements one at a time, and possibly hitting the key too quickly and stepping past it and missing something and having to start over.


问:
How to get developers to do code reviews in a timely manner
The company I work for requires all code to be reviewed by other developers before it is committed.  The members of my team are often frustrated because the other developers are too busy coding to do a review, especially if it is very long.  How do you incentivize other developers to do timely code reviews?

(We use git-svn so we are able to continue coding while waiting for a review.  However, I still find it frustrating when I have to wait a long time before I can commit my code.)

答:
You have a number of issues to address - you have to win hearts and minds and you have to ensure that time is available for code reviews.

The second part is probably easiest - you agree (collectively and that has to include management) that the first thing a dev does each morning is their code reviews - this is simple, understandable, effective and gives you a nice clear stick to beat people with if they don't comply. Better, you're not interrupting anything, you're not asking them to stop working on their code you're not asking people to squeeze something into their to-do list...

The first part is the real problem - the participants in the review process have to see it as having value otherwise they'll never do a code review (which is percieved as not having value) when they could be writing code or fixing bugs (which is surely more important...?).

If you can put the two together - firstly ensuring that everyone believes (or understands) that there is value in the code reviews - at the most basic it should mean fewer bugs which means more new code which is usually more fun - and then secondly arranging things so that there is a clear space in the schedule for the code reviews to be done then hopefully good things will happen... it will become part of the culture.

Once its part of the culture it may no longer be necessary to say "first thing every day" - but having said that I think that it fits well into the pattern one probably wants a dev to work in.


问:
How to store data in Gujarati language in SQLite?
I am developing an Android application for Gujarat's farmers. So this app should be in Gujarati also.

Is there any way so that I can store my data in Gujarati in SQLite?

答:
Yes. Just store those strings.

Sqlite always works with unicode strings. Java String is also unicode. So everything should work out of the box. If it does not, than say what that is.

Internally sqlite encodes all strings either in utf-8 or utf-16 (there is a per-database option), but since it always converts them as needed (to one or other for comparison and to/from java.lang.String in the API), you don't even need to care.


答:
I'm going to base this on a couple of assumptions:

Everyone seems to want to write code (If not, you have people that need to go.).

Everyone wants their own code to be checked in.

Only allow those who complete their reviews to have their code checked in.

Maybe a certain block of time can be dedicated to code reviews in hopes of avoiding the problem of being interupted.

The goal should be to check in quality code. You don't want to punish/force the reviews to the point where everyone just gives it a "rubber stamp" approval.

If you have different levels (jr., sr. etc), promotion and maintaining a title should be contingent on doing your job.

Title: How to get developers to do code reviews in a timely manner

Body:
The company I work for requires all code to be reviewed by other developers before it is committed.  The members of my team are often frustrated because the other developers are too busy coding to do a review, especially if it is very long.  How do you incentivize other developers to do timely code reviews?

(We use git-svn so we are able to continue coding while waiting for a review.  However, I still find it frustrating when I have to wait a long time before I can commit my code.)


答:
Consider using a tool like Review Board. It is very helpful, especially for long reviews.

You can upload your diffs and wait until a reviewer has finished their review.
If you have open reviews that prevent you from continuing your work you can report this during your daily meetings (your team want new features to be checked in so that they can be tested as soon as possible, don't they?).


问:
understanding the encoding scheme in python 3
I got this error in my program which grab data from different website and write them to a file:

```<code>'charmap' codec can't encode characters in position 151618-151624: character maps to <undefined>
</code>```

I am not familiar with all the encoding decoding thing and I have been okay with what python 2 did. Although the python officially said that they made the change in order to make things better, it seems to get worse.

I have no idea how to fix these errors. However I am a pro-active person so I would really like to know what is causing the problem and how to solve it. I have check the official site but the words are hard to understand.

Could I have a simple elaboration on that? Another page is also acceptable.

EDIT:
I've check this page, the Unicode HOWTO in Python 2.7. My understanding is that we must translate the unicode string into binary format while we're writing it to file and it require an encoding. Obviously 'utf-8' is the best one, but why it didn't force the python interpreter to use 'utf-8'? Instead, it use some strange codec such as 'charmap' and 'cp950' and 'latin-1'.

答:
See the Python wiki on the subject. You are trying to encode a unicode string (the default string type in Python 3) with an encoding that doesn't support some of the characters in your string.

```<code>>>> '\u0411'.encode("iso-8859-15")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/iso8859_15.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode character '\u0411' in position 0: character maps to <undefined>
>>> '\u0411\u0411\u0411\u0411\u0411'.encode("iso-8859-15")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/iso8859_15.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-4: character maps to <undefined>
</code>```

As you can see, some encodings use a charactermap internally, and detect encoding errors for multiple characters at once.

You'll have to narrow it down to the exact code points (characters in position 151618-151624) and the encoding used.

Body:
See the Python wiki on the subject. You are trying to encode a unicode string (the default string type in Python 3) with an encoding that doesn't support some of the characters in your string.

>>> '\u0411'.encode("iso-8859-15")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/iso8859_15.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode character '\u0411' in position 0: character maps to <undefined>
>>> '\u0411\u0411\u0411\u0411\u0411'.encode("iso-8859-15")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/iso8859_15.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-4: character maps to <undefined>

As you can see, some encodings use a charactermap internally, and detect encoding errors for multiple characters at once.

You'll have to narrow it down to the exact code points (characters in position 151618-151624) and the encoding used.


答:
The first thing to establish is what exactly you need to do, to decide whether or not a framework and/or MVC (or other design pattern) would be of benefit.

Frameworks are there to provide a consistent platform for development whilst usually providing solutions to common programming requirements (such as Database interaction, form creation and validation, user authentication etc.)

For PHP at least the MVC / HMVC design pattern does tend to dominate the mainstream frameworks available (e.g. Zend, CakePHP, CodeIgniter etc.) but there are many different design patterns that one could use.

MVC is so popular because it offers an established and understood way of separating data modelling and processing logic from view/presentation layer (something which is considered desirable in order to produce robust, scalable applications).

It's important to note (and as was expressed by @Marjan Venema in a comment to @ElYusubov's answer) that MVC, MVP, MVVM and the other MVx patterns are (in principal at least) all the same 'design pattern'.

Typically different design patterns all serve (often subtly) different purposes and in several cases were developed with a specific language in mind. However a true 'design pattern' is not a hard and fast rule to programming and is really more of a philosophical / idealogical understanding of a programs implementation and design requirements and logical function(s).

Research is the best way to find out about different programming principals and best practices, here's some Wikipedia links to get you started:

Design Pattern

Design by Contract

Software Design Pattern

Architectural Pattern

Interactional Design Pattern

In practice there's nothing stopping you from implementing your own 'pattern', IMO the best way is to learn by doing, for me at least I didn't fully understand the MVC pattern until I started trying to write a web site using it.

Once you understand some of the programming concepts and best practices you can use those to build your own system to solve the specific problems you're facing and to meet your needs, whether it conforms to an established 'pattern' or not.

If you have no specific set of problems to solve then learning one of the common frameworks is your best bet.


答:
In general this problem can be stated as integer programming problem. So the task is

x_i = how many chip type i you have

maximize:

sum(-x_i)

subject to:

sum(chipvalue_i*x_i)=pot

x_i >= 0 and x_i is integer for all i

In general this kind of problems are NP-hard. But if the pot size isn't too big one relatively easy algorithm for the problem is so called branch-and-bound algorithm. For explanation of the algorithm see: http://web.mit.edu/15.053/www/AMP-Chapter-09.pdf, Chapter 9.5, page 289

Title: Strategy/algorithm to divide pot to chips

Body:
I want to split poker pot to chips.

Example:

Pot = $17.500.

I have the endless piles of chips. I have the following types of chips: ChipsTypes = [$1, $5, $10, $25, $100, $500, $1.000, $5.000, $10.000, and so on]. Index starts from 0.

I want to get an array that says which chips I have to take to divide the pot and in which order to have minimum number of denominations and chips after pot-to-chips conversion. For example Result = [7, 5] means that I have to take 3 * $5.000 + 5 * $500 which $17.500.

Is there is any strategy or algorithm that would suit my need?


问:
What does value propagation mean?
I am working on an algorithm which calculates intervals for variables in some given constraints. For example there is a function called propagateValues and its description is

Propagate value ranges for the given constraints

What exactly is meant by value propagation ?

The algorithm I am working is basically trying to simplify sets of constraints by doing a range/interval analysis before querying the solver for a feasible solution (to make solving constraint sets more efficient)

答:
In constraint satisfaction, propagation means to make explicit a truth condition that is already present in the problem, but only implicitly.

For instance, if you have a variable that must be even, and another that has to be greater than 10, those are constraints on the two variables. Nothing else is known about the solution. However, if you have another binary constraint stating that the first variable has to be greater than twice the value of the second, then the value range of the first variable is actually 20, 22, 24... rather than 0, 2, 4, 6...

Propagating means finding such a range that is smaller than it first appears (usually by evaluating more than one constraint simultaneously), and then adjusting the value set for one variable to the stronger condition. It can go a long way towards solving a constraint satisfaction problem, or at least make it more efficient to enumerate all solutions.

Title: What does value propagation mean?


答:
The only time you'd want to estimate the entire backlog is if you are required to produce an estimate for completion of ALL features. That comes up when trying to integrate SCRUM with projects that need a 'finish' date for the entire project.

Assuming you don't need a 'done' date for the entire backlog, then I'd just estimate the stuff for the next iteration or two in detail and get on with the development. Since you've got a priority to the backlog, you don't need much more than that.


问:
Modern implementation of Spring Remoting or EJB3
Im working on a "what is possible with the latest and greatest" prototype.  One major issue that has been a big thorn in the side of myself and my AS/400 admin is when the existing system spins up, there are 35 individual applications, that each connect to 8 databases, and run a connection pool of 5 connections per.  for you math wizards out there, thats 1400 individual database connections to the server on startup and over the course of a typical day maybe 40 are ever used.

What I would like to do in this prototype is move all database functions to a central library (api).  From that point, I would like to deploy this API individually and have the 35 applications simply open service classes remotely and pass objects back and forth.  end result being the applications no longer have to create database connections, they simply call remote methods and we can tune the central api accordingly to handle the load.

Back in the day, EJB3 would have been the way to go.  the integration with security policies is nice, but i always had performance issues with it.  Spring remoting running hessian looks promising, seeing im using spring everywhere else.  but it has been YEARS since i have had to do anything like this so i was wondering what you guys suggest to use to accomplish this.

thanks

答:
Thanks for answering the Q's!

Jboss 7.1 should be able to supply a shared connection pool for all of your applications.  Checkout the JBOSS_DIST/docs/examples/jca folder for example datasource configurations.

Also see Apache's Database Connection Pooling library. You can swap that in if Jboss's native solution doesn't cut it.

Also, ask on JBoss.org - they're a pretty proactive bunch.


答:
After prioritising the Product Backlog I always try to estimate all the User Stories as part of the Sprint Planning session for Sprint 0. There have only been a couple of projects when there were simply too many stories for this to be practical in one Sprint Planning session. When this happened, as we were estimating the stories in the order of their priority, when we ran out of time we only left low priority stories un-estimated which we weren't intending on working on in the first Sprint. We were then able to finish estimating the remainder of the stories in the planning session for the next Sprint - don't waste valuable development time on estimating, confine this to the timeboxed Sprint Planning sessions.

We use relative estimation in Story Points which we arrive at through Planning Poker. This makes the whole process quick and easy enough that it is almost always achievable to estimate the entire Product Backlog at the outset of the project.

In answer to your second question; if there are specific acceptance criteria for a User Story, yes these should be added when the story is created. If you don't, as you have identified, it will be hard to estimate not to mention hard to implement correctly! If you have general acceptance criteria which apply to all stories (perhaps a maximum response time for any transaction or a minimum amount of code coverage), then these should be defined in a Definition of Done. This forms a set of quality standards which each team member must hit before they can declare a story complete.

Personally I prefer not to create an overall Product Backlog as the data it represents can be misleading. As new User Stories should be coming up all the time, whilst you're burning down against the backlog you're often adding more to it. Showing the number of incomplete User Stories or the total incomplete Story Points over time isn't necessarily a fair representation of the progress of the project.


问:
How do CDNs protect failover sites from DDoS attacks?
I'm in the design process for a Java web app that I will probably end up deploying to Google App Engine (GAE). The nice thing about GAE is that I really don't have to worry about fortifying my app from the dreaded DDoS attack - I just specify a "billing ceiling", and if my traffic peaks up to this ceiling (DDoS or otherwise), GAE will just shut my app down. In other words, GAE will essentially scale to any amount until you simply can't afford to keep the app running any longer.

So I'm trying to plan a contingency whereby, if I do hit this billing ceiling and GAE shuts my app down, my web app domain DNS settings "fail over" to another, non-GAE IP address. Some initial research has shown that certain CDNs like CloudFlare offer services for this exact situation. Basically, I just keep my DNS settings with them, and they provide an API I can hit to automate a failover procedure. Thus, if I detect that I'm at 99% my billing ceiling for my GAE app, I can hit this CloudFlare API, and CloudFlare will dynamically change my DNS settings to point away from the GAE servers to some other IP address.

My initial contingency would be to failover to a "read-only" (static content only) version of my web app hosted somewhere else, maybe by GoDaddy or Rackspace.

But then it suddenly dawned on me: if DDoS attacks target the domain name, what difference does it make if I rollover from my GAE IP address to my (say) GoDaddy IP address? In essence, the failover wouldn't do anything other than allows the DDoS attackers to bring down my backup/GoDaddy site!

In other words, DDoS attackers coordinate an attack on my web app, hosted by GAE, at www.blah-whatever.com, which is really an IP address of 100.2.3.4. They cause my traffic to spike to 98% my billing ceiling, and my custom monitor triggers a CloudFlare failover from 100.2.3.4 to 105.2.3.4. The DDoS attackers don't care! They're still launching an attack against www.blah-whatever.com! The DDoS attack continues!

So I ask: what protection do CDNs like CloudFlare offer so that - when you need to fail over to another DNS - you aren't at risk for the same, continued DDoS attack? If such protection exists, are there any technical restrictions (e.g. read-only, etc.) that are placed on the failover site? If not, what good are they?! Thanks in advance!

答:
I work for Incapsula, a Cloud Security company that also provides CDN based acceleration services (like CF).

I want to say that while (as correctly stated by @Billy ONeal) CDN by itself provides no  DDoS protection, a Cloud based Proxy Network is a VERY effective DDoS mitigation tool.

And so, in case of DDoS on Cloud CDN, it is not the "CDN" but "Cloud" that protects you by taking in all the extra traffic generated by DDoS, while still allowing access to your site from different POPs around the world.

Also, because this a front-gate proxy solution, this technology can be used to mitigate level 3-4 network DDoS attacks (i.e. SYN Floods) which use spoofed IPs to send numerous SYN requests to your servers.

In this case a proxy will not establish a connection until an ACK response is received, thus preventing the SYN flood from happening.

There are also other ways you can use Cloud for website security (i.e. Bad Bot Blocking, Cloud-based WAF) and some of these can be also used for DDoS mitigation or prevention (stopping scanner bots is a good example for the later) but the main thing to understand here is that this is all based not on CDN but on Cloud technology.


问:
When should I use AtomPub?
I have been conducting some research into RESTful web service design and I've reached what I think is a key decision point so I thought I'd offer it up to the community to get some advice.

In keeping with the principles of a RESTful architecture I want to present a discoverable API, so I will be supporting the various HTTP verbs as fully as possible. My difficulty comes with the choice of representation of those resources. You see, it would be easy for me to come up with my own API that covers how search results are to be presented and how links to other resources are provided, but this would be unique to my application.

I've read about the Atom Publishing Protocol (RFC 5023), and how OData promotes its use, but it seems to add an extra level of abstraction over what is (currently) a rather simple API.

So my question is, when should a developer select AtomPub as their choice of representation - if at all? And if not, what is the current recommended approach?

答:
After doing a fair amount of research into this, here are my findings:

There seem to be 3 primary formats and approaches: AtomPub, OData and HAL. I've summarised the research for each below.

AtomPub

Pro: Well established standard

Pro: Works with XML and JSON

Pro: Has excellent Java support through Apache Abdera

Con: Abdera introduces a lot of dependencies

Con: Very complex to work with on server side

Con: Difficult to build a complete JavaScript client

OData

Pro: Builds on AtomPub

Pro: Works with XML and JSON

Pro: Has good Java support through the odata4j project

Pro: Provides a good URI query structure

Con: Introduces a complete framework (essentially replaces Dropwizard)

Con: Very complex to work with, particularly the entity data model (EDM)

Con: Difficult to find a good JavaScript client library without relying on Windows-only tools for EDM

HAL

Pro: Introduces a lightweight and extensible approach

Pro: Works with XML and JSON

Pro: Trivial to create a JAXB model to implement it (no dependencies)

Pro: Provides a good linking framework

Pro: Trivial to create a JavaScript client using jQuery XML parsing

Con: Not ratified (although IETF have been approached)

So when should I use AtomPub?

From the above one should choose AtomPub if you're happy with the additional complexity and want to use standard libraries for your clients. This would probably be the case if you're running a large document repository.

I've put more detail (which is out of scope for this question) into a recent blog article that might be of help to others.

Title: When should I use AtomPub?


问:
Is it appropriate to make a User Story for removing small pieces of existing functionality?
For an area of an application that has been developed, the request has come in to remove an item from a menu.

I know this is a small thing, but how do you treat it in Scrum?  I'm used to using User Stories for adding functionality, not removing.

So my question is: Should I create a user story for this, somehow phrased to do with removing the button?  Or is there a better way or dealing with this?

答:
Yes, you should write a user story.

Use a story for everything you do. It forces you to answer the question "what business value is there in doing this work?". Writing user stories also forces you to understand who benefits from the work.

Plus, you are adding something. Presumably, the removal is because the feature isn't used or is buggy, or replaced by some other feature. Thus, you are adding usability to the product.

For example, the story might read like th is:

As the product owner of product X, I want feature Y to be removed so
  that our UI is more streamlined, and only provides features that are
  genuinely useful to our customers.

The value isn't in the user story per se, it's in the work done to create the story. By writing the story, you help focus your efforts.

OwnerDisplayName: Paul


问:
Advice for solo programmer whose team will expand in the near future
For 4 years now, I've been the solo developer for a small company. We have a handful of well establish products in a niche industry. We will be hiring 1-2 developers soon, and that will likely change the way things operate around here.

While I won't have a "real" title, I will be "in charge" of this team. What I want to do is establish a very organized and productive programming department for my company. I got this solo job right out of college, so while I've become proficient as a programmer in this industry, I lack a lot of team programming experience. I feel that starting out on the right foot will be key.

Right now it's just me, a few computers, and an SVN server. I'm looking for any general guidance on building a team from the ground up.

答:
hire someone a lot more competent than you

... and with experience in large enterprise software project.

They will help you industrialize your processes and you will probably learn a lot from them.

You will teach them your niche market.

If you can't find such a person, I suggest you to go to trainings related to team management. I suggest you a Scrum Certification as a starter.


答:
This is also called hoisting or scalar promotion. See here:

Hoisting means that you have pulled some operation out of a loop
  because the loop itself does not affect the result of the operation.
  In your case, you are hoisting the conditional test out of the while
  loop.

Re-ordering means changing the sequence of instructions in a way that
  does not affect the result. Typically this would be adjacent
  instructions with no data dependencies, e.g. it does not matter which
  order you perform the following two statements:

```<code>int a = x;
int b = y;
</code>```

Body:
This is also called hoisting or scalar promotion. See here:

Hoisting means that you have pulled some operation out of a loop
  because the loop itself does not affect the result of the operation.
  In your case, you are hoisting the conditional test out of the while
  loop.

Re-ordering means changing the sequence of instructions in a way that
  does not affect the result. Typically this would be adjacent
  instructions with no data dependencies, e.g. it does not matter which
  order you perform the following two statements:

int a = x;
int b = y;


问:
easiest way for push notifications
I wanted to implement real time push notification to one of the apps written in RoR. I don't have any experience with nodejs, nowjs, express or socketio.

What would be the easiest way to implement the realtime push notification system?

答: The easiest way would be to use a long-poll. However, this is not push. A long-poll is a normal request, with some long timeout. If there is a message, the request will be answered. Your client receives the answer and starts the next request. This way you almost always have an open request, waiting for an answer.

Title: easiest way for push notifications


答:
http://railscasts.com/episodes/260-messaging-with-faye

Taken from this question: https://stackoverflow.com/questions/5616614/how-would-you-create-a-notification-system-like-on-so-or-facebook-in-ror

My personal opinion is that while architecturally one of the most widespread solution is long-poll or comet, from a development perspective, I don't agree that it's the easiest in the sense that it's a part of the way to do things: simply there's much more in a queue/pubsub system because of the load its backend has to bear.

Personally, I'd even consider plugging in an ActiveMQ server or some other message queue solution, as long as it has a notion of per-user queue, which can be drained by a client, and it has a JS API to drain, and perhaps a Ruby / REST API to push, it works.

But again, this is my personal opinion, that while yes, long-polling can be an option (or socket.IO can be), it's only a part of the equation, even if a major part.

Title: easiest way for push notifications

Body:
I wanted to implement real time push notification to one of the apps written in RoR. I don't have any experience with nodejs, nowjs, express or socketio.

What would be the easiest way to implement the realtime push notification system?


问:
Code Documentation First?
Has anyone ever tried creating a complete code documentation first, before actually writing the code? I was thinking about this earlier because I thought it would help to write a concrete interface and would make sure your initial design wasn't floored by making you think about how classes interact. Is this a good idea? Has anyone tried it? Ell</p>

答:
Some people even go further and state that a company should completely work backwards, so

Write the press release

Write a FAQ

Define the customer experience

Write the User Manual

Start programming

See
http://www.allthingsdistributed.com/2006/11/working_backwards.html

Title: Code Documentation First?


答:
It sounds to me like you are attempting to solve the Knapsack Problem if you want a general solution where any denominations would work.

Put in those terms this is an unbounded knapsack problem where all the values are -1 and the weights are the denomination of the chip.

You should be able to find lots about the problem online.


答:
As the senior developer you will need manager hat on and start looking at your company's hr policies. (especially items such as holiday entitlement, sick leave procedures and disciplinary process although I hope you will never need it)

Now depending on the new hires skills and ability start delegating some aspects of your current work, you will need the time for managing priorities and scheduling.

One good source of simple and basic management skills on what to do and how in a professional manner is http://www.manager-tools.com. They do regular podcasts on management and career advice, not to mention a sizeable back catalog of material for you.

Title: Advice for solo programmer whose team will expand in the near future

Body:
For 4 years now, I've been the solo developer for a small company. We have a handful of well establish products in a niche industry. We will be hiring 1-2 developers soon, and that will likely change the way things operate around here.

While I won't have a "real" title, I will be "in charge" of this team. What I want to do is establish a very organized and productive programming department for my company. I got this solo job right out of college, so while I've become proficient as a programmer in this industry, I lack a lot of team programming experience. I feel that starting out on the right foot will be key.

Right now it's just me, a few computers, and an SVN server. I'm looking for any general guidance on building a team from the ground up.


答:
Joshua Bloch discusses this very point in his interview for the book "Coders at Work".

Contrary to more orthodox and academic views, he advises something to the tune of your thoughts (maybe you have read it there yourself?): that before writing the documentation you have to understand what do you want from the system and get a more "real" feeling. For this purpose he would design part of the interfaces and some client code that uses them.

The most important thing is to know what you’re trying to build: what
  problem you’re trying to solve. The importance of requirements analysis
  can’t be overstated. There are people who think, “Oh, yeah, requirements
  analysis; you go to your customer, you say, ‘What do you need?’ He tells
  you, and you’re done.”

Nothing could be further from the truth. Not only is it a negotiation but it’s
  a process of understanding. Many customers won’t tell you a problem;
  they’ll tell you a solution. A customer might say, for instance, “I need you to
  add support for the following 17 attributes to this system. Then you have to
  ask, ‘Why? What are you going to do with the system? How do you expect
  it to evolve?’” And so on. You go back and forth until you figure out what all
  the customer really needs the software to do. These are the use cases.

Coming up with a good set of use cases is the most important thing you can
  do at this stage. Once you have that, you have a benchmark against which
  you can measure any possible solution. It’s OK if you spend a lot of time
  getting it reasonably close to right, because if you get it wrong, you’re
  already dead. The rest of the process will be an exercise in futility.

The worst thing that you can do—and I’ve seen this happen—is you get a
  bunch of smart guys into a room to work for six months and write a 247-
  page system specification before they really understand what it is they’re
  trying to build. Because after six months, they’ll have a very precisely
  specified system that may well be useless. And often they say, “We’ve
  invested so much in the spec that we have to build it.” So they build the
  useless system and it never gets used. And that’s horrible. If you don’t have use cases, you build the thing and then you try to do something very simple
  and you realize that, “Oh my gosh, doing something very simple like taking
  an XML document and printing it requires pages upon pages of boilerplate
  code.” And that’s a horrible thing.

-- Joshua Bloch, from an interview in "Coders at Work: Reflections on the Craft of Programming" by Peter Seibel

If you're already thinking along these lines, it'd be good if you can get a hold of the book and read the whole interview. As I said, he is always very enlightening.

Title: Code Documentation First?

Body: Has anyone ever tried creating a complete code documentation first, before actually writing the code? I was thinking about this earlier because I thought it would help to write a concrete interface and would make sure your initial design wasn't floored by making you think about how classes interact. Is this a good idea? Has anyone tried it? Ell</p>

ContentLicense: CC BY-SA 4.0


答:
It depends on the reason that the button is being removed:

If it is being removed because the functionality is no longer
needed/used, then write a user story indicating the business
requirement change.

If it is being removed because it's confusing, or behaving
improperly, then tie the work to the bug that you're fixing.

If it is being removed because it's a UI change, then tie it to the
tech debt story that details that re-work.

Otherwise, stop doing unnecessary work and/or tell business to stop dictating to the team how your UI should look.

Title: Is it appropriate to make a User Story for removing small pieces of existing functionality?

Body:
For an area of an application that has been developed, the request has come in to remove an item from a menu.

I know this is a small thing, but how do you treat it in Scrum?  I'm used to using User Stories for adding functionality, not removing.

So my question is: Should I create a user story for this, somehow phrased to do with removing the button?  Or is there a better way or dealing with this?


答:
I don't know as I'd classify this as a "mistake", unless the site is practically unusable due to the performance.  Almost everybody has "post-implementation remorse" at some point, especially when working with new technology.  Since it appears you have a good relationship with the client, I'd suggest just telling them "Hey, I had some ideas that might make the site work a little faster, would you mind if I tweaked it a bit?"

Unless there were stated or understood performance goals that you missed, you're perfectly entitled to charge for any improvements or enhancements.  However, since you're getting the benefit of a hands-on learning experience with some new tools, I'd suggest a nominal "final adjustment" charge (say two hours worth).  And in any further projects, be sure to have a "performance tuning" phase, so you'll have something definite to charge this kind of work to.

Title: Should I charge a client for mistakes that I made?

Body: After developing a website for a client, I've realized that the load time is too extreme, and some changes need to be made. The extreme load times are attributed to the bloated css/js frameworks that I've been using. Much of the code that was included with these frameworks is not even being used and is slowing the site load time. My plan is to get rid of the css framework and just use a bare bones responsive css framework which is only like 1kb in size, and just add only the code needed. So my question is, should I charge the client for back-stepping and fixing this mistake? </p>


问:
How can I get my website's search results into Google's search results?
All I can find online is stuff about search result rankings, which I'm not concerned with at the moment. We're going to have a cloud-based online database and we want Google search results for something relevant to our site to display our website's search results for the same query.

For example, if someone types in "lunchbox" to google, there might be a result that says "Amazon search results for 'lunchbox'" and then you click that and it takes you to amazon, and it's already searched 'lunchbox' for you.

What can we do to enable this capability for our site?

答:
You can restrict Google's search results to a specific site with the site: directive.

```<code>lunchbox +site:amazon.com
</code>```

will tell Google to only query "lunchbox" on domains at/under "amazon.com" (that last bit is important: "+site:stackexchange.com" gets you hits on the entire network).

I re-read your question, and am not sure that my first interpretation was correct. It now seems like you're actually saying "when someone comes from Google, I want to re-run my own search with the same search terms."

If that's the case then the answer's easy: look at the Referer header, and pull the terms out of it.

Body:
You can restrict Google's search results to a specific site with the site: directive.

lunchbox +site:amazon.com

will tell Google to only query "lunchbox" on domains at/under "amazon.com" (that last bit is important: "+site:stackexchange.com" gets you hits on the entire network).

I re-read your question, and am not sure that my first interpretation was correct. It now seems like you're actually saying "when someone comes from Google, I want to re-run my own search with the same search terms."

If that's the case then the answer's easy: look at the Referer header, and pull the terms out of it.


问:
What's the name of this pattern involving multiple inputs and what to do based on an input?
If I've got code similar to this (although perhaps not as constrained as warning levels):

```<code>switch(item.StatusCode)
{
    case StatusCode.SUCCESS:
        CallSuccess(item);
        break;
    case StatusCode.WARNING:
        CallWarning(item);
        break;
    case StatusCode.ERROR:
        CallError(item);
        break;
}
</code>```

I often find myself converting it to something more like:

```<code>var behaviors = new Dictionary<StatusCode, Action<Item>>
{
    {StatusCode.SUCCESS, (item) => CallSuccess(item)},
    {StatusCode.WARNING, (item) => CallWarning(item)},
    {StatusCode.ERROR,   (item) => CallError(item)},
}

behaviors[item.StatusCode](item);
</code>```

I find that in a lot of cases this makes for more maintainable code.  Is this a pattern, does it actually help like I think it does, and what's its name?

答:
I believe this is usually considered an application of the Strategy Pattern.

The whole point of this is more maintainable code - among other things, it makes it trivial to add new behaviors at runtime (to say nothing of compile time).  There is (usually) some loss in terms of performance, but this tends to be outweighed by the increase in maintainability.


问:
Why does the code auditing tools like FindBugs require a compile step to work properly?
Basically I ran Intellij Idea 's plug in called FindBugs-Idea to analyze my code . I corrected whatever errror was caught and then ran the tool again but it was still complaining about the same error even though it was fixed in the source file . It only stopped complaining after I recompiled my classses . Why does it require a compilation step ? Shouldn't it basically look in the source file and detect a possible bug ? How do these tools work in general ?</p>

答:
Findbugs examines the bytecode to identify patterns that tend to be buggy.

This is far more efficient than analyzing source code. You would essentially have to parse the source anyway to analyze it, so let the existing compiler do that work for you and focus on finding bugs.

By working with compiled bytecode, FindBugs can treat your code as identical to the third-party libraries that you use, and investigate all of them (to ensure that you're calling the library correctly).


答:
Strategy pattern &  Open Closed Principle

It looks like Open Closed Principle is pretty good to solve described routine issue. This is a part of S.O.L.I.D. principles. One of its applications is in strategy pattern, also mentioned in (GoF).

This principle usually works when an existing codebase is written, but yet it's easier to write all new code than it is to change old code.

Wouldn't you like extending an existing codebase to be as productive and frustration-free as writing all new code?  - This is where the Open Closed Principle comes into play. To paraphrase, the Open Closed Principle is stated as: software entities should be open for extension but closed for modification.

What Benefits does it provide ?

The code is easier to read. I don’t need to go and read (or
search) an “endless” switch statement to understand each aspect of the code.

The code is more maintainable. I only need to go to the relevant class that implement the logic in order to change it or refactor it when needed.

It is easier to add more logic. I only need to add more classes
to the pile of existing logic and that is it. Doing so helps us to imply
the Open / Closed Principle because in if/switch statements we are going

to have to change our code (add another case statement) in opposed
to Strategy which we do not change existing logic.

Strategy Pattern is more testable. Unit testing can be easily done.

Some references:

The Strategy Pattern in .NET

The Open Closed Principle

LOS Techies

Applying Strategy Pattern Instead of Using Switch Statements

Title: What's the name of this pattern involving multiple inputs and what to do based on an input?

Body:
If I've got code similar to this (although perhaps not as constrained as warning levels):

```<code>switch(item.StatusCode)
{
    case StatusCode.SUCCESS:
        CallSuccess(item);
        break;
    case StatusCode.WARNING:
        CallWarning(item);
        break;
    case StatusCode.ERROR:
        CallError(item);
        break;
}
</code>```

I often find myself converting it to something more like:

```<code>var behaviors = new Dictionary<StatusCode, Action<Item>>
{
    {StatusCode.SUCCESS, (item) => CallSuccess(item)},
    {StatusCode.WARNING, (item) => CallWarning(item)},
    {StatusCode.ERROR,   (item) => CallError(item)},
}

behaviors[item.StatusCode](item);
</code>```

I find that in a lot of cases this makes for more maintainable code.  Is this a pattern, does it actually help like I think it does, and what's its name?


问:
What are the Top Developer Productivity Tools/Plugins for Java in Eclipse?
I personally use CodeRush in Visual Studio 2010 to do refactoring, write code faster with templates and generally navigate my code 10 times faster than stock VS.  Recently, I've been working on another Android app and got to thinking...What are the top productivity plugins for Eclipse?

Preferably free. I'm looking for plugins that help write in Java, not PHP or Rails or any of the other languages Eclipse supports.

答:
Mylyn is a very widely appreciated plugin for Eclipse, and is available on the main Eclipse site now. It can watch the pieces of code that you work on together (for example, when changing "tax calculation" code, you tend to use the same five files) and then emphasize them the next time you work on the same task. It's a great way to undo the "information overload" you get when working on a large project.

FindBugs for Eclipse will help you save time by analyzing your source code for potential Java bugs. It has a false positive rate, and you wouldn't want to run it each build, but it's a great process to go through.

Eclipse's own refactoring and navigation features will save you time as well. My favorite feature of the JDT is the "Quick Fix." When you have an error in your source code (you can use Control-Period to navigate to it), simply do a Control-1 for the Quick Fix operation. It will give you a list of ways to fix the error. For example, if you write a = foo(s), but a is not declared, one of the Quick Fix options is to "declare a". Eclipse will look at the return type from foo and use that for a, automatically adding any imports. With this style, you will find you write code with errors intentionally, because the Quick Fix route is faster!

My other favorite Eclipse shortcut is "Expand Selection To->Enclosing Element" (Alt+Shift+Up). This takes where your cursor is and then selects the element of the parse tree you are on. When you do it again, you move further up the parse tree. This is great, because you can select an entire expression easily, not having to worry about selecting the code before or after it. That makes it much easier for you to have a valid expression in order to perform the "Extract Local" refactoring.

JUnit is indispensible if you are writing unit tests, and it's well integrated with the environment and process.

If you do any work with GWT, then Google's GWT Eclipse plug-in is nice. You can even use it for working with any Tomcat application, not just a GWT one.

All of these tools are available free.


问:
How can calculus and linear algebra be useful to a system programmer?
I found a website saying that calculus and linear algebra are necessary for System Programming.

System Programming, as far as I know, is about osdev, drivers, utilities and so on. I just can't figure out how calculus and linear algebra can be helpful on that. I know that calculus has several applications in science, but in this particular field of programming I just can't imagine how calculus can be so important.

The information was on this site:
http://www.wikihow.com/Become-a-Programmer

Edit: Some answers here are explaining about algorithm complexity and optimization. When I made this question I was trying to be more specific about the area of System's Programming. Algorithm complexity and optimization can be applied to any area of programming not just System's Programming. That may be why I wasn't able to came up with such thinking at the time of the question.

答: I suspect it's true around the edges. System programmers have to be far more concerned about performance and reliability, so algorithm analysis might be important, and calculus is sometimes needed for proofs of Big-Oh analysis. Subjects like queuing theory and discrete optimization (that's mathematical optimization not code optimization) can a play a role too. However I think those would mostly apply to folks working on the bleeding edge of operating systems and network protocols, not so much the person working on the USB 3.0 driver.</p>


答:
I would imagine its not very important if you're writing non GUI utilities on top of a modern operating system without working on its internals.  Its probably a different story if you are working on changing a modern operation system or developing a new one.

If you're working with video hardware or a bare metal windowing system, you're going to need knowledge of linear algebra to efficiently update graphics. I haven't looked myself, but I bet you could find examples in the source code for X, KDE and Gnome.

If you're working with hardware regarding digital signal processing then calculus will be very important.  I imagine there are some devices which do their heavy lifting with the system's CPU instead of a local microprocessor and these often interface to analog electrical systems.

Also calculus plays an important role in performance analysis besides just linear algebra when attempting curve fitting to the data.

Title: How can calculus and linear algebra be useful to a system programmer?

Body:
I found a website saying that calculus and linear algebra are necessary for System Programming.

System Programming, as far as I know, is about osdev, drivers, utilities and so on. I just can't figure out how calculus and linear algebra can be helpful on that. I know that calculus has several applications in science, but in this particular field of programming I just can't imagine how calculus can be so important.

The information was on this site:
http://www.wikihow.com/Become-a-Programmer

Edit: Some answers here are explaining about algorithm complexity and optimization. When I made this question I was trying to be more specific about the area of System's Programming. Algorithm complexity and optimization can be applied to any area of programming not just System's Programming. That may be why I wasn't able to came up with such thinking at the time of the question.


答:
Your definition of Systems Programming pretty well aligns with the answer in Wikipedia.

If you think about what it's providing - ie. a software interface into hardware, then it starts to make sense why calculus and linear algebra are handy skills to have.

Abstracting out that low level interface requires you to understand how the device operates.  Electronics devices are still bound by the laws of physics.  Calculus and linear algebra provide a means to model the behavior of the device.  Modeling the device lets you provide a service into its functionality.

That having been said, those two fields are not the end-all be-all for Systems Programming.  I know quite a few EE's who didn't do as well with calculus and linear algebra but can still explain what the device is doing fairly succinctly.


答: There are different types of static analysis tools - those that operate on the source code and those that operate on a compiled product. Findbugs is an example of the latter, while a tool like PMD is an example of the former. Depending on what type of problems the tool is trying to detect, the choice of what product to analyze can make it easier or more difficult. As an example, tools that analyze the byte code can't be used to find problems that lead to code being less readable, but they can analyze anything that compiles to the same byte code.</p>

Title: Why does the code auditing tools like FindBugs require a compile step to work properly?

Body: Basically I ran Intellij Idea 's plug in called FindBugs-Idea to analyze my code . I corrected whatever errror was caught and then ran the tool again but it was still complaining about the same error even though it was fixed in the source file . It only stopped complaining after I recompiled my classses . Why does it require a compilation step ? Shouldn't it basically look in the source file and detect a possible bug ? How do these tools work in general ?</p>


答:
I'll go ahead and say that I don't think calculus or linear algebra are likely to be important for systems programming.

I certainly think calculus and linear algebra are worth learning in general -- I'm a math guy!  And, as other answers point out, there is some indirect relevance, as performance analysis and algorithm design can use advanced math.  However, I don't think systems programming is any more dependent on those kinds of math than most other fields that aren't generally thought of as mathematical.


答:
General web application and/or administrative programming doesn't involve much application of linear algebra or calculus, but many specialist fields do. If you deal with geometry you're bound to run into linear algebra. Most physics programming also deals with both algebra and calculus. As well as just about anything having to do with waveform manipulation, such as sound and radio programming.
In general it is more important to understand discrete mathematics which, amongst other things, deals with set theory, graph theory and formal (boolean) logic which is useful in many applications like information management, databases and other places where data and/or logic combine.
In the case of Systems programming I don't see that many applications.</p>


问:
What is the most basic and simple platform for collaborative development (PHP project)?
I need to work with 4-5 programmers on a fairly average PHP application using codeigniter. We're in 5 different locations in one city, and all of the programmers are all not too well educated and I'm assuming that most of them have never used any version control system.

Can you recommend some very very easy-to-get-into platform for collaborating on a project like this? I'm talking about something that is only a tad more sophisticated than a shared dropbox folder.

答:
...FTP

Ok, this is the way I started to collaborate, hooking up Notepad++ to FTP, backing up crap every 10 minutes in renamed folders really sucked, if you do this, for the sake of your project at least use version control at the server.

An online IDE

Cloud9 is very nice and has concurrent editing, however, it will cost you to have more than 1 private workspace to work with your team, but it is worth it.

...try Mercurial

If you don't find Git approachable enough by your coworkers, try Mercurial with TortoiseHG, which is a GUI client for Mercurial. It will take them two minutes to setup and less to start using it.

Have them use the GUI, they just have to learn to use 4 buttons (pull, update, commit, push) and learn 2 or 3 concepts in order to save and share their work.

Have them register in bitbucket. Create a repository for your project, and have them fork it so they can work in their own mirror of the repository and that way they don't have to deal with merging. You do the integration and just ask them to issue pull requests from their Bitbucket fork once they've pushed. Have them pull only from your repository (the one they forked from).

Learn Mercurial yourself so that you can solve all related problems, this is a good start: http://hginit.com/

Try both

You can use Mercurial from Cloud9, how cool is that?.

Stop assuming

If you are the one looking to use the correct tools you are already in a leadership position. Don't assume they're not educated and talk with them about how things are done in the real world.

Be enthusiastic about it an not patronizing.

It really doesn't get any easier than this if you want to do things right. If they expressly don't want to use version control then you might have another kind of more serious problem.


问:
How can I write a set of functions that can be invoked from (almost) any programming language?
I'd like to find a way to write an API that can be accessed from any other programming language via language bindings (or some other framework). Is it possible to do this? If so, which programming language would be the most suitable for writing a "cross-language" API? My goal is to create a single set of functions that I can access from any programming language that I'm working with, so that I won't need to manually re-write the entire API in each language.</p>

答:
To add to above answers that suggest using an RPC mechanism. You could use Apache Thrift.(http://thrift.apache.org/). It is basically a RPC framework.

As per the Thrift wiki:

The Apache Thrift software framework, for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages


问:
JavaScript application design patterns
I need to write a PhoneGap application with JavaScript and I'm thinking of the code design patterns. I've read some books of JavaScript design patterns but can't really see the advantages/disadvantages on them and I think I don't understand the implementation and usage right.

I would like to have some opinions of which might suit my needs best. I'd like the code to be readable and maintainable.

The application itself is quite small and simple. It has a player management (add/remove), a game management (add/remove players from a team, start/stop/reset a stopwatch).

In last app I created I had over 30 named functions in a global scope which I think is a big no no. So, now I want to make things right, and was thinking of either using an object literal or a module pattern... something like this perhaps:

```<code>var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind();
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    },

    player: {
        add:            function(name) { ... },
        remove:         function(name) { ... }
    },

    team: {
        addPlayer:      function(name) { ... },
        removePlayer:   function(name) { ... }
    },

    game: {
        create:         function() { ... },
        startTime:      function() { ... },
        stopTime:       function() { ... },
        resetTime:      function() { ... }
    }
};

document.addEventListener('deviceready', MYAPP.init, false);
</code>```

... or perhaps this?

```<code>var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind();
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    }
}

var PLAYER = (function () {

    // Some private variables
    var privateVar, privateMethod;

    return {
        add: function (name) { ... },
        remove: function (name) { ... }
    };

}());

document.addEventListener('deviceready', MYAPP.init, false);
</code>```

答:
Use the module pattern, use a dependency handling framework (like require.js) during development.

Usually we had this "require" - "provide" duality, and the module pattern, it has satisfied us with a few million lines of client-side JS code (yes, there are some huuge apps out there).

Consider using some of the MVC frameworks like Knockout.JS

Look at how Ext.JS apps are structured perhaps.

Look at how YUI 3 is structured. Yahoo! is also a big user of JavaScript, and they had Crockford on board until quite recently, they know what they do perhaps.

The essential thing about code maintainance are twofold. For every change:

know which file to open

know where to scroll in that file immediately

Now,if you have one, large, single file, you break rule nr. 1.

Otherwise, Uncle Bob's SOLID principles are still adequate, also the usual module handling recommendations from Kevlin Henney. Javascript is just a language.

Title: JavaScript application design patterns


答:
Your first example is pretty good. Id recommend the sef-revealing module pattern, it allows you to split your application in files:

```<code>(function( MYAPP, $, undefined ) {

  // we pass in undefined because 'undefined' is no reserved word in Javascript

  'use strict';

  //Private Method
  function addItem( item ) {
    //...
  }

   //Public Method
   MYAPP.someMethod = function() {
     // ...
   };

}( window.MYAPP = window.MYAPP || {}, jQuery ));
</code>```

This way you make shure jQuery or whatever library you want to use is what you expect, and use the same pattern accross several files.

This could work for your application:

```<code>(function( MYAPP, $, undefined ) {
  'use strict';

  // These are private
  var players = [],
      team = [];

  // This will be executed at ready event
  $(document).ready(function() {
    bind();
  });

  // private Method
  // (it doesn't need to be public, since the ready
  // handler shares the same scope)
  function bind() {
    // Bind jQuery click and page events
  }

  MYAPP.player = {
    add: function(name) {
      players.push(name);
    },
    remove: function(name) {
      // ...
    }
  };

  MYAPP.team = {
    addPlayer: function(name) {
      // ...
    },

    removePlayer: function(name) {
      // ...
    }
  };

}( window.MYAPP = window.MYAPP || {}, jQuery ));
</code>```

One word to the strict mode. Strict mode helps out in a couple ways:

It catches some common coding bloopers, throwing exceptions.

It prevents, or throws errors, when relatively "unsafe" actions are
taken (such as gaining access to the global object).

It disables features that are confusing or poorly thought out.

To enable strict mode put this at the top of a program to enable it for the whole script:

```<code>"use strict";
</code>```

Or place it within a function to turn on strict mode only within that context.

```<code>function imStrict(){
   "use strict";
   // ... your code ...
}
</code>```

Title: JavaScript application design patterns

Body:
I need to write a PhoneGap application with JavaScript and I'm thinking of the code design patterns. I've read some books of JavaScript design patterns but can't really see the advantages/disadvantages on them and I think I don't understand the implementation and usage right.

I would like to have some opinions of which might suit my needs best. I'd like the code to be readable and maintainable.

The application itself is quite small and simple. It has a player management (add/remove), a game management (add/remove players from a team, start/stop/reset a stopwatch).

In last app I created I had over 30 named functions in a global scope which I think is a big no no. So, now I want to make things right, and was thinking of either using an object literal or a module pattern... something like this perhaps:

```<code>var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind();
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    },

    player: {
        add:            function(name) { ... },
        remove:         function(name) { ... }
    },

    team: {
        addPlayer:      function(name) { ... },
        removePlayer:   function(name) { ... }
    },

    game: {
        create:         function() { ... },
        startTime:      function() { ... },
        stopTime:       function() { ... },
        resetTime:      function() { ... }
    }
};

document.addEventListener('deviceready', MYAPP.init, false);
</code>```

... or perhaps this?

```<code>var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind();
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    }
}

var PLAYER = (function () {

    // Some private variables
    var privateVar, privateMethod;

    return {
        add: function (name) { ... },
        remove: function (name) { ... }
    };

}());

document.addEventListener('deviceready', MYAPP.init, false);
</code>```

Body:
Your first example is pretty good. Id recommend the sef-revealing module pattern, it allows you to split your application in files:

(function( MYAPP, $, undefined ) {

  // we pass in undefined because 'undefined' is no reserved word in Javascript

  'use strict';

  //Private Method
  function addItem( item ) {
    //...
  }

   //Public Method
   MYAPP.someMethod = function() {
     // ...
   };

}( window.MYAPP = window.MYAPP || {}, jQuery ));

This way you make shure jQuery or whatever library you want to use is what you expect, and use the same pattern accross several files.

This could work for your application:

(function( MYAPP, $, undefined ) {
  'use strict';

  // These are private
  var players = [],
      team = [];

  // This will be executed at ready event
  $(document).ready(function() {
    bind();
  });

  // private Method
  // (it doesn't need to be public, since the ready
  // handler shares the same scope)
  function bind() {
    // Bind jQuery click and page events
  }

  MYAPP.player = {
    add: function(name) {
      players.push(name);
    },
    remove: function(name) {
      // ...
    }
  };

  MYAPP.team = {
    addPlayer: function(name) {
      // ...
    },

    removePlayer: function(name) {
      // ...
    }
  };

}( window.MYAPP = window.MYAPP || {}, jQuery ));

One word to the strict mode. Strict mode helps out in a couple ways:

It catches some common coding bloopers, throwing exceptions.

It prevents, or throws errors, when relatively "unsafe" actions are
taken (such as gaining access to the global object).

It disables features that are confusing or poorly thought out.

To enable strict mode put this at the top of a program to enable it for the whole script:

"use strict";

Or place it within a function to turn on strict mode only within that context.

function imStrict(){
   "use strict";
   // ... your code ...
}