答:
I have lots of sympathy for your situation, but few concrete suggestions. If nothing else, maybe I'll convince you that as bad as a situation is, it could be worse.  It can ALWAYS be worse.  :-)

First, I think you have (at least) two problems with your culture, not just one.  One problem is the approach to refactoring, but the code reviews seem like a distinct problem.  I'll try to separate my thoughts.

Code Reviews

I was in a group that HATED code reviews. The group was formed by merging two groups from separate parts of the company.  I came from the group that had been doing code reviews for several years, with generally good results.  Most of us believed code reviews were a good use of our time.  We merged into a larger group, and as near as we could tell, that "other" group had never even heard of code reviews.  Now we were all working on "their" code base.

Things were not well when we merged.  New features were 6-12 months late, year after year.  The bug backlog was huge, growing, and life-draining.  Code ownership was Strong, especially among the most senior "gurus".  "Feature branches" sometimes lasted years and spanned a few releases; sometimes NOBODY but a single developer saw the code before it hit the main branch.  Actually "feature branch" is misleading, since it suggests the code was somewhere in the repository.  More often it was only on the developer's individual system.

Management agreed that we needed to "do something" before quality became unacceptably low.  :-)  Their answer was Code Reviews.  Code Reviews became an official "Thou Shalt" item, to precede every check-in.  The tool we used was Review Board.

How did it work in the culture I described?  Better than nothing, but it was painful and took more than a year to reach a sort of minimal level of compliance.  Some things we observed:

The tool you use tends to focus code reviews in certain ways.  This can be a problem.  Review Board gives you nice, colorful line-by-line diffs and lets you attach comments to a line.  This makes most developers ignore all the lines that didn't change.  That's fine for small, isolated changes.  It's not so good for big changes, large hunks of new code, or code that has 500 instances of a renamed function mixed with 10 lines of new functionality.

Even though we were in an old, sick code base that had mostly never been reviewed before, it became "impolite" for a reviewer to comment on anything that was NOT a change line, even to point out an obvious bug.  "Don't bother me, this is an important check-in and I don't have time to fix bugs."

Shop for an "easy" reviewer.  Some folks will look at a 10-file review with 2000 changed lines for 3 minutes and click "Ship It!".  Everyone quickly learns who those people are.  If you really don't want your code reviewed in the first place, send it to an "easy" reviewer.   You check-in will not be slowed down.  You can return the favor by becoming an "easy" reviewer for his code.

If you hate code reviews, just ignore the emails you get from Review Board.  Ignore the follow-ups from your team members.  For weeks.  Until you have 3 dozen open reviews in your queue and your name comes up in group meetings a few times.  Then become an "easy" reviewer and clear all your reviews before lunchtime.

Avoid sending your code to a "hard" reviewer.  (The sort of developer who would ask or answer a question like this one.)  Everyone quickly learns who the "hard" reviewers are, just as they learn the easy ones.  If code reviews are a Waste Of Time (™), then reading detailed feedback about the code you OWN is both Waste Of Time (™) and an insult.

When code reviews are painful, people put them off and keep writing more code.  You get fewer code reviews, but each one is BIG.  You need more, smaller code reviews, which means the team needs to figure out how to make them as painless as possible.

I thought I was going to write a few paragraphs about Code Reviews, but it turns out I was mostly writing about culture.  I guess it boils down to this: code reviews can be good for a project, but a team gets only the benefits they deserve to get.

Refactoring

Did my group despise refactoring even more than it hated code reviews?  Of course!  For all the obvious reasons that have already been mentioned. You're wasting my time with an icky code review, and you're not even adding a feature or fixing a bug!

But the code was still in desperate need of refactoring.  How to proceed?

Never mix a refactoring change with a functional change.  A number of people have mentioned this point.  If code reviews are a friction point, don't increase the friction.  It's more work, but you should plan on a separate review and a separate check-in.

Start small. Very small. Even smaller than that.  Use very small refactorings to gradually teach people that refactoring and code reviews aren't pure evil.  If you can sneak in one tiny refactoring per week without too much pain, in a couple of months you might be able to get away with two per week. And they can be a little bigger.  Better than nothing.

We had essentially NO unit tests.  So refactoring is forbidden, right?  Not necessarily.  For some changes, the compiler is your unit test.  Focus on refactorings that you can test. Avoid changes if they can't be tested.  Maybe spend the time writing unit tests instead.

Some developers are scared of refactoring because they are scared of ALL code changes.  It took me a long time to recognize this type.  The write a chunk of code, fiddle with it until it "works", and then NEVER want to change it. They don't necessarily understand WHY it works. Change is risky.  They don't trust themselves to make ANY change, and they certainly won't trust you.  Refactoring is supposed to be about small, safe changes that don't alter behavior.  There are developers for whom the very idea of a "change that doesn't alter behavior" is inconceivable.  I don't know what to suggest in these cases.  I think you have to try to work in areas that they don't care about.  I was surprised when I learned that this type can have long, stable careers as software developers.

Title: Reconciling the Boy Scout Rule and Opportunistic Refactoring with code reviews

Body:
I am a great believer in the Boy Scout Rule:

Always check a module in cleaner than when you checked it out." No
  matter who the original author was, what if we always made some
  effort, no matter how small, to improve the module. What would be the
  result? I think if we all followed that simple rule, we'd see the end
  of the relentless deterioration of our software systems. Instead, our
  systems would gradually get better and better as they evolved. We'd
  also see teams caring for the system as a whole, rather than just
  individuals caring for their own small little part.

I am also a great believer in the related idea of Opportunistic Refactoring:

Although there are places for some scheduled refactoring efforts, I
  prefer to encourage refactoring as an opportunistic activity, done
  whenever and wherever code needs to cleaned up - by whoever.
  What this means is that at any time someone sees some code that isn't
  as clear as it should be, they should take the opportunity to fix it
  right there and then - or at least within a few minutes

Particularly note the following excerpt from the refactoring article:

I'm wary of any development practices that cause friction for
  opportunistic refactoring ... My sense is that most teams don't do
  enough refactoring, so it's important to pay attention to anything
  that is discouraging people from doing it. To help flush this out be
  aware of any time you feel discouraged from doing a small refactoring,
  one that you're sure will only take a minute or two. Any such barrier
  is a smell that should prompt a conversation. So make a note of the
  discouragement and bring it up with the team. At the very least it
  should be discussed during your next retrospective.

Where I work, there is one development practice that causes heavy friction - Code Review (CR). Whenever I change anything that's not in the scope of my "assignment" I'm being rebuked by my reviewers that I'm making the change harder to review. This is especially true when refactoring is involved, since it makes "line by line" diff comparison difficult. This approach is the standard here, which means opportunistic refactoring is seldom done, and only "planned" refactoring (which is usually too little, too late) takes place, if at all.

I claim that the benefits are worth it, and that 3 reviewers will work a little harder (to actually understand the code before and after, rather than look at the narrow scope of which lines changed - the review itself would be better due to that alone) so that the next 100 developers reading and maintaining the code will benefit. When I present this argument my reviewers, they say they have no problem with my refactoring, as long as it's not in the same CR. However I claim this is a myth:

(1) Most of the times you only realize what and how you want to refactor when you're in the midst of your assignment. As Martin Fowler puts it:

As you add the functionality, you realize that some code you're adding
  contains some duplication with some existing code, so you need to
  refactor the existing code to clean things up... You may get something
  working, but realize that it would be better if the interaction with
  existing classes was changed. Take that opportunity to do that before
  you consider yourself done.

(2) Nobody is going to look favorably at you releasing "refactoring" CRs you were not supposed to do. A CR has a certain overhead and your manager doesn't want you to "waste your time" on refactoring. When it's bundled with the change you're supposed to do, this issue is minimized.

The issue is exacerbated by Resharper, as each new file I add to the change (and I can't know in advance exactly which files would end up changed) is usually littered with errors and suggestions - most of which are spot on and totally deserve fixing.

The end result is that I see horrible code, and I just leave it there. Ironically, I feel that fixing such code not only will not improve my standings, but actually lower them and paint me as the "unfocused" guy who wastes time fixing things nobody cares about instead of doing his job. I feel bad about it because I truly despise bad code and can't stand watching it, let alone call it from my methods!

Any thoughts on how I can remedy this situation ?


问:
Fixing a spelling mistake in a method name
One of the methods that I commonly use in our codebase is misspelled (and it predated me).

This really irritates me not simply because it is mispelled but more importantly it makes me ALWAYS get the name wrong the first time I type it (and then I have to remember "Oh, right, it should be mispelled to this...")

I'm making a few changes around the original method. Should I take the opportunity to just rename the freaking method?

答:
I would generally recommend yes, rename it.

Other answers here have listed good reasons why you might not want to renamed it though, so if you find yourself in one such situation, you can create a new method with the proper name and implementation, and change the old method to call the new method. Then mark the old one as deprecated if your language supports it.

ContentLicense: CC BY-SA 3.0


问:
Using AngjularJS with Twitter Bootstrap
I want to refactor an OLD legacy application and give it a new feel... so, I want to use Twitter Boostrap for the UI... I've also been playing around a lot with AngularJS... is it common place to use them in conjunction with one another? Is it even the correct question to ask? I've done about an hour's worth of "googling" on the subject and I see a lot of people using the CSS-portion of bootstrap with Angular, however, do I gain anything (or lose anything) by also including the bootstrap .js portion, as well?

Thanks.

答: That all depends. Are you going to use the UI widgets as built by Bootstrap or are you going to use AngularJS-ish versions? Fortunately, someone has addressed that: http://angular-ui.github.io/bootstrap/</p>

Title: Using AngjularJS with Twitter Bootstrap


问:
What does "trivial" mean?
You often see statements like "all non-trivial software has bugs" or "all non-trivial abstractions are leaky". But what makes a program "trivial" instead of non-trivial? Where is the cut-off line at which we can say that a program isn't trivial and "excuse" bugs?

Even something only a few lines long could have bugs. Say you have a simple command line C program that asks "What is your name?", reads a response using scanf or gets, stores it in a buffer and prints back "Hello " + name. That program could easily have a buffer overflow if the input is larger than a buffer, so it could have a bug even though it's only a few lines.

But if you ensured that you always allocated eblnough memory or bounds checked, etc, you don't have the bug. So is the program "trivial" or not? It can be buggy or not, but it's small and simple. Can we give any meaning to the idea of a "trivial program" or is it merely an excuse for sloppyness?

答:
"Trivial" typically refers to an implementation that demonstrates the relevant functionality and no more, though there is no hard-and-fast rule.

In the examples you list, the word is used to couch against purpose-built counterexamples. For example, "all nontrivial abstractions are leaky" means something like, "all abstractions are leaky except for ones you devise specifically to disprove this statement." If the purpose of your abstraction is to illustrate an abstraction, then the author would probably consider it trivial.

Another interpretation is to imply that there exists a certain threshold of complexity below which the axiom doesn't apply. In that sense, "all nontrivial abstractions are leaky" means that all non-leaky abstractions are defined as trivial by this axiom. This is the "no true Scotsman..." argument reapplied.

Title: What does "trivial" mean?


答:
It's a rather open-ended question.

Trivial could be software in which the amount of time required to fix the problem would cost more than any kind of workaround for it. Another example would be a small utility that has one of the bugs you mention, but since it is easily replaceable by another utility that does the same thing, it gets ignored.

I work on 911 systems so I work with a lot of non-trivial software. However, we have some management utilities which were written 10-15 years ago that we consider trivial since there is no real business advantage to updating them. Even the occasional bugs that come up are often ignored since we can go direct to the database and fix the problem. We're a pretty small shop though, so YMMV.

Title: What does "trivial" mean?

Body:
You often see statements like "all non-trivial software has bugs" or "all non-trivial abstractions are leaky". But what makes a program "trivial" instead of non-trivial? Where is the cut-off line at which we can say that a program isn't trivial and "excuse" bugs?

Even something only a few lines long could have bugs. Say you have a simple command line C program that asks "What is your name?", reads a response using scanf or gets, stores it in a buffer and prints back "Hello " + name. That program could easily have a buffer overflow if the input is larger than a buffer, so it could have a bug even though it's only a few lines.

But if you ensured that you always allocated eblnough memory or bounds checked, etc, you don't have the bug. So is the program "trivial" or not? It can be buggy or not, but it's small and simple. Can we give any meaning to the idea of a "trivial program" or is it merely an excuse for sloppyness?


问:
What are "siblings" of .json files?
I was reading through the documentation for Bower here and I read this line: "The .bowerrc file should be a sibling of your project's bower.json." What does that mean exactly? Searching Google returned questions of people asking how to find siblings, but not what they actually are. </p>

答: Siblings share the same parent, so it means they should both be in the same folder. </p>

Title: What are "siblings" of .json files?


问:
Branching strategy for frequent releases
We have very frequent releases and we use Git for version control. When i am mentioning about frequency, please assume it to include bug-fixes and feature release too. All releases are eventually merged into ‘mainline’. When a release is deployed on production and if a bug is identified, people start fixing the bug on the same branch from which the latest release was deployed on production. They do not create a new bug-fix branch for the same. I feel that’s not the right way to go for. There are several components and each component has a different owner, and thus, different perspective. Though I have not initiated talks with them, I am sure there will be a lot of resistance. Main issue that they might cite would be, “There’s a lot of work involved in creating and tracking branches especially when there are so frequent deployments on production. This will consume a lot of dev effort.”

Do you think that fixing bug on the same branch from which release was done, a good idea? If yes, how do you manage it? Using tags?

I know that best practices may not always be applicable due to several factors but still I would like to know what might be a good approach for branching in a scenario where releases/bug-fixes happen almost on a daily basis.

Edit: Thanks everyone for sharing your views and for the useful links. I think the main concern i have here is this: Do you think that fixing bug on the same branch from which release was done, a good idea? Is this approach fine in the long run or are we messing up things just to realize it later?

答:
The important thing here is to have a consistent workflow which can be easily followed by both newbies and veterans in your organizations. Decide on a process which meets your requirements and ensure that the workflow makes sense for both trivial and more complex changes.

That said, there are a few standard workflows out there. Here's a few of them:

GitHub Flow

GitHub Flow is a lightweight, branch-based workflow that supports teams and projects where deployments are made regularly. Scott Chacon explains the differences from Git Flow here.

So, why don’t we use git-flow at GitHub? Well, the main issue is that
  we deploy all the time. The git-flow process is designed largely
  around the “release”. We don’t really have “releases” because we
  deploy to production every day – often several times a day.

This site provides a great visual walkthrough for the GitHub Flow.

Git Flow

Git Flow defines a strict branching model designed around the project release. This provides a robust framework for managing larger projects. It defines specific branches for release, development, hot-fixes, etc. and the transitions between them.

There are a number of git extensions and tools available online to help support this workflow. Take a look at the nvie/gitflow extension for a starting point.

You can get a detailed explanation of the various stages and roles in the workflow here and here.


问:
How the Stream.filter() method works?
I know how the lambda expresion works and I know it is an argument for .filter() that establish the criteria to filter with. But I don't get  how .filter() uses the argument, in this case a lambda expression, because .filter() does't have an implementation or at least require one at compile time. I search for this unknown implementation in the Oracle's site but there are just a few words explaning how it works and no code at all.

Is that implemetation hidden or is created automatically by the java compiler?

Does an aggregate operation need one?

double average = roster
  .stream()
  .filter(p -> p.getGender() == Person.Sex.MALE)
  .mapToInt(Person::getAge)
  .average()
  .getAsDouble();
```

roster is a List<Person> instance of ArrayList<Person>

Person is a simple class that represents a person

答:
The lambda object is created automatically by the compiler.

Any "functional" interface (that is an interface with just 1 function) can be the target for one. The equivalent non-lambda code would be:

```<code>double average = roster
.stream()
.filter(new Predicate<Person>(){
          public boolean test(Person p){
              return p.getGender() == Person.Sex.MALE;
           }
      })
.mapToInt(Person::getAge)
.average()
.getAsDouble();
</code>```

And it could have been implemented this way by the compiler but they were concerned with efficiency and wanted people to be able to reference methods directly. So instead they translate the lambda to a private method which may or may not be static (depending on whether this is captured) and use a meta factory that creates the actual lambda object which then forwards to the actual code in the private method.

For more information see the following page.

Title: How the Stream.filter() method works?

Body:
The lambda object is created automatically by the compiler.

Any "functional" interface (that is an interface with just 1 function) can be the target for one. The equivalent non-lambda code would be:

double average = roster
.stream()
.filter(new Predicate<Person>(){
          public boolean test(Person p){
              return p.getGender() == Person.Sex.MALE;
           }
      })
.mapToInt(Person::getAge)
.average()
.getAsDouble();

And it could have been implemented this way by the compiler but they were concerned with efficiency and wanted people to be able to reference methods directly. So instead they translate the lambda to a private method which may or may not be static (depending on whether this is captured) and use a meta factory that creates the actual lambda object which then forwards to the actual code in the private method.

For more information see the following page.


问:
How should I determine my rates for writing custom software?
For a custom software that will likely take a year or more to develop, how would I go about determining what to charge as a consultant? I'm having a hard time coming up with a number, and searches online are providing vastly different numbers (between $55/hr and $300/hr).

I don't want to shoot too low because it's going to take me so much time (and I'm deferring my education for this project). I also don't want to shoot too high and get unpleasant looks and demand for justification. FWIW I live in Canada, and have approx. 10 years of development experience.

I've read the "take your salary and divide it by 1000" rule of thumb, but the thing is I don't have a salary. Currently I'm just doing fairly small programming tasks for a friend who is starting a marketing company, pricing each task fairly arbitrarily. I don't know what I would make over the course of a year doing it, but it would be incredibly low.

My responsibilities for the project would be the architecture, programming, database, server, and UX to some degree. It's going to be a public facing web service so I will also need to put a lot of effort into security and scalability.

Any advice or experience?

答:
You should define your rates based on the value you're delivering to the client. If your custom software is going to increase their sales or profits, you better increase your rate since they can afford it and it's worthwhile for them. This is called "value-added"

Never underestimate your own value.

You can charge $20/hr if you want to compete with outsourcing firms, or you can charge $100/hr and frame your solution as a value-add for the business that will increase profits.


问:
Design Patterns for Javascript
A lot of web frameworks have a MVC-style layout to code and approaching problems. What are some good similar paradigms for JavaScript? I'm already using a framework (jQuery) and unobtrusive js, but that still doesn't address the problem I run into when I have more complex web apps that require a lot of javascript, I tend to just end up with a bunch of functions in a single, or possibly a few files. What's a better way to approach this?</p>

答:
Namespacing: Don't forget to use objects as a pseudo-package (most frameworks do this, you should also):

```<code>var YourCompany = {};

YourCompany.util = {};

YourCompany.util.myFunction = function() { /* ...  */ }
</code>```

You don't necessarily need to set it up that way, and use whatever naming conventions you prefer, but the namespacing will help you out a lot (makes it easier on refactoring search-and-replace too, when you decide to move something).

ContentLicense: CC BY-SA 2.5

Title: Design Patterns for Javascript

Body:
Namespacing: Don't forget to use objects as a pseudo-package (most frameworks do this, you should also):

var YourCompany = {};

YourCompany.util = {};

YourCompany.util.myFunction = function() { /* ...  */ }

You don't necessarily need to set it up that way, and use whatever naming conventions you prefer, but the namespacing will help you out a lot (makes it easier on refactoring search-and-replace too, when you decide to move something).


答:
AngularJS utilize web front end technologies (HTML & CSS) and don't abstract them out with extra layer like what other frameworks; therefor you require a strong web front end framework to work with AngularJS providing standard language, will supported framework and a plug and play responsive implementation.

let's consider the other options that works with AngularJS:

not using a framework and create everything from scratch: unless you are a very good web developer with a strong team supporting you and plenty of time; avoid this option, this requires long experience and knowledge in web technologies not to mention compatibility handling, responsive implementation.

using other frameworks: i don't see many reasons not to go for other frameworks like ZURB Foundation other than personal taste and good support; bootstrap is wildly used now and well supported, and you can find plenty of snippets and template websites online such as Bootsnipp.

bottom-line using bootstrap with AngularJS would definitely increase your productivity and chances of success, reduce cost and implementation effort, personally i think the mix is priceless.

Title: Using AngjularJS with Twitter Bootstrap

Body:
I want to refactor an OLD legacy application and give it a new feel... so, I want to use Twitter Boostrap for the UI... I've also been playing around a lot with AngularJS... is it common place to use them in conjunction with one another? Is it even the correct question to ask? I've done about an hour's worth of "googling" on the subject and I see a lot of people using the CSS-portion of bootstrap with Angular, however, do I gain anything (or lose anything) by also including the bootstrap .js portion, as well?

Thanks.


问:
Flaws in my PHP development setup - sharing sources causing lags
I have following development setup for my PHP projects:

Working station running on Windows 7 with PhpStorm IDE.

GIT for version controlling.

CentOS on virtual machine (VirtualBox) with Apache and MySQL (copy of production server).

So far, I've been sharing project's source folders between host and guest systems and it was working quite well only really slow. The reason behind this is that Apache was reading files from remote folder (mounted locally). After doing some research, I found out that this set up can be improved by using disk mapping (Samba) instead of folder sharing. So I did that change. I configured my PhpStorm to automatically deploy files to mapped drive. Everything works like a charm now, except for one problem - when I change branches I need to synchronize project's local folder with the one on mapped drive and that takes time, a lot of time (like branching in SVN). Is there another way to handle this than just working on files directly on mapped drive?

答: I have used a setup similar to yours to do local develoment. In my case, I set up git (actually I use Mercurial, but same idea), and added the VM as a remote on my local repo. I can then check out different branches or commits through an SSH connection to the VM. If the VM has a GUI, you could also manage the remote repo that way. If you pretty much always want the VM to use the latest commit on master, you can even set up a git hook that automatically checks it out when you push up.</p>


问:
Where to start when designing an application that allows plugins
I'm building an application, and I'm thinking long-term I would like to be able to allow plugin support. The application I'm creating is a Java based application. How could I allow plugins using a scripting language, or is it better to require plugins to use Java?

Would I need to create some sort of plugin interface to allow the use of plugins?

Any ideas of references of where to start?

答:
If you ask me, plugins using Java is better as it is relatively easier than scripting languages. You have to provide some sort of interface to the plugins. After you successfully implemented the plugin architecture, it is also useful for yourself to implement extra-functionality to your application, without breaking the existing code. See how NetBeans or Eclipse works. Those softwares load a number of files in the name of "packages" during start-up. Those packages are actually a kind of plugins. Alternatively, implementing a successful plugin architecture require quite some effort and costs performance (see the load times of Eclipse).

https://stackoverflow.com/questions/465099/best-way-to-build-a-plugin-system-with-java
http://www.javaranch.com/journal/200607/Plugins.html


问:
Exception handling in WIn Forms application
When handling exceptions for example in a method in my presentation logic, is it ok to catch all possible exceptions in a one catch block as follows if the only purpose here is alerting the user.

```<code>private void Do()
{
    try
    {
        //  Do some stuff here which might throw an exception
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}
</code>```

Or else should we always catch every possible exceptions (like OutOfMemoryException, NullReferenceException etc. followed by more generalized exceptions) in separate catch blocks ?

Since the information in e.message is not relevant for average users, we could do like

```<code>MessageBox.Show("Exception occurred and contact system administrator");
</code>```

Is that the standard way ?

NOTE : My sole purpose is to alert user and try to keep the system up (with out crashing)

答:
IMHO if that is ok depends mostly on the context of the Do method, and what you know about the stuff in the try-block. Lets assume you have an UI application, and the Do part is just a Button-Click handler. Lets further assume the part within the try block does some fairly complex non-UI things which might fail with any kind of unforseeable exception (but normally it should not, and when it does, there has happened something severe). So if your failure handling strategy is to display the exception message to the user and let him or her decide what to do next (for example, he can decide to close and restart the application, or to ignore the error), then catching all type of exceptions is just the way to go. That might not be a perfect solution, but it is pragmatic and works for a lot of real world cases.

Of course, you should make sure the user has enough information to make the correct decision. A general message like "an Exception occurred" is typically not enough information. So think about what you can present to your users and what not. If you fear your typical user cannot understand the failure message, show him the "general message", but make sure the support people or admin can get the real message afterwards (maybe from a log file, maybe from a separate menu entry etc.) If you use something like a log file, logging the stack trace of the exception maybe also a good idea, since it will help you (the developer) to find the root cause in case of an internal program error.

However, if you know that the part within the try block can sometimes throw an exception which makes it impossible for your program to proceed (like an OutOfMemoryException, or maybe an exception which indicates that a severe internal program error has occurred, or something like that), you should catch that individually, show the reason of failure to the user and end the program afterwards automatically. Think about what the most user-friendly behaviour is. Does it make sense to let the user decide if the program should proceed, or is there a chance if the user ignores the error, that he will loose or destroy parts of his data now? If the latter is the case, better not let the user decide - better end the program in a controlled manner.

The former was just an example - the gist is: think about the responsibilities for failure handling: what is in your case the responsibility of the user, what is the responsibility of the UI part (the button handler), and what is the responsibility of the part in the try block - then you can make a decision of which exceptions to catch and which information to display.


问:
Whole Program in CASE
I'm going to start by saying, this may not be the correct place to post this.

So...I'm working in Embedded Development, using C.

Is there any benefit or disadvantages to doing the following:

```<code>while (1)
{
   i++;
   switch (i)
   {
      case 1:
         x_get_inputs();
         break;
      case 2:
         x_react();
         break;
      case 3:
         x_set_outputs();
         i = 0;
         break;
      default:
         break;
    }
}
</code>```

Rather than a standard list of function calls?

I think this is similar to a Round Robin RTOS?

My logic is that the program cycle time will be shorter, and as such this should be more efficient?

答:
Assumed the variable i is initialized to 0 at the beginning, your code is just an obfuscated version of

```<code>while(1)
{
    x_get_inputs();
    x_react();
    x_set_outputs();
}
</code>```

(and it took me some minutes to understand that your code really has this semantics, and no hidden emulated goto). That's shorter and showing explicit what's going on here. Your original version is hard to understand, hard to maintain, and I guess it will be not even bring you any advantages at the assembly or performance level. So for this case, I would advice against it.

On the other hand, when this is really called in a context where i can have an arbitrary value from 0 to 2 beforehand, the construct makes more sense (though I think there should be at least a safety guard around this preventing i beeing >2, which would end in an endless loop without calling any of the three functions any more.

However, IMHO the construct is still overly complicated even for that case. Here is a shorter version, which does the same:

```<code>while (1)
{
   switch (i)
   {
      case 0:
         x_get_inputs();
      case 1:
         x_react();
      case 2:
         x_set_outputs();
      default:
         i = 0;
    }
}
</code>```

You can make this even more clean by replacing the integer i by an enum (with well choosen names), and change the name of i to something like "firstOperation". Furthermore, one should add some kind of safeguard for the i>2 case as well. I leave this as "an exercise for the reader".

Title: Whole Program in CASE

Body:
Assumed the variable i is initialized to 0 at the beginning, your code is just an obfuscated version of

while(1)
{
    x_get_inputs();
    x_react();
    x_set_outputs();
}

(and it took me some minutes to understand that your code really has this semantics, and no hidden emulated goto). That's shorter and showing explicit what's going on here. Your original version is hard to understand, hard to maintain, and I guess it will be not even bring you any advantages at the assembly or performance level. So for this case, I would advice against it.

On the other hand, when this is really called in a context where i can have an arbitrary value from 0 to 2 beforehand, the construct makes more sense (though I think there should be at least a safety guard around this preventing i beeing >2, which would end in an endless loop without calling any of the three functions any more.

However, IMHO the construct is still overly complicated even for that case. Here is a shorter version, which does the same:

while (1)
{
   switch (i)
   {
      case 0:
         x_get_inputs();
      case 1:
         x_react();
      case 2:
         x_set_outputs();
      default:
         i = 0;
    }
}

You can make this even more clean by replacing the integer i by an enum (with well choosen names), and change the name of i to something like "firstOperation". Furthermore, one should add some kind of safeguard for the i>2 case as well. I leave this as "an exercise for the reader".


问:
What exactly is the build number in MAJOR.MINOR.BUILDNUMBER.REVISION
What I think about Build Numbers is that whenever a new nightly build is created, a new BUILDNUMBER is generated and assigned to that build. So for my 7.0 version application the nightly builds will be 7.0.1, 7.0.2 and so on. Is it so? Then what is the use of a REVISION after the build number? Or is the REVISION part being incremented after each nightly build? I am a little confused here... do we refer to each nightly build as a BUILD?

The format is mentioned here: AssemblyVersion - MSDN

答:
Let me just say how I see and use it....

ProgramName version major.minor.build.revision

major:
For me is the current project I am working on. The number will not change until I start a new project of the same program name. This means I will literally be writing a new program of the same gender (example: access v1 - access v-2 - access v-3 * all the same program but completely rewritten).

minor:
This means I am adding functionality to the current published project. For example maybe I added the ability to print a receipt or added the ability to import pictures. Basically additional functionality I want to add now and not wait for the next major release to do it.

build:
This I use to indicate very small changes in the published major.minor version. This could be a change in the layout, colour scheme, etc.

revision:
This I use to indicate a bug fix in the current published major.minor.build - There are occasions where I am not progressing the current project and a bug arises. This bug needs to be fixed and published. It just means I am fixing what I already published to work properly. I would also use this if I am working on a new build, a new addition or started a new major version. The published version obviously needs to be patched while we are waiting for the next major, minor or build release.

So in this manner a finished or stalled project can still be fixed and made useable until the next release is published.

I hope this gives someone a better understanding of how this type of versioning would (or should) work. To me it is the only definition and practice that makes any type of real sense when using this type of versioning.


答:
The whole confusion stems from the different semantics that MS uses for "Build number" and especially "Revision". The terms just mean different things.

Most people (myself included) use a semantic version numbering scheme where you just get a higher BUILD number whenever you have to make a new build for whatever reason. For us, a hotfix is considered just another code change, and the BUILD part increases automatically with every CI run. Modules with same MAJ.MIN.REV are considered interchangeable, and the BUILD tells you which one is the most recent.

Incrementing REVISION, however, indicates a new permanent release branch, that's why we place it before BUILD. The downside of that approach is, that we might get the following sequence of events:

commit number 4711: Alice added feature A

CI produces build 1.2.3.100

commit number 4712: Bob modified feature B

commit number 4713: Alice fixed feature A (the "hotfix")

CI produces build 1.2.3.101

As you can see, the hotfix is not the only change contained in the next build, also Bob's modification become part of that build. If you want to stabilize the current branch, you may run into troubles as you never can't be sure whether or not Bob just added a bunch of bugs.

MS uses both terms differently. The BUILD number is not automatically incremented, instead it can be considered being kind of a release branch, to freeze the code used for a particular version of the code. The REVISION indicates additional "hot" changes applied to that BUILD branch. The sequence would therefore be as follows:

commit number 4711: Alice added feature A to trunk/master

Carl creates build branch 1.2.100

CI produces build 1.2.100.0

commit number 4712: Bob modified feature B in trunk/master

commit number 4713: Alice fixed feature A in the 1.2.100 branch

CI produces build 1.2.100.1

The term REVISION may refer to

a product revision (that's how most people use it)

a revision of a particular daily build (that's what MS does)

The key difference between the two processes is, whether or not you want the ability to apply hotfixes to CI builds and thus, at which point in the process the branch is made. This aspect becomes important when you want to be able to pick a particular build at any time after all the tests succeeded and promote exactly that version to the next official release of your product.

In our case the CI tool creates a repository tag, so we always have the necessary information ready to use, when needed. With SVN it becomes even simpler, because tags and branches are implemented exactly in the same way - a tag is nothing more than a branch located under /tags.

See also

From the FAQ section at TFS branching strategy:

In what branch should I fix the P1 (hotfix) ticket?

The P1 should be fixed in the branch that is closest to the code base running in Production. In this case the P1 should be fixed in the Prod branch. By applying the fix in any other branch and rolling out the changes to production you risk releasing semi-finished or untested code from the subsequent iterations.

Now you may argue if it is safe to work directly against the Prod branch, think again, a P1 that requires immediate attention should not be a fundamental problem in the system. In case it is a fundamental problem it should be added to the Product backlog as it may require further analysis and discussion with the customer.

Another good read is the TFS branching guide

Title: What exactly is the build number in MAJOR.MINOR.BUILDNUMBER.REVISION

Body:
What I think about Build Numbers is that whenever a new nightly build is created, a new BUILDNUMBER is generated and assigned to that build. So for my 7.0 version application the nightly builds will be 7.0.1, 7.0.2 and so on. Is it so? Then what is the use of a REVISION after the build number? Or is the REVISION part being incremented after each nightly build? I am a little confused here... do we refer to each nightly build as a BUILD?

The format is mentioned here: AssemblyVersion - MSDN


问:
Which string search algorithm is actually the fastest?
I have been stuck for some time on which is the fastest string search algorithm, heard many opinions, but in the end I'm not sure.

I have heard some people saying that the fastest algorithm is Boyer-Moore and some saying that   Knuth-Morris-Pratt is actually faster.

I have looked up for the complexity on both of them but they mostly look the same O(n+m). I have found that in the worst case scenario Boyer-Moore has an O(nm) complexity compared to Knuth-Morris-Pratt which has O(m+2*n). Where n=length of text and m=length of pattern.

As far as I know Boyer-Moore has a linear-worst case-time if I would use the Galil Rule.

My question, Over all which is actually the fastest String search algorithm (This question includes all possible sting algorithms not just Boyer-Moore and Knuth-Morris-Pratt).

Edit: Due to this answer

What I'm exactly looking for is:

Given a text T and a pattern P I have to find all the appearances of P in T.

Also the length of P and T are from [1,2 000 000] and the program has to run under 0.15 sec.

I know that KMP and Rabin-Karp are enough to get a 100% score on the problem but I for one wanted to try and implement Boyer-Moore. Which would be best for this type of pattern search?

答:
Though I am slightly late to answer this question, but I think Z-Algorithm is much faster than any its counterparts. Its worst-case complexity is O(m+n) and it requires no preprocessing of the pattern/text. It is also very easy to code as compared to the other algorithms.

It works in the following manner.

For example, there is a string S ='abaaba'. We are to find z(i) values for i=0 to len(S)-1. Before going into the explanation, let me put lay down some definitions first.

z(i) = no. of characters of the prefix of S that matches the prefix of s(i).

s(i) = ith suffix of S.

The following are the s(i) values for s = 'abaaba'.

```<code>s(0) = 'abaaba' = S
s(1) = 'baaba'
s(2) = 'aaba'
s(3) = 'aba'
s(4) = 'ba'
s(5) = 'a'
</code>```

The z values are respectively

```<code>z(0) = 6 = length(S)
z(1) = 0
z(2) = 1
z(3) = 3
z(4) = 0
z(5) = 1
</code>```

For detail understanding of the algorithm, refer to the following links.

http://codeforces.com/blog/entry/3107

https://www.youtube.com/watch?v=MFK0WYeVEag

Now it takes O(N) to find all the z values without any pre-processing overhead. One would be wondering now how can you use this logic to match pattern in a given string?

Let's see with an example.
Pattern(P) : aba, Text(T) : aacbabcabaad.

Put this in the form P$T. ($ - any character that does not appear in either pattern or text. I'll come to the importance of $ in a little while.)

P$T = aba$aacbabcabaad

We know len(P) = 3.

All z values of P$T are

```<code>z(0) = 16 = len(P$T)
z(1) = 0
z(2) = 1
z(3) = 0
z(4) = 1
z(5) = 1
z(6) = 0
z(7) = 0
z(8) = 2
z(9) = 0
z(10) = 0
z(11) = 3
z(12) = 0
z(13) = 1
Z(14) = 1
Z(15) = 0
</code>```

Now which z(i) = len(P). Ans = 11. So our pattern is present at Ans-len(P)-1 = 7. -1 is for $ character.

Now why $ or any such special character is important. Consider P = 'aaa' and T = 'aaaaaaa'. Without the special character, all z(i) will have incremental values. One can still find the position of pattern in text with the below formulae:

Condition: z(i) >= len(P) and Position: Ans-len(P). But the condition in this case becomes a little tricky and confusing. I personally prefer to use the special character technique.

Body:
Though I am slightly late to answer this question, but I think Z-Algorithm is much faster than any its counterparts. Its worst-case complexity is O(m+n) and it requires no preprocessing of the pattern/text. It is also very easy to code as compared to the other algorithms.

It works in the following manner.

For example, there is a string S ='abaaba'. We are to find z(i) values for i=0 to len(S)-1. Before going into the explanation, let me put lay down some definitions first.

z(i) = no. of characters of the prefix of S that matches the prefix of s(i).

s(i) = ith suffix of S.

The following are the s(i) values for s = 'abaaba'.

s(0) = 'abaaba' = S
s(1) = 'baaba'
s(2) = 'aaba'
s(3) = 'aba'
s(4) = 'ba'
s(5) = 'a'

The z values are respectively

z(0) = 6 = length(S)
z(1) = 0
z(2) = 1
z(3) = 3
z(4) = 0
z(5) = 1

For detail understanding of the algorithm, refer to the following links.

http://codeforces.com/blog/entry/3107

https://www.youtube.com/watch?v=MFK0WYeVEag

Now it takes O(N) to find all the z values without any pre-processing overhead. One would be wondering now how can you use this logic to match pattern in a given string?

Let's see with an example.
Pattern(P) : aba, Text(T) : aacbabcabaad.

Put this in the form P$T. ($ - any character that does not appear in either pattern or text. I'll come to the importance of $ in a little while.)

P$T = aba$aacbabcabaad

We know len(P) = 3.

All z values of P$T are

z(0) = 16 = len(P$T)
z(1) = 0
z(2) = 1
z(3) = 0
z(4) = 1
z(5) = 1
z(6) = 0
z(7) = 0
z(8) = 2
z(9) = 0
z(10) = 0
z(11) = 3
z(12) = 0
z(13) = 1
Z(14) = 1
Z(15) = 0

Now which z(i) = len(P). Ans = 11. So our pattern is present at Ans-len(P)-1 = 7. -1 is for $ character.

Now why $ or any such special character is important. Consider P = 'aaa' and T = 'aaaaaaa'. Without the special character, all z(i) will have incremental values. One can still find the position of pattern in text with the below formulae:

Condition: z(i) >= len(P) and Position: Ans-len(P). But the condition in this case becomes a little tricky and confusing. I personally prefer to use the special character technique.


问:
How to submit a part of project based when other parts are not completely implemented yet
I have been given an online task in which I am supposed to develop a service which is based on some other class/service which has not been implemented yet but I have a rough API for that and the results return by my class would be used by some other class/service

I am not sure what would be the best way to return this. I mean shall I have some dummy/mock implementation for the service I am expecting or using in my class and also for the service that would use the result returned by my class or is it Ok to just develop my part and assume things based on the rough API spec.

For example :
I am in Team C and have to implement CService service. My class will call Team A's AService service (this is not implemented yet but I have a rough spec for this) and the results returned by my class would be used by Team B's service.

答:
You should use a stub/mock for the classes/services that you are using. That way you can test your own code without needing those classes/services.

For the code that calls you (Team B's service), you don't need to provide stubs/mocks. Your testcases should cover that side.

At the same time, try to keep a good communication with teams A and B. It will help to get a common understanding of how each API is expected to be used and, unless you are in a very strict development method, you might be able to change it still to make your development easier.


问:
How would I change the precision of a variable in Python?
I'm working on a 2D-physics engine, and I need a certain variable to be precise only to the hundredths. Are there any methods for basically shaving off all of that unneeded precision?

I have tried things like

```<code>"{0:.2f}".format(a)
</code>```

but that obviously produces a string, not a number.

I'm moving an object based upon its speed, and I want it to(obviously) stop when its value is 0.0, but it keeps going because its speed is really something like 0.0000562351.

答:
It is typical to compare floats using a tolerance, rather than by equality. This both avoids some of the issues with floating point arithmetic on computers and allows you to specify an appropriate level of precision. In your case, if you only care about hundredths of a unit:

```<code>if abs(speed - limit) < 0.01:
    ...
</code>```

For example:

```<code>>>> abs(0.0 - 0.0000562351) < 0.01
True
</code>```

Body:
It is typical to compare floats using a tolerance, rather than by equality. This both avoids some of the issues with floating point arithmetic on computers and allows you to specify an appropriate level of precision. In your case, if you only care about hundredths of a unit:

if abs(speed - limit) < 0.01:
    ...

For example:

>>> abs(0.0 - 0.0000562351) < 0.01
True


答:
Make sure you're up to date with the other teams' progress and details, and also develop your own dummy service.
This way you can test your code, create various dummy scenarios, and still keep it relevant to what the other team is developing.</p>

Title: How to submit a part of project based when other parts are not completely implemented yet

Body:
I have been given an online task in which I am supposed to develop a service which is based on some other class/service which has not been implemented yet but I have a rough API for that and the results return by my class would be used by some other class/service

I am not sure what would be the best way to return this. I mean shall I have some dummy/mock implementation for the service I am expecting or using in my class and also for the service that would use the result returned by my class or is it Ok to just develop my part and assume things based on the rough API spec.

For example :
I am in Team C and have to implement CService service. My class will call Team A's AService service (this is not implemented yet but I have a rough spec for this) and the results returned by my class would be used by Team B's service.


问:
Best way to let users/visitors alter the website design
What I am trying to do is give the users/visitors the option to alter the whole website based on their taste. So they can move for example the sticky bar from top to bottom, alter background colors, news box from left to right etc.

For users I will probably store all the information in the DB but I am not sure how I should handle this afterward. Should I store all the settings into a cookie instead of grabbing that info from the DB all the time and "rebuilding" the website based on their taste or do you have any other idea?

答:
Instead of using cookies, it would be smarter to use sessions: There is now only one cookie set, which would be some unique identifier of the user.And then indeed grab all the important user information from the database.

You can of course store this information in session variables afterwards, and only reload them if they are not set, or a user changed their preferences.


问:
Is there a more intelligent way to do this besides a long chain of if statements or switch?
I'm implementing an IRC bot that receives a message and I'm checking that message to determine which functions to call. Is there a more clever way of doing this? It seems like it'd quickly get out of hand after I got up to like 20 commands. </p>

<p>Perhaps there's a better way to abstract this?    </p>

```<code> public void onMessage(String channel, String sender, String login, String hostname, String message){

        if (message.equalsIgnoreCase(".np")){
//            TODO: Use Last.fm API to find the now playing
        } else if (message.toLowerCase().startsWith(".register")) {
                cmd.registerLastNick(channel, sender, message);
        } else if (message.toLowerCase().startsWith("give us a countdown")) {
                cmd.countdown(channel, message);
        } else if (message.toLowerCase().startsWith("remember am routine")) {
                cmd.updateAmRoutine(channel, message, sender);
        }
    }
</code>```

答:
"Intelligent" can be (at least) three things:

Higher Performance

The Dispatch Table (and its equivalents) suggestion is a good one. Such a table was called "CADET" in years past for "Can't Add; Doesn't Even Try." However, consider a comment to aid a novice maintainer on just how to manage said table.

Maintainability

"Make it beautiful" is no idle admonition.

and, often overlooked...

Resiliency

The use of toLowerCase has pitfalls in that some text in some languages must undergo painful restructuring when changing between magiscule and miniscule. Unfortunately, the same pitfalls exist for toUpperCase. Just be aware.


问:
Looking to simulate the rolling of a ball around a roulette wheel, while the resulting number is already known
I want to make a roulette board with a ball spinning and landing on a certain field.

The catch is that the field the ball will land on, is known beforehand.

I want the animation to look somewhat realistic, even though the result is decided beforehand.
So I think I need to calculate the path the ball will follow, starting from it's end position. However, in this case, it always needs to end up in the same starting position.

How can this be done?

答:
I think you have the right idea - start from the desired end point & work backwards.  You have at least 2 variables to play with - the initial speed of the ball & the initial speed of the wheel.

If you want to go nuts with this, remember you also have those diamond-shaped obstacles above the numbers on the wheel.  As the ball starts to lose momentum & curve into the numbers, it'll often hit one of those obstacles & take a crazy bounce.  That's a place where you can "adjust" the angle of the bounce & make it land where you want.

If you want to keep it simple, always start with the wheel in the same location & just make the (I forget - 34?) possible animations.  Playback could be as simple as "show Spin00.gif".


问:
Reconciling the Boy Scout Rule and Opportunistic Refactoring with code reviews
I am a great believer in the Boy Scout Rule:

Always check a module in cleaner than when you checked it out." No
  matter who the original author was, what if we always made some
  effort, no matter how small, to improve the module. What would be the
  result? I think if we all followed that simple rule, we'd see the end
  of the relentless deterioration of our software systems. Instead, our
  systems would gradually get better and better as they evolved. We'd
  also see teams caring for the system as a whole, rather than just
  individuals caring for their own small little part.

I am also a great believer in the related idea of Opportunistic Refactoring:

Although there are places for some scheduled refactoring efforts, I
  prefer to encourage refactoring as an opportunistic activity, done
  whenever and wherever code needs to cleaned up - by whoever.
  What this means is that at any time someone sees some code that isn't
  as clear as it should be, they should take the opportunity to fix it
  right there and then - or at least within a few minutes

Particularly note the following excerpt from the refactoring article:

I'm wary of any development practices that cause friction for
  opportunistic refactoring ... My sense is that most teams don't do
  enough refactoring, so it's important to pay attention to anything
  that is discouraging people from doing it. To help flush this out be
  aware of any time you feel discouraged from doing a small refactoring,
  one that you're sure will only take a minute or two. Any such barrier
  is a smell that should prompt a conversation. So make a note of the
  discouragement and bring it up with the team. At the very least it
  should be discussed during your next retrospective.

Where I work, there is one development practice that causes heavy friction - Code Review (CR). Whenever I change anything that's not in the scope of my "assignment" I'm being rebuked by my reviewers that I'm making the change harder to review. This is especially true when refactoring is involved, since it makes "line by line" diff comparison difficult. This approach is the standard here, which means opportunistic refactoring is seldom done, and only "planned" refactoring (which is usually too little, too late) takes place, if at all.

I claim that the benefits are worth it, and that 3 reviewers will work a little harder (to actually understand the code before and after, rather than look at the narrow scope of which lines changed - the review itself would be better due to that alone) so that the next 100 developers reading and maintaining the code will benefit. When I present this argument my reviewers, they say they have no problem with my refactoring, as long as it's not in the same CR. However I claim this is a myth:

(1) Most of the times you only realize what and how you want to refactor when you're in the midst of your assignment. As Martin Fowler puts it:

As you add the functionality, you realize that some code you're adding
  contains some duplication with some existing code, so you need to
  refactor the existing code to clean things up... You may get something
  working, but realize that it would be better if the interaction with
  existing classes was changed. Take that opportunity to do that before
  you consider yourself done.

(2) Nobody is going to look favorably at you releasing "refactoring" CRs you were not supposed to do. A CR has a certain overhead and your manager doesn't want you to "waste your time" on refactoring. When it's bundled with the change you're supposed to do, this issue is minimized.

The issue is exacerbated by Resharper, as each new file I add to the change (and I can't know in advance exactly which files would end up changed) is usually littered with errors and suggestions - most of which are spot on and totally deserve fixing.

The end result is that I see horrible code, and I just leave it there. Ironically, I feel that fixing such code not only will not improve my standings, but actually lower them and paint me as the "unfocused" guy who wastes time fixing things nobody cares about instead of doing his job. I feel bad about it because I truly despise bad code and can't stand watching it, let alone call it from my methods!

Any thoughts on how I can remedy this situation ?

答:
Sometimes, refactoring is a bad thing.  Not for the reasons that your code reviewers are giving, though; it sounds like they don't really care about the quality of the code, and you do care, which is awesome.  But there are two reasons that should stop you from refactoring: 1. You can't test the changes you made with automated tests (unit tests or whatever) or 2. You're making changes to some code that you don't understand very well; i.e., you don't have the domain specific knowledge to know what changes you should make.

1. Don't refactor when you can't test the changes you made with automated tests.

The person doing your code review needs to be able to be sure that the changes you made did not break anything that used to work.  This is the biggest reason to leave working code alone.  Yes, it would definitely be better to refactor that 1000 line long function (that really is an abomination!) into a bunch of functions, but if you can't automate your tests then it can be really hard to convince others that you did everything right.  I have definitely made this mistake before.

Before refactoring, make sure there are unit tests.  If there are not unit tests, write some!  Then refactor away, and your code reviewers will have no (legitimate) excuse for being upset.

Don't refactor pieces of code that require Domain-specific knowledge you don't have.

The place I work has a lot of chemical engineering-heavy code.  The code base uses the idioms common to chemical engineers. Never make changes that are idiomatic to a field. It might seem like a great idea to rename a variable called x to molarConcentration, but guess what?  In all the chemistry texts, molar concentration is represented with an x.  Renaming it makes it harder to know what is actually going on in the code for people in that field.

Instead of renaming idiomatic variables, just put comments explaining what they are.  If they are not idiomatic, please rename them.  Don't leave the i, j, k, x, y, etc. floating around when better names will work.

Rule of thumb for abbreviations: if, when people are talking, they use an abbreviation, it is okay to use that abbreviation in the code. Examples from the code base at work:

We have the following concepts which we always abbreviate when talking about them: "Area of Concern" becomes "AOC", "Vapor cloud explosion" becomes VCE, stuff like that.  In our code base, somebody refactored all the instances called aoc to AreaOfConcern, VCE to vaporCloudExplosion, nPlanes to confiningPlanesCount... which made the code actually much harder to read for people that had the domain specific knowledge.  I've been guilty of doing stuff like this too.

This might not actually apply in your situation at all, but there are my thoughts on the issue.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Java is to JavaScript as car is to carpet.

  — Chris Heilmann

LastEditorDisplayName: Roger Pate


问:
putting methods in base class that doesnt make sense/belong there
I've been lately thinking over design principles and patterns and a question did strike me.

Let us say, I want to design a racing game. I want to design the classes for a variety of cars.

each car may have different feature

the most common features can be put in the base class - 'Car'

Now, I learned that you should always strive to work with abstractions.

All the code that tries to manipulate the car will try to call the abstract methods on Car like Car.Accelerate(), Car.TurnLeft(), etc...

But what about the specific features? Like some cars might have rocket thrusters or a parachute and you might want to use them (I know this sounds ridiculous, but my point here is 'There might be special features in derived classes that might not justify the actual type(or base type) of that specific class')?

So, what about them?

Would you rather raise few more abstract methods in base class making it less cohesive, or would you put some if blocks and type casts (to get the actual class object and use that method) making it more coupled?

答:
Forget about design right now.  Your idea for the system is too ill-formed to decide on low-level design details like class inheritance.  Instead decide on some exact use cases and implement them.  Then implement some more use cases.  Continuously refactor the code to eliminate duplication.  Introduce interfaces to eliminate circular dependencies.  When it starts getting messy and you aren't sure how to proceed, then you can post code to stackoverflow.

After you get considerable practice coding, then you will be able to visualize more of the implementation earlier in the process.


答:
Try to think of it the other way around: If you had to drive from A to B and you didn't care about the roads you use or the time you get there, you might just take a Car, Accelerate() it, and Stop() whenever you're there. So, an abstract kind of Car will easily suffice for the purpose. I imagine many people would use that Car while they don't actually care for the details.

But then there are circumstances where you actually need speed. You need a rocket booster in order to arrive in time. So what you do, is not get some Car but a RocketBoostedCar. It'll provide you means to AccelerateWayFaster() than other cars and, well, there you go - pretty fast.

My point is: if you actually need special features that an abstract can't deliver, you already know that you have a concrete (special) object. You probably asked for it (using its constructor, or telling a factory to produce a special kind). And if you have that "special" Car, you can use its special features.

Title: putting methods in base class that doesnt make sense/belong there

Body:
I've been lately thinking over design principles and patterns and a question did strike me.

Let us say, I want to design a racing game. I want to design the classes for a variety of cars.

each car may have different feature

the most common features can be put in the base class - 'Car'

Now, I learned that you should always strive to work with abstractions.

All the code that tries to manipulate the car will try to call the abstract methods on Car like Car.Accelerate(), Car.TurnLeft(), etc...

But what about the specific features? Like some cars might have rocket thrusters or a parachute and you might want to use them (I know this sounds ridiculous, but my point here is 'There might be special features in derived classes that might not justify the actual type(or base type) of that specific class')?

So, what about them?

Would you rather raise few more abstract methods in base class making it less cohesive, or would you put some if blocks and type casts (to get the actual class object and use that method) making it more coupled?


问:
Why do arrays in Java not override equals()?
I was working with a HashSet the other day, which has this written in the spec:

[add()] adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2))

I was using char[] in the HashSet until I realized that, based on this contract, it was no better than an ArrayList! Since it's using the non-overridden .equals(), my arrays will only be checked for reference equality, which is not particularly useful. I know that Arrays.equals() exists, but that doesn't help when one is using collections such as HashSet.

So my question is, why would Java arrays not override equals?

答:
The fundamental difficulty with arrays overriding equals is that a variable of a type like int[] may be used in at least three fundamentally different ways, and the meaning of equals should vary depending upon usage.  In particular, a field of type int[]...

...may encapsulate a sequence of values in an array which will never be modified, but may be shared freely with code that won't modify it.

...may encapsulate exclusive ownership of an integer-holding container which may be mutated at will by its owner.

...may identify an integer-holding container which some other entity is using to encapsulate its state, and thus serve as a connection to the state of that other entity.

If a class has an int[] field foo which is used for either of the first two purposes, then instances x and y should regard x.foo and y.foo as encapsulating the same state if they hold the same sequence of numbers; if the field is used for the third purpose, however, then x.foo and y.foo would only encapsulate the same state if they identify the same array [i.e. they're reference equal].  If Java had included different types for the three usages above, and if equals took a parameter identifying how the reference was being used, then it would have been appropriate for int[] to use sequence equality for the first two usages and reference equality for the third.  No such mechanism exists, however.

Note also that the int[] case was the simplest kind of array.  For arrays containing references to classes other than Object or array types, there would be additional possibilities.

A reference to a sharable unchanging array which encapsulates things that will never change.

A reference to a sharable unchanging array which identifies things owned by other entities.

A reference to an exclusively-owned array which encapsulates references to things that will never change.

A reference to an exclusively-owned array which encapsulates references to exclusively-owned items.

A reference to an exclusively-owned array which identifies things owned by other entities.

A reference that identifies an array owned by some other entity.

In cases 1, 3, and 4, two array references should be considered equal if corresponding items are "value-equal".  In cases 2 and 5, two array references should be considered equal if they identify the same sequence of objects.  In case 6, two array references should be considered equal only if they identify the same array.

For equals to behave sensibly with aggregate types, they need to have some way of knowing how references will be used.  Unfortunately, Java's type system has no way of indicating that.


答:
program your wheel display with a sliding origin.   Run the "spin down" algorithm without
display, change the origin so the ball will stop on the right number.  Run the spin-down
algorithm again with display and real time delays.</p>

Title: Looking to simulate the rolling of a ball around a roulette wheel, while the resulting number is already known

Body:
I want to make a roulette board with a ball spinning and landing on a certain field.

The catch is that the field the ball will land on, is known beforehand.

I want the animation to look somewhat realistic, even though the result is decided beforehand.
So I think I need to calculate the path the ball will follow, starting from it's end position. However, in this case, it always needs to end up in the same starting position.

How can this be done?


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
DO NOT TAKE DOWN THE SITE

Not if he's paying for the hosting and its under his name.  That might be construed as illegal access or hacking - resulting in the possibility of YOU facing criminal charges.

You sent a final invoice.  If he doesnt pay, take him to small claims court (or your country's equivalent).

These things happen... next time require payment upon delivery and have a written contract.

Title: How to get money from reluctant client?


问:
What is the session about simplicity that Martin Odersky suggested during the "Scala with style" talk?
The video of Scala with style is here: http://parleys.com/play/51c1994ae4b0d38b54f4621b/chapter21/about

It's around 41:10 that he suggested another talk.

I can not hear the name of speaker or the name of the session very clearly.

Could someone help me to figure that out?

答:
The talk he's referring is "Simple Made Easy", here's an InfoQ link for you.

A great talk by the way. For the most part it's language agnostic, so it's a worthwhile watch even if you're not interested in Clojure itself. I highly recommend it.

Quoting the InfoQ summary:

Rich Hickey emphasizes simplicity’s virtues over easiness’, showing that while many choose easiness they may end up with complexity, and the better way is to choose easiness along the simplicity path.


问:
delegating program logic to lower-level objects
I'm writing a library for use in scientific computing and ran into a bit of a quandary. The types at work here are a class M which consists of some data and a reference to a container class C. There are many different implementations of C and I devoted a lot of work to making sure that M objects could use C objects without knowing their internal representation.

The code may be used for high-performance scientific computing someday, so speed actually is a concern. If M were to break the encapsulation of C objects, the code could run faster. I tested this and indeed I could get a 50% speedup. But, that would involve lots of repeated code and violation of the open-closed principle.

Alternatively, I can take the behavior that M needs to perform and delegate it to C. By default, C will use the same implementation-agnostic algorithm that I had before, but the logic has just moved downtown to a new class. The advantage of this approach is that, if CO is an implementation of C which can do substantially better than the default implementation, it can override that method with its own version.

There is, at present, only 1 method that M will need to delegate to C. I can imagine at most 2 more behaviors that will need to be dealt with in this way. There may be a bit of repeated code, but it could be handled with a code generator too.

Is this a common approach? If so, what's it called? If not, is that because it's a terrible idea for some reason that I haven't noticed? It's not quite the strategy pattern; most of the container objects don't even bother implementing their own strategy, they use the default.

答:
Unless you have multilayered architecture and these classes fall in different layers, one way to think about this is in terms of responsibilities (given that OO aspects of your program are unclear to me from the question), instead of whether one class is "lower" or "higher". You would ideally want every class to have exactly one responsibility (which is the single responsibility principle) regardless of whether it exposes one method or many. In my experience, that goes a long way in achieving open-closed design, because the responsibility that you delegate to a class is well-contained within the class. As you extend your application, either you will have new classes with new responsibilities, or you will be extending existing classes if the functionality you are adding will fit in the existing classes' responsibilities.

Based on your description, whether the method is in M or in C, you can allow the derived class to override the method and improve the performance. And a derived class of M on a particular platform can also be one with the code that is targeted towards that platform instead of generic platform so that it improve the performance.

However, when you are thinking about generic implementation and platform specific optimizations, you do need to consider whether having them in a single class will add more than a single responsibility in one place. (And if this issue is not limited to a single class, then you may need to consider it at a higher level, e.g. see Separation of Concerns principle).

A second issue that comes into picture in this example may be whether M and C (if they needed to be two separate classes because of different responsibilities) is whether they need to be coupled (i.e. M needs to instantiate or directly use C or vice versa). In many cases that can be left up to the caller such that the caller would instantiate C or an implementation of C, and then pass it to M. In such a case, M only works against C (or an interface from which C is derived) and as you add more implementations of C, the calling code picks the correct one and then passes to M.

Wherever possible, I also look at other examples that may have already been implemented that either I know of from past projects, or that are publicly available, e.g. in .NET Framework Class Library (it doesn't necessarily have to be in the language you are using). FCL thus has a SymmetricAlgorithm class which is derived for every implementation of a symmetric cryptographic algorithm (such as AES), but if you needed to use a password for encryption, you would have to use a DeriveBytes class (which has its own derivations) to first compute a Key and an Initialization Vector, which are the input to the SymmetricAlgorithm. It is this separation that allows various types of key derivation algorithms to be targeted towards any type of symmetric algorithm.


问:
Where to start when designing an application that allows plugins
I'm building an application, and I'm thinking long-term I would like to be able to allow plugin support. The application I'm creating is a Java based application. How could I allow plugins using a scripting language, or is it better to require plugins to use Java?

Would I need to create some sort of plugin interface to allow the use of plugins?

Any ideas of references of where to start?

答:
If you, or others with similar skills will be writing the plugins, then why not stay with the host language? If your application addresses a particular (non-software) area of expertise, and you want to give end-users the ability to write their own plugins, then a custom scripting language, well suited to expressing solutions in the end-users' domain of expertise, could make the plugin interface more accessible to them.

In your design you'll need to consider what parts of your application you want to expose to the plugin interface, and how to limit the potential damage from a badly written plugin. Those answers will guide you to the design of the interface.


问:
How important is it for a programmer to have an online presence?
I've noticed more and more mentions (both in posts here and in actual job descriptions) of programmers' "portfolios" - typically their public profiles on sites such as this, GitHub, etc.

How important is this, and would companies (startups in particular) reject (or immediately discard without even interviewing) otherwise outstanding candidates who don't have an online presence?

Personally, I prefer to keep a very low profile online. My name here cannot identify me, and I have other handles for other sites. I have a very spartan (and completely private) Facebook page. I do code on my own, but the code lives in local repositories. In general, the less information online about me, the better.

I could see a designer needing some sort of online portfolio, but for a programmer, is this really a big negative when job-searching?

答:
In my experience the personal site/brand/presence is incredibly helpful in having cool job opportunities present themselves. Especially in software development.

Good companies won't reject your application if you're without a solid online presence, but having one will definitely help companies find you.

Side note: If you're a freelancer looking for gigs, it's paramount that you spend some time creating a great online presence. Portfolio, github profile, stackoverflow, and public client reviews.

Today you will always be filtered based on your online presence first. Pretty much always.


问:
How to create a scoring system with time and correct answers for a game?
o create a scoring system with time and correct answers for a game?
up vote 0 down vote favorite

I have a small mobile quiz game, which consists of 30 questions, and a timer which starts from 0 seconds, and goes all the way up to 1 hour. Below you can see that my timer starts from 0, and it is displayed in the format of MM:SS.

```<code>var timestamp = new Date(0, 0, 0, 0, 0, 0);

function pad(n) { return ("0" + n).slice(-2); }

Number.prototype.pad = function (len) {
    return (new Array(len+1).join("0") + this).slice(-len);
}
</code>```

So, what I actually need is, some kind of formula, or system in order to receive a final score. So the more correct answers a user has, and the faster finishes the quiz, the more points gets. I know that this is kind of unrelated question for this forum, but I'm kind of stuck. I would like to hear your opinions, about the scoring system. So the smallest score should be 0, and the highest, well no limit.

答:
I would make the minimum = 0 when 0 questions were answered and time elapsed was 60 mins.

From there, add points for every question answered and total time left, e.g.

Let's say each correct answer = 200 points.
Each unused minute = 20 points.

5 questions answered in 60 mins = 1000 points.
5 questions answered in 30 mins = 1000 + 600 = 1600 points.
10 questions answered in 60 mins = 2000 points.

With this methodology, you may have to put in a minimum bound, i.e. the user must play for so many minutes and must have answered so many questions, e.g. let's say at least 2 answers and 2 minutes, which means that if someone quits a game after 2 mins and answering 2 questions:

2 questions answered in 2 mins = 400 + 1160 = 1560.

If you don't put this in, then if the user quits without answering at all in the very first minute, they still get 1200 points!

This is a very simple formula such that each question and every minute of time carries same weight. It makes it simpler for participants IMO. However, you may need to adjust your reward for each question and each unused minute, and that could make it better, for example, give so large a reward for questions as opposed to unused minutes (such as 600 points each for the question answered vs 5 each for unused time) so that if the user leaves in the first minute, they're still quite at the bottom.

An alternate approach is to use average # of questions per minute and reward that. You could calculate this ratio and multiply it with some constant (say 5000). Since the questions answered are the numerator and time taken is the denominator, if questions answered increase or time decreases then the reward increases. If questions answered decrease or the time increases, the reward decreases. With the same numbers as used before, the points using such a scheme could be like the following:

5 questions answered in 60 mins = 5/60 * 5000 = 416.
5 questions answered in 30 mins = 5/30 * 5000 = 833.
10 questions answered in 60 mins = 10/60 * 5000 = 833.

See though that the difference between the first approach and this one is that for the same number of average questions answered per minute (i.e. 5 q in 30 min vs. 10 q in 60 mins), the first approach rewarded differently, the second one rewards the same.


问:
Matching weighted unbalanced Bipartite graph
I am looking for a way to solve an assignment problem, but I am having some problems finding the correct algorithm to use.

I have 2 list of nodes A and B, and in my problem may the length of A not be equal to B.

In addition, the node a in A may not be a potential match with all nodes in B. The preference is given by a double where 0 is not interested to 1 that is very interested and then remove all matches with an edge of 0 after (As there might be matches that is impossible).

If a have a preference of x to b, will b have the same preference to a.

Example graph:

I am interested in creating the most optimal matching, meaning that to sum of the edges are the largest possible. In the example above would I be interested in the matching (1,1) and (3,2) leaving 2 in the left row unmatched, with a total edge weight of 1.9.

I have been looking at the stable marriage and the Hungarian algorithm but both these algorithm requires there to be an equal amount of nodes on each side, and they do not find the greatest total edge weight.

(Greatest or lowest is fines as I can just invert the edge weight)

Can any of you point me towards an algorithm that will solve this problem for me?

答: You can add dummy nodes to B having edges with weight 0 to nodes in A and then invert the weights of edges. Check http://en.wikipedia.org/wiki/Assignment_problem and I think you can apply Hungarian algorithm to this problem with the modification and after finding the minimum total cost you can invert the weights again.</p>


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答: There's some great advice here! My two cents worth is; Don't be overwhelmed by the BIG problem, don't forget that the exciting and challenging part of solving a problem is breaking it down into series of manageable and more importantly comprehensible sub-problems, which in turn break down again and again into smaller sub-problems. Any good programmer will typically do this on a minute by minute basis while they are creating code (using functions, methods, sub-routines etc to help reduce the overall complexity of a section of code) and this methodology typically applies to any BIG problem you face in life (not just at work).</p>


问:
Is it bad to use Unicode characters in variable names?
I recently tried to implement a ranking algorithm, AllegSkill, to Python 3.

Here's what the maths looks like:

No, really.

This is then what I wrote:

```<code>t = (µw-µl)/c  # those are used in
e = ε/c        # multiple places.
σw_new = (σw**2 * (1 - (σw**2)/(c**2)*Wwin(t, e)) + γ**2)**.5
</code>```

I actually thought it is unfortunate of Python 3 to not accept √ or ² as variable names.

```<code>>>> √ = lambda x: x**.5
  File "<stdin>", line 1
    √ = lambda x: x**.5
      ^
SyntaxError: invalid character in identifier
</code>```

Am I out of my mind? Should I have resorted for a ASCII only version? Why? Wouldn't an ASCII only version of the above be harder to validate for equivalence with the formulas?

Mind you, I understand some Unicode glyphs look very much like each other and some like     ▄ (or is that ▗▖ ) or ╦  just can't make any sense in written code. However, this is hardly the case for Maths or arrow glyphs.

Per request, the ASCII only version would be something along the lines of:

```<code>winner_sigma_new = ( winner_sigma ** 2 *
                    ( 1 -
                     ( winner_sigma ** 2 -
                       general_uncertainty ** 2
                     ) * Wwin(t,e)
                    ) + dynamics ** 2
                   )**.5
</code>```

...per each step of the algorithm.

答:
For variable names with well-known mathematical origins this is absolutely acceptable - even preferred.  But if you ever expect to distribute the code, you should place these values in a module, class, etc. so that IDE auto-complete can handle "typing" the strange characters.

Using √ or ² in an identifier - not so much.


问:
Why do people use markdown wysiwyg editors in web applications?
I understand the advantages of using markdown in local text files, and then taking those files and generating HTML. This is great for documentation, readme's in git repositories and posts for static site generators. It is very simple to create markdown syntax in any text editor, it's human readable, and you can create HTML from markdown relatively easily.

What I don't understand, is the advantages of using a wysiwyg editor for markdown in web applications, especially those that use a database server. (non-flat-file). I thought the whole point of using markdown was to remove the need for a wysiwyg editor. What is the advantage of using a markdown wysiwyg editor over an editor that just outputs HTML (avoiding the overhead of converting markdown to HTML in the process)?

clarification: basically I'm looking for technical advantages to having a WYSIWYG editor output markdown instead of HTML. To the end user the text form will look the same, so it's only dealing with markdown/html in the backend of an application. Anchor CMS sorta does this, and I'm wondering if there is an advantage over just plain HTML output.

答:
Real example: Confluence, a wiki made by Atlassian. It used to have both a markdown and a WYSIWYG editor in it, and you could flip between the modes. They removed the markdown mode and I was angry because it gave me better control/ability to do what I explicitly wanted, rather than fighting the WYSIWYG editor. (I think they still have an auto markdown-to-rich-text-as-you-type feature of sorts?) Certain things - like say, table layout - are definitely easier in markdown. So two parts: better/faster creation than a WYSIWYG editor, and more explicit control when the WYSIWYG editor fails you or is ironically more convoluted than the markdown itself.

Side note: I'm not actually sure how it is stored in the database under the hood. I have a feeling it was removed because some shiny new WYSIWYG feature didn't have a good corresponding feature in the markdown.


问:
I don't know how to understand the Wildcard type in Java
I am reading the Core Java (9th edition) by Cay S. Horstmann and Gary Cornell. After making an effort, I cannot still understand the ? super Manager. Here are some materials relating to this question.

```<code>public class Pair<T> {
    private T first;
    private T second;

    public Pair(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public void setFirst(T first) {
        this.first = first;
    }

    public void setSecond(T second) {
        this.second = second;
    }

    public T getFrist() {
        return this.first;
    }

    public T getSecond() {
        return this.second;
    }
}
</code>```

The Manager inherits from Employee, and Executive inherites from Manager. Pair has methods as follows:

```<code>void setFirst(? super Manager)
? super Manager getFirst()
</code>```

Since ? super Manager denotes any supertype of Manager, why I cannot call setFirst method with Employee (it is obvious that Employee is the supertype of Manager), but only with type Manager or a subtype such as Executive(but Executive is the subtype of Manager, not a supertype of Manager)?

答:
The difference seems to be the purpose of your variable.

If you use a variable of type Pair to read then you use Pair<? extends Manager>
In this case, when calling a method of pair that returns something parameterized, you will have the benefit of type-safe. But you almost cannot write anything into it, always a compilation error.

On the other hand, if you use a variable of type Pair to write then you use
Pair<? super Manager>. In this case, when calling a method of Pair<> type that receives a parametrized variable of type (or subtype) of Manager, you have the type safe.

Honestly, I don't see the difference between Pair<? super Manager> and  Pair<Manager> except that when you use Pair<? super Manager>
 the read methods in Pair<> returns generic java Object (ie not type safe for read, the compiler kind of discourages reading in this case)

I think seeing it as read and write like this is easier.

Now back to the why you cannot write an Employee object into your Pair<? super Manager>. This is because <? super Manager>
is actually a type that extends some unknown supertype of Manager. And because it is unknown, you don't know if Employee actually is a subtype of that unknown type.

Even more concrete: let's say Manager also implements an interface IManager.
Then <? super Manager> can be an IManager object and now Employee is not a valid substitution of IManager (because it is not a subtype of IManager). In this case, any subtype of Manager can be a substitution because it will be subtype of any unknown supertype of Manager. You can call setFirst(Executive e) here.