答:
you won't find your object if you get with a different object that is equal to the object you put

or to give an example:

```<code>MyClass obj1 = new MyClass(1);
MyClass obj2 = new MyClass(1);
assert obj1.equals(obj2);
assert obj1.hashcode()!=obj2.hashcode(); //this is wat happens if you don't inclde hashcode
table.put(obj1,2);
table.get(obj2) // will likely return null but that is a gamble
table.get(obj1) // but this will return the object passed in
</code>```

the reason for this is that HashTable (and HashMap) will use the hashcode to limit the space it has to search through to find the object and that relies on the assumption that if obj1.equals(obj2) then obj1.hashcode == obj2.hashcode()

Title: Using HashTable without overriding hashcode()

Body:
Today I was asked this question during an interview:

What will happen if we do not override the hashcode method for our
  class, then add it to HashTable and then try to get objects?

What could go wrong?

Body:
you won't find your object if you get with a different object that is equal to the object you put

or to give an example:

MyClass obj1 = new MyClass(1);
MyClass obj2 = new MyClass(1);
assert obj1.equals(obj2);
assert obj1.hashcode()!=obj2.hashcode(); //this is wat happens if you don't inclde hashcode
table.put(obj1,2);
table.get(obj2) // will likely return null but that is a gamble
table.get(obj1) // but this will return the object passed in

the reason for this is that HashTable (and HashMap) will use the hashcode to limit the space it has to search through to find the object and that relies on the assumption that if obj1.equals(obj2) then obj1.hashcode == obj2.hashcode()


问:
Using HashTable without overriding hashcode()
Today I was asked this question during an interview:

What will happen if we do not override the hashcode method for our
  class, then add it to HashTable and then try to get objects?

What could go wrong?

答:
Assuming your class extends only Object, then the hashCode() implementation of your class will depend on the object identity. I.e. that the hash code of two different instances will (almost certainly) be different, even if they hold the exact same value.

This means that you will most likely not find the object again in the Map (you might find it by chance, however).

ContentLicense: CC BY-SA 3.0


答:
The idea with a HashTable when you try retrieving an object is that the data structure computes the hash code of the object using the GetHashCode() method and then goes through a list using the Equals() method.

With default GetHashCode() implementation, two perfectly similar objects might end up yielding different hash codes which means that if you do not use the exact same instance, you will never find the your object in the HashTable.

In general, you want to make sure of two things when implementing hash codes:

If A.Equals(B) then A.GetHashCode()==B.GetHashCode()

Try to get a distribution of hash codes properly spread to get the maximum efficiency from the hash table (if too few hash codes are possible, you'll end up searching a list).


问:
Is it right to appraise Scrum members according to number of successful user stories completed?
When my Manager told to team that "from now on successful user stories will be considered for appraisal!"

We sat there for while shocked and that was one of the several jaw dropping moments he gave us.

We felt that was stupid idea, since this will ruin all concept and goal of agile development methodology.

Let me know what you people think? And how can we convince him?

答:
Most of the time, User Stories are completed in a collective effort. This makes it virtually impossible to base individual appraisal on this metric.

The metric itself can be easily manipulated since the planning process is also a team effort and even sooner than later, the whole system gets rigged. That's definitely what you don't want in a people focused process.

I think good performance has to be recognized by some kind of bonus system based on team success, but User Stories are not a good indicator of success.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
When is it acceptable to NOT fix broken windows?
In reference to broken windows, are there times when refactoring is best left for a future activity?

For example, if a project to add some new features to an existing internal system is assigned to a team that has not worked with the system until now, and is given a short timeline in which to work with - can it be ever be justifiable to defer major refactorings to existing code for the sake of making the deadline in this scenario?

答:
Most programmers are in the business of making money for their employer.
So when should refactoring happen: When it makes your firm money. Refactoring is time spent not spent on other projects and time saved in the future on this project.

Whether it's worth it is mostly up to your manager.


答:
What's gonna happen if we do not override hashcode method for our class, then add it to HashTable and then try to get objects?

It depends on what "adding to HashTable" means. Java's Hashtable doesn't have any add method. The interviewer probably meant put method, which takes in a key and a value. The value can be anything (could be even null in HashMap, which is the present-day version of Hashtable). Nothing special happens regardless of whether or not you override the value object's hashcode, or any other method.

The interviewer probably meant that the key object's hashcode wouldn't be overridden. Only then the object identity issues, as pointed out in other answers, come into play. Even then, you don't necessarily have to override the key's hashcode. For example, if you use Strings as keys, they already have an appropriate hashcode implementation in them. Besides, they can't be subclassed. Furthermore, if you do override hashcode but don't override equals, you may get some amazing behavior...

If the question really was exactly what you wrote, I would have teased the interviewer with these questions. A good programmer doesn't assume that the interviewer probably meant this or that. He asks instead.


问:
Formalizing programmers errors
Every one of us make errors leading to bugs. Once I wanted to start logging my errors for future analysis, probably mentioning project title, approximate time spent and the most important, the type of error. For example when I copy-pasted a fragment about 'x' and replaced every occurrence of 'x' with 'y' and forgot to replace a tiny piece, this goes to 'copy-paste error'. The usefulness of this approach depends on whether I can formalize my errors at all and probably minimizing the number of types to choose from. Otherwise I would start postponing, ignoring and so on so make this system useless.

Are there existing research in this area, probably a known minimum set of errors? Maybe some of you already tried to implement something like this and succeeded/failed?

答:
I would say that, if you want to understand your own programming errors, you would need to think about what matters to you.  I personally think of my programming errors in the following categories:

Clerical errors. Examples are typo's, calling the wrong functions/methods, getting the order of arguments wrong etc.  Typically compilers and type checkers catch such errors, or a simple exercising of the code does.

Misunderstandings of the program.  I may not have a full understanding of the program (or its components, classes, libraries or whatever), or misunderstood them, and wrote the wrong code that doesn't fit.  Usually these errors are caught by the first few cycles of routine testing.

Misunderstandings of the requirements.  I was supposed to do X but did Y.  Either I didn't understand the requirements fully or misunderstood them.  These are caught by the first few cycles of user testing.

Logical flaws.  These are the biggies.  Assuming I understood everything correctly, I still ended up writing the wrong code.  These are not simply "human" errors.  I was either lazy, didn't think things through carefully, used the wrong algorithms or data structures that didn't fit, the problem was too hard and complicated and I didn't put enough effort into doing it right, or perhaps I wasn't up to the task.  These are usually not caught by routine testing and go into deployment.  Big problem.  Every time I get one of these, I think long and hard about how to avoid such a thing in future.

Design flaws.  Used the wrong data structure, wrong interfaces, wrong program structure or whatever.  These things don't affect the program behaviour, but affect future development.  They result in a brittle system that can't be extended or modified easily, result in more and more bugs of the previous kinds over a period of time, or simply result in a structure that I am not proud of.  Some amount of painful and tedious refactoring is needed to fix these problems.  Every time I get one of these, I learn something new and deep about the nature of programming.

Title: Formalizing programmers errors


答:
You can think of it in the same way as asking for credit. Is it ok to borrow money to invest in X in the short-term, and pay for it on a long-term basis? There is no definitive answer, it can be in the best interest of the organization (e.g. to meet current client expectations), or it can be a disaster if done irresponsibly.

It all comes down to priorities, and management should be aware that although the number one priority is to make "code work", implement new features, and meet the customer expectations, every time you leave broken windows you are making that number one priority slower, more difficult, and requiring more resource investment. Also, 99% of the time it is not feasible to stop developing new features and concentrate every effort in "fixing the codebase".

In conclusion, yes it is acceptable to leave broken windows sometimes, just like it is acceptable to ask for a loan...just remember that you really, really have to pay for it in the future. And in the future, the time to do it will most likely not be that much greater than the time you have now.

Title: When is it acceptable to NOT fix broken windows?

Body:
In reference to broken windows, are there times when refactoring is best left for a future activity?

For example, if a project to add some new features to an existing internal system is assigned to a team that has not worked with the system until now, and is given a short timeline in which to work with - can it be ever be justifiable to defer major refactorings to existing code for the sake of making the deadline in this scenario?


问:
How important are UML diagrams for a successful project?
I'm in the middle of a project and I was asked to write UML diagrams (use cases,class diagram,etc). The project isn't very complex.

I was wondering if this be a waste of my time? Should I just be doing other fun stuff like writing code? And when is it not ok to build something without going through all of the conceptual phase? Is it all about complexity? And if so, how to measure it?

答:
UML is absolutely fantastic to get a graphical view of your architecture using a class diagram. Interaction using sequence diagram is magic for me.
The problem is not therefore UML but MDD for me.

I mean that if UML is a viewer of the code then it is really helpful for documentation purposes but certainly not for code generation. Project should be code centric and certainly not Model driven centric. UML should used at implementation stage using a live code and model synchronization.I mean not only at requirement level which requires too much investment for small return in productivity and quality.


问:
Is there any reason in a Java program for a special naming for a function arguments?
I'd like to know, why would I want to have a special prefixes for a function arguments, like "p_name", "p_age", "p_sex"? On the one hand it helps to distinguish parameter from local variable or field further in the function body, but would it help? On the other hand, I didn't saw such naming recommendations anywhere including official Java language conventions. Please advise any reasons for using such naming policy</p>

答:
Java allows you to assign a value to formal parameters, e.g.

```<code>public int sum(int a, int b) {
    a = a + b; // valid but evil!
    return a;
}
</code>```

However, this is a bad idea as programmers usually expect to access the values passed to the method. A naming convention might help to prevent accidental manipulation of parameters. But there is a better way: make the parameter final. The compiler won't let you assign to a final parameter and I don't see a reason why you should.

The only reason to keep up such a naming convention is consistency and thus readability. This of course requires that people are already used to the p_ prefix style. I personally believe that adding such a prefix decreases readability as these are two characters carrying very little information. These characters are much better spent in a good readable name.

BTW, such assignments won't have an effect outside of the method execution as Java uses call by value semantics for primitives and object references.

Body:
Java allows you to assign a value to formal parameters, e.g.

public int sum(int a, int b) {
    a = a + b; // valid but evil!
    return a;
}

However, this is a bad idea as programmers usually expect to access the values passed to the method. A naming convention might help to prevent accidental manipulation of parameters. But there is a better way: make the parameter final. The compiler won't let you assign to a final parameter and I don't see a reason why you should.

The only reason to keep up such a naming convention is consistency and thus readability. This of course requires that people are already used to the p_ prefix style. I personally believe that adding such a prefix decreases readability as these are two characters carrying very little information. These characters are much better spent in a good readable name.

BTW, such assignments won't have an effect outside of the method execution as Java uses call by value semantics for primitives and object references.


答:
I suspect the main reason is a mild form of OCD many programmers are afflicted with, which makes sorting or making things as separate that are already explicitly different feel "right" even when it carries little or no practical advantage.

Another common example for this is having the names of all enums prefixed with "Enum", and keeping them in a separate package named "enums".

Title: Is there any reason in a Java program for a special naming for a function arguments?

Body: I'd like to know, why would I want to have a special prefixes for a function arguments, like "p_name", "p_age", "p_sex"? On the one hand it helps to distinguish parameter from local variable or field further in the function body, but would it help? On the other hand, I didn't saw such naming recommendations anywhere including official Java language conventions. Please advise any reasons for using such naming policy</p>


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Code that tries to show off how clever the programmer is, despite the fact that it adds no real value:</p>

```<code>x ^= y ^= x ^= y;
</code>```

Body:
Code that tries to show off how clever the programmer is, despite the fact that it adds no real value:

x ^= y ^= x ^= y;


答:
For most Java programmers, the answer would have to be "No, there's no reason to do this." Especially the "p_" prefix - you'll find few proponents for that (and those that do use it tend to do so because of habits from other languages).

Having said that, I personally (ab)use Eclipse's feature of adding a method parameter prefix ("a") to fall back to coding habits from Smalltalk (which can't be beaten in terms of readability), where method arguments are typically prefixed with the article "a" or "an" to indicate their more transient nature (as opposed to class or instance variables). Examples are aString (because the method operates on a String that is passed in, not on the slightly more permanent instance variable one, anElement, or 'someAccounts' (for a collection), etc. Obviously most non-Smalltalkers would probably neither condone nor understand this idiosynchrasy ;-) but it does add readability if used correctly and, if you're used to it, it helps to tell method parameters apart from other types of variables (yes, I know most IDEs do that for you, but you can't always rely on code being viewed in them).

Note that I'm not posting this answer to convert all non-Smalltalkers but simply to offer a left-field alternative to using this way of naming arguments that may be interesting to some.


问:
Is monkeypatching considered good programming practice?
I've been under impression, that monkeypatching is more in quick and dirty hack category, rather than standard, good programming practice. While I'd used from time to time to fix minor issues with 3rd party libs, I considered it temporary fix and I'd submit proper patch to the 3rd party project.

However, I've seen this technique used as "the normal way" in mainstream projects, for example in Gevent's gevent.monkey module.

Has monkeypatching became mainstream, normal, acceptable programming practice?

See also: "Monkeypatching For Humans" by Jeff Atwood

答:
I believe that all patches are inherently risky due to their run-time nature, and inability to  be caught at design-time.

They welcome runtime exceptions, and require complex debuggers and watches just to follow.

They are used when people SEAL classes, and so inheritance is impossible. However, there are better ways to extend objects without damaging them.

My two cents


问:
INI files or Registry or personal files?
I want to save the configuration of my project which includes

Screen size

Screen position

Folder paths

Users settings and so on.

The standard places where you can save these are configuration values are:

Registry

INI files

Personal files (like *.cfg)

How do you choose between these places? Also, are there any pros and cons of using any of them?

答:
You forgot an option: the Database.
This is mostly used in scenarios where you have users logging into your application when your application can't rely on the logged in windows user.
This is for instance when your app is running in a kiosk mode windows.</p>


答:
No, but sometimes monkeypatch is a lesser evil (than having broken code :)). My general rules for monkeypatches in ruby are:

have a really good reason for monkey-patch (temporary critical hotfix is a good reason. Nice formatting of to_s method is not, unless you're working on ActiveSupport)

make them as transparent as possible: put them into specific place in codebase and separate files, write documentation describing the reason for monkeypatch (here's an example).

easy to remove - documentation should include info about removal and what to watch for. Lots of monkeypatches are temporary, so they should be easy to remove.

Title: Is monkeypatching considered good programming practice?

Body:
I've been under impression, that monkeypatching is more in quick and dirty hack category, rather than standard, good programming practice. While I'd used from time to time to fix minor issues with 3rd party libs, I considered it temporary fix and I'd submit proper patch to the 3rd party project.

However, I've seen this technique used as "the normal way" in mainstream projects, for example in Gevent's gevent.monkey module.

Has monkeypatching became mainstream, normal, acceptable programming practice?

See also: "Monkeypatching For Humans" by Jeff Atwood


问:
Best practices for App Idea ownership and shares
I am developing apps on my sparetime. I am the sole developer, and two non-programmer friends of mine provide vision, content, algorithms and ideas. We always agree happily on all the features, todos and prioritizations. But naturally, coding it is the biggest part.

When selling, we agree on splitting profit equally, that is 33% each.

But version 1.0 naturally does not sell much. And I go on to try to make the app more viral. This includes tons of stuff where the others are of little help. Examples: Adding support for sharing, facebook connect, gameifying, letting users add content, home page, support, maintenance, server services to make it easier for to update content. The list is long. Suddenly I will be doing 100% of a lot of work but only "own" a third of the income.

My friends may either "fade out" of the project after 1.0, or they continue to contribute, but with less value and I would rather exchange them for more programmers or graphic designers. The effort they made to version 1.0 is worth a lot to the app and I realize I would have never done it without them. But I am doing all the work in the end. It is hard to negotiate about splitting 90, 5, 5 instead of 33% each, because the idea is still theirs.

How to solve this? What are the best practices to regard the ownership of the app? What kind of agreements could I make that make it beneficial and motivational for me to continue developing the app?

答:
In a sense your friends and you have a company.(let's call it A)
In some other sense you are your own company.(call it B)

So I see two obvious things you can do: either buy the idea from company A with company B or have company A hire company B to do the work.


答:
This is a reason why it is hard to do business with your friends. It's always going to be the case that someone feels like they are pulling more weight than the others and should get more of the rewards. Difference is that it's much harder to have that negotiation with friends and keep your own interests at the forefront.

Best practice in these cases is to settle these things before you're waist-deep into delivery. Like the saying goes: you write contracts while you are friends, for the time when you are not. My best advice is to start with yourself. What do YOU think would be fair. Things to consider are:

How crucial is your participation in relation to the others? Could they easily replace you or even do without you? And vice-versa, could you do without them?

If your friends were to replace you, what would be a fair estimate on what it would cost to buy the effort you produce from elsewhere?

What is the effort you put in worth to you? Could you make more money doing something else? How much do you value any free-time you give up for this?

After that, treat this like any negotiation. Know what you want to achieve and what you are willing to surrender. And try to not think of the other people as your friends. In this context, they aren't. They are your partners. If they were your "friends" they would happily give you all their ideas for free and let you keep the money. They are not, however. They expect to be paid, just like you are expecting to be paid. Make sure that in the end, everyone is happy with the deal (that includes you!). The goal has to be that when you all agree, you should be able to shake hands, look each other in the eyes and then go have a beer with no love lost between you.

Also, and I can't stress this enough, put everything in writing. There should be absolutely no question about what you all agreed on in the future. Some extra minutes spent on this now can save you endless grief down the road.

Title: Best practices for App Idea ownership and shares

Body:
I am developing apps on my sparetime. I am the sole developer, and two non-programmer friends of mine provide vision, content, algorithms and ideas. We always agree happily on all the features, todos and prioritizations. But naturally, coding it is the biggest part.

When selling, we agree on splitting profit equally, that is 33% each.

But version 1.0 naturally does not sell much. And I go on to try to make the app more viral. This includes tons of stuff where the others are of little help. Examples: Adding support for sharing, facebook connect, gameifying, letting users add content, home page, support, maintenance, server services to make it easier for to update content. The list is long. Suddenly I will be doing 100% of a lot of work but only "own" a third of the income.

My friends may either "fade out" of the project after 1.0, or they continue to contribute, but with less value and I would rather exchange them for more programmers or graphic designers. The effort they made to version 1.0 is worth a lot to the app and I realize I would have never done it without them. But I am doing all the work in the end. It is hard to negotiate about splitting 90, 5, 5 instead of 33% each, because the idea is still theirs.

How to solve this? What are the best practices to regard the ownership of the app? What kind of agreements could I make that make it beneficial and motivational for me to continue developing the app?


答:
Functions with numbers in the name instead of having descriptive names, like:

void doSomething()
{
}

void doSomething2()
{
}
```

Please, make the function names mean something!  If doSomething and doSomething2 do similar things, use function names that differentiate the differences.  If doSomething2 is a break-out of functionality from doSomething, name it for its functionality.

Title: Which things instantly ring alarm bells when looking at code?

Body:
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

Body:
Functions with numbers in the name instead of having descriptive names, like:

void doSomething()
{
}

void doSomething2()
{
}

Please, make the function names mean something!  If doSomething and doSomething2 do similar things, use function names that differentiate the differences.  If doSomething2 is a break-out of functionality from doSomething, name it for its functionality.


答:
Some developers say they are "Fixing broken windows" when really they are "rearranging the deck chairs on the Titanic". Refactoring code that works but offends your sense of smell is relatively easy. If you find that you keep coming back to that sort of task instead of adding new capabilities for your users, or making the app more usable for them (optimization meaning making the app run faster is good here, optimization meaning making the code more readable is different) then perhaps you are tidying up too much. Not because tidying up is bad, but because the company is paying for development in order to get something developed. They don't want a brittle, hard-to-read, poorly architected solution, to be sure, but they also don't want a polished and beautiful half-solution.

Tidy up when you need to do something simple "to get going", or when you're waiting for another team to tell you whether your problem is in fact their fault, or when you're waiting for a decision. There will be plenty of opportunities. If you have the chance to move the whole app forward, take it, unless you are starting to feel the whole thing has become brittle. It probably hasn't. You will get a chance to refactor - you don't need to worry about that.

To come back to the second half of your question, a sprint to add features facing a short timeline, it would be wrong to say "and we won't be doing any refactoring, there isn't time." It would also be wrong to say "I know it's been 6 weeks and it looks exactly the same to the users, but these broken windows really needed to be fixed." Fit the refactoring into the gaps that happen in any project. Don't take refuge in tidying up at the expense of meeting the goal of the project.


问:
How Should a model and controller be distributed between subviews of the View?
In many User Interface libraries, we have concept of views and subviews.
so according to MVC pattern every view should update the model as soon as it changes.

For that view should have a reference of its model. If we have a subview and it does some calculation, then should that model also be passed to the subview or part of that model pertaining to that subview should be passed to that subview.

and Say when we take certain actions, should there be a separate controller for the subview or the actions on the subview should be handled by its parent view's controller ?

答:
First of all, there is no sub-view in MVC. That means, your sub-view should have it's own model.

The second thing is that a view should not do any kind of calculations*. That is what the model is for.

*  The reason not to do calculations in view is because the only way to test a view is to see how it displays what it should display.


答:
It is acceptable when the damage to the business by fixing them is greater than by not fixing them.

Situations where this occurs might be:

where a deadline or business opportunity might be missed because of the time needed to fix

where a piece of code is (genuinely) scheduled to be retired in a very short time scale therefore there is almost no benefit to refactoring it.

And these situations do occur - commercial situations will often contrive artificial deadlines which have to be met where the opportunity to negotiate them away has passed,  and requirements which have a time component - for instance a change in legislation or tax rules which come into force of a specific date - do exist.

The trick is in identifying these situations and assessing them properly. Code which is scheduled to be retired will often stick around for years. Artificial deadlines may need to be met but they can often be met in different ways (for instance software can be presented, demo-ed and "launched" on a given date without the final release version necessarily being finished until later).

When presented with this sort of thing you need to approach it with an open mind but always ask is it what it appears? Are the assumptions involved realistic? Is there another way of meeting to goal without shipping substandard code? If there isn't how do I best use the time I have available?

And if there is no alternative always fine, but when will we fix this?

Because it should almost, almost, almost always be when, not if.


问:
CSS3 will be standardized by browsers?
I'm using CSS3 for the first time, but using specific styles with prefix for each browser looks strange. The need of using -moz-, -o-, -webkit- and another prefix turns the CSS bigger and harder to maintain.

I want to know if the browsers are implementing some standardization to avoid the usage of prefix for styles.

答:
The use for the prefiexed properties is to avoid collision between how a vendor renders it and how it should work (based on W3C). These properties will eventually disapear (for the current properties) and will eventually re-appear for new prototype properties.

One thing to keep in mind when using vendors prefixes, define the prefixed properties before the final one, this way, for example, when mozilla's border property will be final you won't have to rewrite your css.

```<code>.selector {
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}
</code>```

This way, each vendor that doesn't support the final format, will support his own and each vendor that support the final format will interpret the two definitions they understands but the second one will overwrite the first one.

Title: CSS3 will be standardized by browsers?

Body:
The use for the prefiexed properties is to avoid collision between how a vendor renders it and how it should work (based on W3C). These properties will eventually disapear (for the current properties) and will eventually re-appear for new prototype properties.

One thing to keep in mind when using vendors prefixes, define the prefixed properties before the final one, this way, for example, when mozilla's border property will be final you won't have to rewrite your css.

.selector {
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}

This way, each vendor that doesn't support the final format, will support his own and each vendor that support the final format will interpret the two definitions they understands but the second one will overwrite the first one.


答:
You need to quantify the work and time being invested in, and come up with your percentages based on that.

Maybe it is too late for that though.

Or maybe, if you are working on it 100% of your time, you should be paid a proper salary for your work from the company, while maintaining the percentage split of the profits.


答:
You need to renegotiate. At the early stage, everyone's share should be contingent on their input. You decided to take the "friendly" approach and split everything equally. Ask for a higher percentage or don't do the work. A failed project may be the easiest way out if your partners aren't going to make the effort or give you the credit you feel you deserve.

If you were to win the lottery, give up programming and invest no money in the company, should the other two do all the work, hire a programmer and let you keep a third if it if it is successful?


答:
Yes, monkeypatching is very useful!

Somehow, names seem to be highly influencial on people's perception. Call it "monkeypatch" and it sounds bad, call it "hot fix" or "on-the-fly fix" and it sounds good.

Independently of that, I think the capability to alter methods/attributes/functions at runtime is a very useful thing. Even javascript people use it all day long without perhaps knowing it.

For instance:

```<code>button.onclick = function(e) { ...}
</code>```

This simple line illustrates the fact that you alter the behavior of button. It was designed that way. Likewise, you could alter every other function but it would be silly to do so.

Now, for the question of delivering patches that way... well... why not. You just have to download a small patch instead of a big release. Heck, you could even patch a server without stopping it, great! And then, one day, you could also fetch the latest release for a bigger update. Fair enough. So yes, I vote for "runtime patches" as a good thing.

Interestingly enough, some languages like Erlang were even build around this concept. The capability to update a server on the fly.

Of course, in the end, and like with everything else, it's a matter of how you use it. You can make wonderful OO stuff and shitty one, it's all the same.

EDIT:

Let me add some case distinction, whether you are patching your own library or a third-party one.

...basically, what you do with such a patch is fixing a bug of your own or a third party library. In either case it's useful. For your own, it enables you to deliver a fix on-the-fly. For a third-party one, either you wait (several months?) until they fix it by themselves, or you do it now on your own. (you can still submit them the patch, so that they will fix it on their side). When they release their next lib version with the issue fixed, you can still, if you want update the library and remove the patch on your side.

Now, of course, if you use a patch to alter the behavior of a lib and alienate its purpose/way of working, then obviously that's a recipe for disaster. Even a monkey would see that ...well, I hope. ;)

Body:
Yes, monkeypatching is very useful!

Somehow, names seem to be highly influencial on people's perception. Call it "monkeypatch" and it sounds bad, call it "hot fix" or "on-the-fly fix" and it sounds good.

Independently of that, I think the capability to alter methods/attributes/functions at runtime is a very useful thing. Even javascript people use it all day long without perhaps knowing it.

For instance:

button.onclick = function(e) { ...}

This simple line illustrates the fact that you alter the behavior of button. It was designed that way. Likewise, you could alter every other function but it would be silly to do so.

Now, for the question of delivering patches that way... well... why not. You just have to download a small patch instead of a big release. Heck, you could even patch a server without stopping it, great! And then, one day, you could also fetch the latest release for a bigger update. Fair enough. So yes, I vote for "runtime patches" as a good thing.

Interestingly enough, some languages like Erlang were even build around this concept. The capability to update a server on the fly.

Of course, in the end, and like with everything else, it's a matter of how you use it. You can make wonderful OO stuff and shitty one, it's all the same.

EDIT:

Let me add some case distinction, whether you are patching your own library or a third-party one.

...basically, what you do with such a patch is fixing a bug of your own or a third party library. In either case it's useful. For your own, it enables you to deliver a fix on-the-fly. For a third-party one, either you wait (several months?) until they fix it by themselves, or you do it now on your own. (you can still submit them the patch, so that they will fix it on their side). When they release their next lib version with the issue fixed, you can still, if you want update the library and remove the patch on your side.

Now, of course, if you use a patch to alter the behavior of a lib and alienate its purpose/way of working, then obviously that's a recipe for disaster. Even a monkey would see that ...well, I hope. ;)


答:
The programmers should let the business side know the extent of the technical debt, so they can make an informed decision. If the need to get to market sooner outweighs the risk of your code, you don't have much choice. Lack of cash flow will trump a lot of technical decisions.

To put some of the problems into a nontechnical perspective, point-out the extended time to fix bugs and add new features. If management has a sales and marketing background, they may understand this. They hate having to tell customers these things will take longer.

If you're thinking about expanding your team, this may be a good time to hire a junior developer. Test coverage will be a huge savior in this case. They'll learn more by doing than by reading documentation.


答:
I usually iterate between code and UML diagrams. I find that the diagrams help to show the big picture and a solid path forward and they can be changed rather quickly when issues are discovered. Also, when I have the diagrams, the coding tends to become trivial.

Conversely, when I draw the code in pictures it exposes dependency issues and makes design improvement opportunities blatantly obvious, which probably wouldn't have been noticed if we just had the code to work from. In particular, if it is a pain to draw, then it is going to also be a pain to code and a nightmare to maintain.

I have found that iteration is required, because just drawing the pictures always misses important aspects, while just coding results in problematic designs.

However, like another poster said, it all boils down to the people. If they are skilled "using" UML diagrams then UML is invaluable. If they aren't then the diagrams are of no value.

Thus, the answer to your question really is, "it depends". In this case, it depends on the people, the complexity of the project and how important it is that the system works properly.

Title: How important are UML diagrams for a successful project?

Body:
I'm in the middle of a project and I was asked to write UML diagrams (use cases,class diagram,etc). The project isn't very complex.

I was wondering if this be a waste of my time? Should I just be doing other fun stuff like writing code? And when is it not ok to build something without going through all of the conceptual phase? Is it all about complexity? And if so, how to measure it?


答: From my experience the UML is important for the communication between developers about the code patterns and for the architecture in general of the application.</p>


问:
asp .net development skills transferred to sharepoint?
Would a competent asp .net C# developer be disregarding a lot of their skills in order to have more concern with configuration and server-side coding when moving their career into the sharepoint 2010 arena? Or is asp .net C# in fact just a good base to begin the study of sharepoint on?</p>

答: ASP.NET and C# are excellent starts to being a SharePoint developer. SP web parts are very similar to ASP.NET controls. In fact, I would hire anyone with ASP.NET and C# experience and no SP experience to learn and develop in SP. I think being a solid .NET developer goes a long way in the SP world rather than the other way around.


问:
How do I make complex SQL queries easier to write?
I'm finding it very difficult to write complex SQL queries involving joins across many (at least 3-4) tables and involving several nested conditions.  The queries I'm being asked to write are easily described by a few sentences, but can require a deceptive amount of code to complete.  I'm finding myself often using temporary views to write these queries, which seem like a bit of a crutch.  What tips can you provide that I can use to make these complex queries easier?  More specifically, how do I break these queries down into the steps I need to use to actually write the SQL code?

Note that I'm the SQL I'm being asked to write is part of homework assignments for a database course, so I don't want software that will do the work for me.  I want to actually understand the code I'm writing.

More technical details:

The database is hosted on a PostgreSQL server running on the local machine.

The database is very small: there are no more than seven tables and the largest table has less than about 50 rows.

The SQL queries are being passed unchanged to the server, via LibreOffice Base.

答:
Become more familiar with set theory if you aren't already. SQL is based in set theory and understanding more about sets will help you become more familiar with how SQL works.

Practice more SQl, if you are just learning SQL its going to take time to understand how to do everything, somethings just take time before you really understand them, Joins are a great example the more you use them the better you will get at it.

Make sure the tables you are querying are properly designed

Don't be afraid of using views on select queries, especially if you have a common set that needs to be refined multiple different ways


答:
It's been my experience that the deadline is the most important thing for the business. It really depends on who's going to use your application. In my case it was for mobile phone OS software... missed deadlines meant missed sales targets and share price hits.

We came across a whole lot of WTF moments when looking at code we inherited and clearly needed to be changed. However because this code worked 'just about' (asynchronicity is poorly understood) there was no incentive for management to actually allow refactoring while there were outstanding commitments to be delivered. It wasn't until a bug was seen 'in the wild' that we'd be allowed change anything, even though we could break it ourselves easily through obscure edge cases. I once refactored approx 10k lines of code in my own time and ended up having to throw it away. The time needed for testing and others reviewing etc couldn't be justified.


问:
What are the best resources for learning about concurrency and multi-threaded applications?
I realised I have a massive knowledge gap when it comes to multi-threaded applications and concurrent programming. I've covered some basics in the past, but most of it seems to be gone from my mind, and it is definitely a field that I want, and need, to be more knowledgeable about.

What are the best resources for learning about building concurrent applications? I'm a very practical oriented person, so if said book contains concrete examples the better, but I'm open to suggestions. I personally prefer to work in pseudocode or C++, and a slant toward game development would be best, but not required.

答:
There are now threading facilities in the C++ standard. So if you want to learn in C++, I suggest reading a simple review of the new language feature before heading over to a generic threading tutorial. Then go back and review the standard in more detail later.

In practice, threading is one of those things that most people think they understand, but don't. I went to a talk from a static analysis researcher who identified race conditions in an IBM research database (Java), in a linux filesystem (C), and in some other pretty high-profile projects. Some of the projects were written by respected experts in concurrency and threading. Be aware that making thread-safe code is difficult and that the knowledge gap is not exclusive to those who recognize it in themselves.

Though it will not directly help you in game programming, I would recommend looking at some MPI tutorials (sorry, no specific recommendations). While it seems difficult to write correct concurrent code with threads, it seems rather easy to do it with message passing. Indirectly, the hope is that exploring different concurrency models will help your own thought process on structuring your code to be thread-safe.


问:
Preferred form for error detection and loop termination conditions?
In this Stackoverflow anwer I dimly recall being taught that it's better to use as "wide" a condition as possible to terminate a loop, rather than testing for an exact termination condition.

i.e. use:

```<code>while (x < 10)
</code>```

rather than

```<code>while (x != 10)
</code>```

however I cannot recall (or find) any formal basis or rationale for this.

Is this actually written down anywhere as best current practise?

答: The rationale could be, that in the second version in case of some bug (say x is incremented by 3 instead of 1) the loop will never terminate, once x jumped from 9 to 12. The first version will at least stop in all cases where x is incremented at all (though would still fail in many other cases).</p>


答:
I'm basing most of this on just trying to get the "right" answer, so you may discover there are some performance issues. No point in speeding up an incorrect query.

Understand the table relationships - Most will be one to many. Know the "many" table. Identify the fields required for your joins.

Think about LEFT join scenarios - Select all the employees and their paycheck from last month. What if they didn't get a paycheck last month?

Know the result set: 1) In a spreadsheet, manually enter at least one correct record for your query. 2) Write the query in a simple enough form to identify how many records should be returned. Use both of these to test your query to make sure joining a new table doesn't alter the result.

Break up your query into managable parts - You don't have to write it all at once. Complex queries can sometimes just be a collection of simple queries.

Beware of mixed levels of aggregation: If you have to put monthly, quarterly and year-to-date values in the same result set, you'll need to calculate them separately in queries grouped on different values.

Know when to UNION Sometimes it's easier to break up subgroups into their own select statements. If you have a table mixed with managers and other employees, and on each column you have to do Case statements based on membership in one of these groups, it may be easier to write a Manager query and union to an Employee query. Each one would contain their own logic. Having to include items from different tables in different rows is an obvious use.

Complex/Nested formulas - Try to consistently indent and don't be afraid to use multiple lines. "CASE WHEN CASE WHEN CASE WHEN" will drive you nuts. Take the time to think these through. Save the complex calcs for last. Get the correct records selected first. Then you attack complex formulas knowing you're working with the right values. Seeing the values used in the formulas will help you spot areas where you have to account for NULL values and where to handle the divide by zero error.

Test often as you add new tables to make sure you're still getting the desired result set and knowing which join or clause is the culprit.

Title: How do I make complex SQL queries easier to write?

Body:
I'm finding it very difficult to write complex SQL queries involving joins across many (at least 3-4) tables and involving several nested conditions.  The queries I'm being asked to write are easily described by a few sentences, but can require a deceptive amount of code to complete.  I'm finding myself often using temporary views to write these queries, which seem like a bit of a crutch.  What tips can you provide that I can use to make these complex queries easier?  More specifically, how do I break these queries down into the steps I need to use to actually write the SQL code?

Note that I'm the SQL I'm being asked to write is part of homework assignments for a database course, so I don't want software that will do the work for me.  I want to actually understand the code I'm writing.

More technical details:

The database is hosted on a PostgreSQL server running on the local machine.

The database is very small: there are no more than seven tables and the largest table has less than about 50 rows.

The SQL queries are being passed unchanged to the server, via LibreOffice Base.


答:
Like anything else, you want to break the problem down into manageable parts.

That really IS how you solve complex problems, by the way.

So: You want to check out the subquery to see that it really returns what you want before running an outer query on it. You want to try a minimal join of each table you're joining in so you can see that you're really thinking it through properly. Things like that. Hoping to type it all in and get out just exactly what you want in one whack is just unrealistic.

A SQL statement, once it reaches a certain level of complexity, is basically a little program in and of itself. It makes a big difference to really understand how the data is combined, selected, filtered, and output.


问:
Why is the empty list used as the list terminator in Lisp?
It seems to me that the list terminator in Lisp could be any arbitrary value. For example, the string terminator in C is the null pointer. Is there a philosophical reason why the empty list was chosen to terminate lists?</p>

答:
A Lisp list is not really terminated with an empty list -- it's terminated with a special value, traditionally called nil. As it happens, that also traditionally evaluates as false -- which makes it about as close to C's null pointer as you can get (in C, a null pointer constant is an integer constant equal to zero, which also evaluates to false).

An empty list is basically just a rather short-hand way of expressing NIL -- since you don't even have a single cons cell, all you're left with is the NIL that terminates the list. In other words, it's not that a list is terminated with an empty list -- it's that an empty list consists of only a terminator.

Using dot notation, it's possible to link cons cells together in other ways, but the result isn't a "list" as the term is normally used.

OwnerDisplayName: Skilldrick

OwnerDisplayName: Jerry Coffin


答:
Lisp lists don't really have a 'terminating' value. Actually Lisp does not even have a primitive list data structure. Lists are built out of the empty list and a chain of linked cons cells pointing to list contents.

Lists are recursively defined:

the empty list is ()

a list newlist is the result of (CONS element list), where (FIRST newlist) is element and (REST newlist) is list.

A list is empty when it is the empty list or (NULL list) is true.

Because newlist is the result of (CONS element list) it is actually a cons cell object and `(CONSP newlist) is true.

In older times FIRST was called CAR and REST was CDR. Today it is good style to use in list operations FIRST and REST. CAR and CDR is better used when one exploits the feature that something (tree, queue, list, ...) is built out of cons cells.

Historically (and still in Common Lisp which aims to be backwards compatible), the empty list is also the unique symbol NIL. The empty list evaluates to itself and it is also the false value. In the Lisp-dialect Scheme, the empty list is NOT the false value.

```<code>CL-USER 12 > (setq l1 ())
NIL

CL-USER 13 > (setq l2 (cons 1 (cons 2 l1)))
(1 2)

CL-USER 14 > (consp l1)
NIL

CL-USER 15 > (consp l2)
T

CL-USER 16 > (null l1)
T

CL-USER 17 > (null l2)
NIL

CL-USER 18 > (first l2)
1

CL-USER 19 > (rest l2)
(2)

CL-USER 20 > (rest (rest l2))
NIL

CL-USER 21 > (consp (rest l2))
T

CL-USER 22 > (consp (rest (rest l2)))
NIL
</code>```

Title: Why is the empty list used as the list terminator in Lisp?

Body: It seems to me that the list terminator in Lisp could be any arbitrary value. For example, the string terminator in C is the null pointer. Is there a philosophical reason why the empty list was chosen to terminate lists?</p>

Body:
Lisp lists don't really have a 'terminating' value. Actually Lisp does not even have a primitive list data structure. Lists are built out of the empty list and a chain of linked cons cells pointing to list contents.

Lists are recursively defined:

the empty list is ()

a list newlist is the result of (CONS element list), where (FIRST newlist) is element and (REST newlist) is list.

A list is empty when it is the empty list or (NULL list) is true.

Because newlist is the result of (CONS element list) it is actually a cons cell object and `(CONSP newlist) is true.

In older times FIRST was called CAR and REST was CDR. Today it is good style to use in list operations FIRST and REST. CAR and CDR is better used when one exploits the feature that something (tree, queue, list, ...) is built out of cons cells.

Historically (and still in Common Lisp which aims to be backwards compatible), the empty list is also the unique symbol NIL. The empty list evaluates to itself and it is also the false value. In the Lisp-dialect Scheme, the empty list is NOT the false value.

CL-USER 12 > (setq l1 ())
NIL

CL-USER 13 > (setq l2 (cons 1 (cons 2 l1)))
(1 2)

CL-USER 14 > (consp l1)
NIL

CL-USER 15 > (consp l2)
T

CL-USER 16 > (null l1)
T

CL-USER 17 > (null l2)
NIL

CL-USER 18 > (first l2)
1

CL-USER 19 > (rest l2)
(2)

CL-USER 20 > (rest (rest l2))
NIL

CL-USER 21 > (consp (rest l2))
T

CL-USER 22 > (consp (rest (rest l2)))
NIL

OwnerDisplayName: Rainer Joswig


答:
This may be not language specific and somewhat anti-scientific explanation, but may give you some thoughts.

You could think about the language as a set of all facts pertaining to the "world" or "universe" created by that language. As this is a set, you would need to have a complement set for all facts excluded from the language, i.e. something to mean "not in this set". In certain light nil (or false or other variants of "nothingness" may be understood as "not in this set"). Since cons is one of the basic building blocks of the language, the atom that is taken to mean nothingness is used for any not yet created value. So, you don't terminate the list with an empty list (how then do you terminate empty lists?), it's just at some point there is nothing the cons is pointing to and nil is the way to tell that.

OwnerDisplayName: wvxvw


答:
As Rainer and Jerry explained, Lisp lists are built from cons cells so it's not really and empty list.  Conceptually it's often helpful to think this way when defining recursive functions though.  It's a bit more obvious if we look at List data type definition in (for example) Haskell.

```<code>data List a = Cons a (List a)
            | Empty <<== nil in Lisp
</code>```

What this says is that either we have a Cons cell with an element followed by a tail or an Empty list.  So a list of 1 element is (Cons 1 Empty).  This is helpful for defining recursive functions such as map.

```<code>map f (Cons e tail) = Cons (f e) (map f tail)
map f Empty = Empty
</code>```

Which in Lisp could be

```<code>(defmethod fmap (f (lst cons))
  (cons (funcall f (car lst))
        (fmap f (cdr lst))))

(defmethod fmap (f (lst null))
  nil)
</code>```

So conceptually thinking of a list as being terminated by the empty list can be very helpful,

Body:
As Rainer and Jerry explained, Lisp lists are built from cons cells so it's not really and empty list.  Conceptually it's often helpful to think this way when defining recursive functions though.  It's a bit more obvious if we look at List data type definition in (for example) Haskell.

data List a = Cons a (List a)
            | Empty <<== nil in Lisp

What this says is that either we have a Cons cell with an element followed by a tail or an Empty list.  So a list of 1 element is (Cons 1 Empty).  This is helpful for defining recursive functions such as map.

map f (Cons e tail) = Cons (f e) (map f tail)
map f Empty = Empty

Which in Lisp could be

(defmethod fmap (f (lst cons))
  (cons (funcall f (car lst))
        (fmap f (cdr lst))))

(defmethod fmap (f (lst null))
  nil)

So conceptually thinking of a list as being terminated by the empty list can be very helpful,

OwnerDisplayName: Andrew Myers


答:
I did this to a very limited degree:

I had a production application with a lot of live users. The system had an in-built error logger. During critical errors, it would send detailed email reports.

Since everything was logged it was possible to see trends, and allowed developers to focus on different areas (sometimes ones we would not normally concentrate on).

SO

A more automated approach would be better.

Perhaps you could create a an application that can log and analyse compiler errors and cross reference them with Source control logs along with automatic error reports from live applications?

Title: Formalizing programmers errors

Body:
Every one of us make errors leading to bugs. Once I wanted to start logging my errors for future analysis, probably mentioning project title, approximate time spent and the most important, the type of error. For example when I copy-pasted a fragment about 'x' and replaced every occurrence of 'x' with 'y' and forgot to replace a tiny piece, this goes to 'copy-paste error'. The usefulness of this approach depends on whether I can formalize my errors at all and probably minimizing the number of types to choose from. Otherwise I would start postponing, ignoring and so on so make this system useless.

Are there existing research in this area, probably a known minimum set of errors? Maybe some of you already tried to implement something like this and succeeded/failed?


答:
In answer to your question regarding refactoring, I would say, "yes". As someone else pointed out in the answers above, refactoring is an ongoing process, and some times there are tactical and business decisions which supercede the need to rewrite code which is already working (although perhaps in a klugey way).

Regarding "broken windows": I first heard this term in the context of software development, about 10 years ago. But at that time, it was used to describe allowing broken unit tests. This was describing the scenario where people have the temptation to not fix broken unit tests, because it seems more expedient just to remember which tests are "okay to fail", instead of fixing the broken tests (which were validly broken due to interface or requirements changes, for example).

I think applying the broken window metaphor to broken unit tests is more fitting, and more descriptive of the danger of allowing "broken windows" in the software neighborhood. In my opinion, if you were talking about broken unit tests (as broken windows), then the answer would be it is never okay. (To the extent we can ever say never...)


问:
Using HashTable without overriding hashcode()
Today I was asked this question during an interview:

What will happen if we do not override the hashcode method for our
  class, then add it to HashTable and then try to get objects?

What could go wrong?

答:
The answer is "nothing bad unless you have overridden equals()".

The general point is that if two objects compare equal i.e. if

```<code> a.equals(b)
</code>```

then they must have the same hashcode i.e.

```<code> a.hashCode() == b.hashCode()
</code>```

also if two objects have different hash codes, they must not compare equal.

This is especially relevant when you put objects in a hash table.  This is because a hash table is an array of lists (called buckets usually).  The hash bucket is indexed using the hash code, typically you use hashCode % arraySize.

So when you put an object in the hash table, you take the hash code of the key and use it to determine the bucket.  You then put a key-value pair in the bucket.  When you want to retrieve an object from the hash table, you take the hash code of the key to find the bucket and test the key of all the key-value pairs in the bucket with .equals() to determine which object is the one you want.

So if you have two key objects which compare equal but have different hash codes and you use one as a key in a hash table, you won't be able to search for it using the other key object because you'll be looking in the wrong bucket.

The implementation of equals() in Object only returns true if the two objects are actually the same object and hashCode() returns the object reference.  However, if you override equals() (e.g. String does so that different strings containing the same character sequence compare equal) then you must override hashCode()

Body:
The answer is "nothing bad unless you have overridden equals()".

The general point is that if two objects compare equal i.e. if

 a.equals(b)

then they must have the same hashcode i.e.

 a.hashCode() == b.hashCode()

also if two objects have different hash codes, they must not compare equal.

This is especially relevant when you put objects in a hash table.  This is because a hash table is an array of lists (called buckets usually).  The hash bucket is indexed using the hash code, typically you use hashCode % arraySize.

So when you put an object in the hash table, you take the hash code of the key and use it to determine the bucket.  You then put a key-value pair in the bucket.  When you want to retrieve an object from the hash table, you take the hash code of the key to find the bucket and test the key of all the key-value pairs in the bucket with .equals() to determine which object is the one you want.

So if you have two key objects which compare equal but have different hash codes and you use one as a key in a hash table, you won't be able to search for it using the other key object because you'll be looking in the wrong bucket.

The implementation of equals() in Object only returns true if the two objects are actually the same object and hashCode() returns the object reference.  However, if you override equals() (e.g. String does so that different strings containing the same character sequence compare equal) then you must override hashCode()


答:
if you use floating point variables chances are that you will never have x==10 this is due to rounding

for example (if constants are not folded) 0.3!=0.1+0.1+0.1 om most machines

Title: Preferred form for error detection and loop termination conditions?

Body:
In this Stackoverflow anwer I dimly recall being taught that it's better to use as "wide" a condition as possible to terminate a loop, rather than testing for an exact termination condition.

i.e. use:

```<code>while (x < 10)
</code>```

rather than

```<code>while (x != 10)
</code>```

however I cannot recall (or find) any formal basis or rationale for this.

Is this actually written down anywhere as best current practise?


答:
Here's a StackOverflow question that illustrates the reasoning perfectly.  He had i != bytes_read as the loop condition, but had more than one place inside the loop that incremented i, which created an infinite loop under certain conditions.  Using <= makes the infinite loop finite instead.  That's all there is to it, nothing so involved that someone's going to write a paper on it.

It also makes it more clear to someone reading the program what values are valid for that variable.  i != bytes_read on its own implies that that values greater than bytes_read are valid.  You have to read several other lines of code to know that they aren't.  This particular example might be blindingly obvious, but it still adds clarity to the code.  From a more formal perspective, it relieves you of the need to prove that the other statements further restrict i to be less than bytes_read.

Whether it qualifies as a "best practice" or not really depends on if there's a better way to do it.  For example, you should use an iterator to loop through items in a container rather than an integer counter based on the container size.  Adding an assert to catch values outside a valid range might be more useful if it's a real possibility.


答:
If the hashcode method is not overridden, the answer to this question really depends on if the  same key object which was used to "put" is going to used for "get" as well:

a) If the same key object is used -  "get" will find the value. Because it will locate the bucket using the same "key" and hence will find the value object.

b) If some another "equivelent" key object is used - Since possibly the hashcode is going to be different due to default implementation of the hashcode method in  Object and hence it might get into a different bucket and might not be able to get the value object.

Body:
Today I was asked this question during an interview:

What will happen if we do not override the hashcode method for our
  class, then add it to HashTable and then try to get objects?

What could go wrong?


问:
Is the creation of brand new software generally a major part of most programming jobs?
I have worked in software development for over 10 years now, and it's dawning on me that I rarely get to create anything "new".  I realize that "new" is a vague term, but I would define it as anything from an obvious new large-scale project to a new large feature in an existing project (say something that would require some thought into its design, and that might take 2 weeks or more to complete).  Maybe a rough guideline is something is new if it requires a written spec.  I think most programmers know what I'm talking about - you're in the zone, writing a ton of code at a fast pace.

Anyway, thinking back to what I've done, I'd estimate that less than 10% of my time is spent on "new" work.  There are things like "adapt this existing system to work in this new environment", which certainly requires a lot of planning, but the actual coding and "new stuff" comes down to making tiny changes in many places throughout the code.  Likewise for small feature requests - if I know what to do, these can often be finished in under an hour, and if I don't, it's just a lot of reading code and figuring out what to do (which frustrates me because I learn much better by doing, not by reading).

In general I feel like I am not really creating anything most of the time.  I kind of assumed that this was the case at most places - a new product would come out rather quickly and at that point everyone would be excited and banging out the code at a fast pace, but then once live it moves into maintenance mode, where few of the subsequent changes would be considered "new & creative".

Am I wrong?  Am I accurately describing most programming jobs, or do most programmers feel like they are often creating new things?

答:
It depends on what work you seek out.

I have only once worked for a pure software product company where I worked on their single gold-plated application in a small start-up team.

Otherwise I have worked for technology companies that needed software to support their internal R&D or outside products.

The upside is I get to build complete start-finish products and pretty much build what I want. Sometimes you can also try newer technologies than if you were stuck adding features to a existing market leading application.

The downside is that you are part of the cost, not part of the product. So I have had projects canned because 'we aren't doing software"/"software isn't core business" = it's amazing how companies think they can sell a $100 K machine tool with no software to operate it!


答: A great deal of software work is maintenance.  No hiring manager will actually tell you this, of course, but it's certainly the case.  </p>

Title: Is the creation of brand new software generally a major part of most programming jobs?

Body:
I have worked in software development for over 10 years now, and it's dawning on me that I rarely get to create anything "new".  I realize that "new" is a vague term, but I would define it as anything from an obvious new large-scale project to a new large feature in an existing project (say something that would require some thought into its design, and that might take 2 weeks or more to complete).  Maybe a rough guideline is something is new if it requires a written spec.  I think most programmers know what I'm talking about - you're in the zone, writing a ton of code at a fast pace.

Anyway, thinking back to what I've done, I'd estimate that less than 10% of my time is spent on "new" work.  There are things like "adapt this existing system to work in this new environment", which certainly requires a lot of planning, but the actual coding and "new stuff" comes down to making tiny changes in many places throughout the code.  Likewise for small feature requests - if I know what to do, these can often be finished in under an hour, and if I don't, it's just a lot of reading code and figuring out what to do (which frustrates me because I learn much better by doing, not by reading).

In general I feel like I am not really creating anything most of the time.  I kind of assumed that this was the case at most places - a new product would come out rather quickly and at that point everyone would be excited and banging out the code at a fast pace, but then once live it moves into maintenance mode, where few of the subsequent changes would be considered "new & creative".

Am I wrong?  Am I accurately describing most programming jobs, or do most programmers feel like they are often creating new things?


答:
Yes, your perception is accurate. It's an absolute truism that far more time, money and effort is spent on maintaining systems than on creating new systems. So obviously, the time allocation of most programmers is going to reflect that.

Part of the reason for this is that a lot of people, when they get to do "new & creative", they do it badly, so that maintaining the system is hard (this is especially likely if they've never done maintenance themselves - nobody who has constantly worked on small greenfield projects can really claim to be competent).

Another (probably bigger) reason is that most systems are designed to be continually useful, not just for an one-off event. So they keep getting used for much longer than it took to develop them. But during that time, requirements change (and are added to) due to changes in legislation, in the market, in research, in the users, whatever. And that means maintenance work.


答:
The term that's often used for new projects that aren't dependent on older development is greenfield project. You may occasionally see the term in job listings -- knowing that you get to start from scratch rather than inheriting somebody else's failed endeavor can make a job more appealing.

Successful software projects generally spend a lot more time being maintained than they do being built as new projects, so it's not at all surprising that you don't get to do a lot of completely "new" stuff.

Also, creating something completely new is a lot of work. Even on a greenfield project, you'll probably choose a number of tools to help you: platform, compiler, frameworks, libraries, etc. As soon as you make those choices, you've imposed certain constraints on your project. That's not to say that you're not doing new work anymore, only that "new" is a relative term here. It's not a big step from there to see adding a feature or module to an existing project as "new" even though you wouldn't call it a greenfield project.


答:
When the code looks like a mess: Comments with "todo" and "note to self" and lame jokes. Code that was obviously used at some point solely for debugging purposes, but was then not removed. Variables or functions with names that suggest that the writer did not consider that anyone would read it later. Often these names will be very long and unwieldy.

Also: If the code lacks rhythm. Functions of wildly divergent length. Functions that do not adhere to the same naming schemes.

Slightly related: It always makes me nervous if a programmer has slobby handwriting. Or if they are bad writers or bad communicators.


答:
I think many software development jobs involving improving an existing product or adapting existing code to a new customer or market.

This isn't really 'maintenance'.  For example, VMWare just released version 8, it's a major upgrade to their main product.  I suspect few of the developers who did this work were there when the first line of code for VMWare was written.  They built their major upgrade on the code written by guys who long since moved on.

Over in the Workplace Beta there is a question about how Google's 20% personal project system works.

I am sure that Google figured out that the best developers want to be there at the creation of new software products and will eventually tire of years of adding small features and tweaking gui's for the next point release.

By having the 20% projects I speculate that Google developer won't mind staying to improve Google's projects since he or she can still have the fun of being there at the start of something new.


问:
Eliminating tab characters in a new language
I'm working on a new programming language, which determines structure with indentation instead of braces in the manner of Python and CoffeeScript. Obviously placing lines indented with spaces next to lines indented with tabs will mess up that kind of syntax, so I'm disallowing that - any given source file must use one or the other, not both.

I'm wondering whether it would be better to mandate one or the other across the board just to eliminate the possibility of time wasted on argument? Spaces seem to be slightly more popular than tabs, so if I were going to do that, I suppose I would mandate indenting with spaces (despite the fact that I personally prefer to use tabs).

Are there any situations where eliminating the possibility of indenting with tabs, would cause a problem?

答:
No. The tab character is an aberration that should never have found its way into ASCII, let alone any modern programming language. It was supposed to move the carriage on a teletype terminal to one of a predefined set of absolute positions,  something that has no equivalent in the task of editing source code. Instead, it usually does a halfhearted approximation of that obsolete task, moving to the nearest multiple of n columns, and in a quite unpredictable way unless you have near-autistic attention to detail. I can see no advantage whatsoever to allowing it in source files, particularly since its presence is not discernible to an unsuspecting reader (unless special processing is enabled, like the whitespace-visual-mode of emacs).

Note that this does not rule out the use of the Tab key to do something useful, e.g. indent in a context-sensitive way like the better IDEs do, but that doesn't mean the compiler should have to deal with the Tab character. In my opinion, it can only cause confusion and is of about as much worth for the programmer trying to express something as the BELL character, i.e. none.


问:
Session Flash vs TempData C# MVC 3
A little background.  A developer I used to work with insisted on disabling Tempdata and using  Session Flash for passing data in the return view.

Question is, is there any advantage to doing it this way?  using a flash message is great for returning data to the user but I've had headaches with passing data from one post to the next with tempdata disabled.

Is there any problem with using flash and tempdata together or is this a major coding faux paus?

答:
Temporarily putting things in the session is going to lead to strange behavior when a user opens up 2 or more windows.  TempData is best for persisting data briefly.

Also, sessions can be cleared a variety of ways.  TempData will rewrite a bit of data on the page to be posted back and will last as long as the window isn't closed.

There's also the problem of session scalability.  Most applications won't run into a problem here but larger applications can be affected.

If you're still not convinced here's a coding guidelines document from Microsoft encouraging the use of tempdata over the session

Title: Session Flash vs TempData C# MVC 3


答:
Some editors support tabs more easily than spaces, e.g., zero-feature plain-text editors which have no expand-tabs-to-spaces functionality. Mandating spaces makes it more inconvenient for people using such editors.

Some editors support indenting with spaces, but have only a global configuration for it rather than a per-file configuration. If the user prefers indenting with tabs, he may find it inconvenient to reconfigure his editor just to use your language. Perhaps more likely is an editor which supports per-file configuration of indentation mode, but uses a global configuration for the default mode when creating a new file: again, if the default isn't spaces then it's inconvenient.

Some programmers prefer indenting with tabs (you've said that you do, for example). They may find it irritating for the language to mandate the use of spaces.

Of course there are no technical problems with mandating the use of spaces. Everyone has a space key, and most programmers use editors capable of indenting with spaces without the user having to tap out <SPACE><SPACE><SPACE><SPACE> each time. However, irritation should not be underestimated as an influence on people's choices.

Title: Eliminating tab characters in a new language

Body:
I'm working on a new programming language, which determines structure with indentation instead of braces in the manner of Python and CoffeeScript. Obviously placing lines indented with spaces next to lines indented with tabs will mess up that kind of syntax, so I'm disallowing that - any given source file must use one or the other, not both.

I'm wondering whether it would be better to mandate one or the other across the board just to eliminate the possibility of time wasted on argument? Spaces seem to be slightly more popular than tabs, so if I were going to do that, I suppose I would mandate indenting with spaces (despite the fact that I personally prefer to use tabs).

Are there any situations where eliminating the possibility of indenting with tabs, would cause a problem?


答:
Yes, to some degree. The holy wars of tabs and spaces is still going on, and if you choose to only allow one of them, you will alienate the opposing group.

My suggestion is, allow both if you don't want to be radical.


答:
A bit of a shot in the dark here, but if you are writing lots of temporary views perhaps you haven't realized yet that most places you could put a table in an SQL statement, that table can be replaced by a query.

So, rather than joining table A to temporary view B, you can join table A to the query that you have been using as temporary view B.  For example:

```<code>    SELECT A.Col1, A.Col2, B.Col1,B.Col2
      FROM (SELECT RealTableZ.Col1, RealTableY.Col2, RealTableY.ID as ID
              FROM RealTableZ
   LEFT OUTER JOIN RealTableY
                ON RealTableZ.ForeignKeyY=RealTableY.ID
             WHERE RealTableY.Col11>14
            ) As B
        INNER JOIN A
                ON A.ForeignKeyY=B.ID
</code>```

This example is rather pointless, but should explain the syntax.

For views that aren't "special" (indexed, partitioned) this should result in the same query plan as if you used a view.

As far as making it easier to write, you can verify each piece to make sure you are getting what you expect before writing out the entire query.

My apologies if this is old hat to you already.

Body:
A bit of a shot in the dark here, but if you are writing lots of temporary views perhaps you haven't realized yet that most places you could put a table in an SQL statement, that table can be replaced by a query.

So, rather than joining table A to temporary view B, you can join table A to the query that you have been using as temporary view B.  For example:

    SELECT A.Col1, A.Col2, B.Col1,B.Col2
      FROM (SELECT RealTableZ.Col1, RealTableY.Col2, RealTableY.ID as ID
              FROM RealTableZ
   LEFT OUTER JOIN RealTableY
                ON RealTableZ.ForeignKeyY=RealTableY.ID
             WHERE RealTableY.Col11>14
            ) As B
        INNER JOIN A
                ON A.ForeignKeyY=B.ID

This example is rather pointless, but should explain the syntax.

For views that aren't "special" (indexed, partitioned) this should result in the same query plan as if you used a view.

As far as making it easier to write, you can verify each piece to make sure you are getting what you expect before writing out the entire query.

My apologies if this is old hat to you already.


问:
Advantages and disadvantages of building a single page web application
I'm nearing the end of a prototyping/proof of concept phase for a side project I'm working on, and trying to decide on some larger scale application design decisions.  The app is a project management system tailored more towards the agile development process.  One of the decisions I need to make is whether or not to go with a traditional multi-page application or a single page application.

Currently my prototype is a traditional multi-page setup, however I have been looking at backbone.js to clean up and apply some structure to my Javascript (jQuery) code.  It seems like while backbone.js can be used in multi-page applications, it shines more with single page applications.  I am trying to come up with a list of advantages and disadvantages of using a single page application design approach.  So far I have:

Advantages

All data has to be available via some sort of API - this is a big advantage for my use case as I want to have an API to my application anyway. Right now about 60-70% of my calls to get/update data are done through a REST API.  Doing a single page application will allow me to better test my REST API since the application itself will use it.  It also means that as the application grows, the API itself will grow since that is what the application uses; no need to maintain the API as an add-on to the application.

More responsive application - since all data loaded after the initial page is kept to a minimum and transmitted in a compact format (like JSON), data requests should generally be faster, and the server will do slightly less processing.

Disadvantages

Duplication of code - for example, model code.  I am going to have to create models both on the server side (PHP in this case) and the client side in Javascript.

Business logic in Javascript - I can't give any concrete examples on why this would be bad but it just doesn't feel right to me having business logic in Javascript that anyone can read.

Javascript memory leaks - since the page never reloads, Javascript memory leaks can happen, and I would not even know where to begin to debug them.

There are also other things that are kind of double edged swords.  For example, with single page applications, the data processed for each request can be a lot less since the application will be asking for the minimum data it needs for the particular request, however it also means that there could be a lot more small request to the server.  I'm not sure if that is a good or bad thing.

What are some of the advantages and disadvantages of single page web applications that I should keep in mind when deciding which way I should go for my project?

答:
-Duplication of code - For example, model code. I am going to have to create models both on the server side (PHP in the case) and the server side in javascript.

You're in the PHP world but there are code-generation strategies in the .NET world for automatically creating JavaScript WCF proxies.  See here

I don't know what options might be available to not have to create your remote objects yourself in JavaScript in a PHP application, but this is an option for those writing single page applications in .NET.


问:
What is the importance of XML in the world of JSON?
How important is it to learn XML when JSON is able to do almost all that I need? Having said that, I use JSON mainly for AJAX requests and obtaining data from various APIs.
I am a total newbie to web development and the reason I am asking this is that I want to know whether I should go ahead and buy a book on XML or whether I can just give it a pass.</p>

答:
XML definitely outshines JSON for markup (which is, after all, hinted at in the name).

I wouldn't like to see a random XHTML page converted into JSON format. It would be horrible. OpenOffice and the latest editions of Microsoft Office all use compressed XML as their format of choice.

As a general rule: Markup goes in XML; structured data goes in JSON.

That's when you're outputting data and have full control yourself over the format. If you're outputting data according to industry standards, or consuming other people's data, you may need to use XML even in places where JSON would seem more appropriate. That's because XML is longer established and has been used in many standards.


问:
Is it just me or is this a baffling tech interview question?

Background

I was just asked in a tech interview to write an algorithm to traverse an "object" (notice the quotes) where A is equal to B and B is equal to C and A is equal to C.

That's it.  That is all the information I was given.

I asked the interviewer what the goal was but apparently there wasn't one, just "traverse" the "object".

I don't know about anyone else, but this seems like a silly question to me.  I asked again, "am I searching for a value?".  Nope.  Just "traverse" it.

Why would I ever want to endlessly loop through this "object"??  To melt my processor maybe??

The answer according to the interviewer was that I should have written a recursive function.

OK, so why not simply ask me to write a recursive function?  And who would write a recursive function that never ends?

My question:

Is this a valid question to the rest of you and, if so, can you provide a hint as to what I might be missing?  Perhaps I am thinking too hard about solving real world problems.  I have been successfully coding for a long time but this tech interview process makes me feel like I don't know anything.

答:
Was this a Java interview question, if so, may be he wanted to test your skills with overriding "hashcode" and "equals".

You would have to override these two methods and use the overridden equals method to stop the recursion when you compare A with A.

Without overriding, your comparison for "object" A to B, A to C and A to A will all result true but after overriding, only when object A compared to object A will return true where as other comparisons will return false.


问:
Difference between software inspection and verification
I was reading about software inspection in Software Engineering by Ian Summerville and I came across the term Software inspection and I started reading about it on Wikipedia. I am unable to understand what is the difference between verification and software inspection?</p>

答:
Software verification is the collection of methods used to determine if the software system that is being constructed is being built right. Some aspect of the system, whether it's the design, the implementation, or the test cases, are compared to the documented requirements of the system.

A software inspection is a particular technique that can be used to verify the system against the specification. There are different types of inspections, ranging from a "desk check" where another developer looks over the work product to a formal inspection (often called a Fagan inspection) with roles, checklists, and meetings, with many formats of inspections falling between these two extremes.


答:
The biggest disadvantage is that the client must have JavaScript enabled and be powerful enough to run a fair amount of it.  It's also harder to satisfy accessibility concerns or anything else that relies on parsing static HTML (though something knowing your specific API can probably do better than HTML scraping).  Finally, it's easier to have significant memory leaks.

As far as duplicating code or putting business logic on the client - I'm not sure how much of that you have to do.  If the model on the client is a View-Model (a model that matches up with the world as the UI sees it, not a business model) then the logic that matches the ViewModel up to the business model can reside on the client, the server, or a bit of both.  It depends on how you feel about having your API contain a client-specific facade vs. having the client translate UI inputs into API calls.

You might also want to look at knockout.js.  I can't say if it's better than backbone but it may fit your project better.

Title: Advantages and disadvantages of building a single page web application

Body:
I'm nearing the end of a prototyping/proof of concept phase for a side project I'm working on, and trying to decide on some larger scale application design decisions.  The app is a project management system tailored more towards the agile development process.  One of the decisions I need to make is whether or not to go with a traditional multi-page application or a single page application.

Currently my prototype is a traditional multi-page setup, however I have been looking at backbone.js to clean up and apply some structure to my Javascript (jQuery) code.  It seems like while backbone.js can be used in multi-page applications, it shines more with single page applications.  I am trying to come up with a list of advantages and disadvantages of using a single page application design approach.  So far I have:

Advantages

All data has to be available via some sort of API - this is a big advantage for my use case as I want to have an API to my application anyway. Right now about 60-70% of my calls to get/update data are done through a REST API.  Doing a single page application will allow me to better test my REST API since the application itself will use it.  It also means that as the application grows, the API itself will grow since that is what the application uses; no need to maintain the API as an add-on to the application.

More responsive application - since all data loaded after the initial page is kept to a minimum and transmitted in a compact format (like JSON), data requests should generally be faster, and the server will do slightly less processing.

Disadvantages

Duplication of code - for example, model code.  I am going to have to create models both on the server side (PHP in this case) and the client side in Javascript.

Business logic in Javascript - I can't give any concrete examples on why this would be bad but it just doesn't feel right to me having business logic in Javascript that anyone can read.

Javascript memory leaks - since the page never reloads, Javascript memory leaks can happen, and I would not even know where to begin to debug them.

There are also other things that are kind of double edged swords.  For example, with single page applications, the data processed for each request can be a lot less since the application will be asking for the minimum data it needs for the particular request, however it also means that there could be a lot more small request to the server.  I'm not sure if that is a good or bad thing.

What are some of the advantages and disadvantages of single page web applications that I should keep in mind when deciding which way I should go for my project?


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答: Code that produces warnings when compiled.</p>


问:
When to distinguish OS versions in canonical names for target platforms
I would like to organize my company's software releases by platform. I've looked at how Mozilla, Perforce, and Apache organize their releases, and it seems that I should partition by OS and processor architecture. I was thinking of something like this:

Linux (x86-32)

Linux (x86-64)

Neutrino (x86-32)

Windows (x86-32)

Windows (x86-64)

Is it common to distinguish between versions of Windows, Linux, or OS X? For example, should I be specifying the Linux kernel version?

答: I would say only if it matters. If you know there are issues with the prior version(s) of the kernel OR if you have not tested with earlier versions, then you should put something like "3.3+" to indicate that anything after kernel 3.3 is known to be tested and good. Anything else is unsupported - it may work, it may not.


答:
It's true, that ASP.NET experience is beneficial for stepping into Sharepoint development considering Sharepoint itself is developed in ASP.NET Webforms, but the underlying ideas of the two are very different. ASP.NET is a framework where as Sharepoint is a full blown development platform.

While you code everything yourself (in a figure of speech) in ASP.NET you won't be developing for Sharepoint like that. Most of the time is spent configuring and molding vanilla Sharepoint into something that is of value to the client.

Sharepoint does a lot for you and that's great. It's ease of page editing without any app redeploys and coding skills holds great appeal for the clients, but it's still very rough around the edges.
No change is as easy as it should be and you will be spending a lot of time fighting with the obscure API of SP. I don't remember the names of the API methods that turned a few of my hairs  gray, but i swear there were a plentiful that just wouldn't work and the other lot that had no documentation.

There are many quirks and do-not-touch areas, that all beginner Sharepoint developers sink a lot of time into on their first try with the platform. Considering the amount of XML you are forced to configure i'd say a step into Sharepoint gives you a good insight of what Java EE developers go through. My point is, ASP.NET experience is helpful, but it doesn't get you very far. Sharepoint is HUGE and a speciality in itself. IMO not something you would easily "master" under 3 - 5 years of experience.

Title: asp .net development skills transferred to sharepoint?

Body: Would a competent asp .net C# developer be disregarding a lot of their skills in order to have more concern with configuration and server-side coding when moving their career into the sharepoint 2010 arena? Or is asp .net C# in fact just a good base to begin the study of sharepoint on?</p>