答:
As others have already said, a big part of what software engineering is about are "extrinsic constraints". eg. Time, budget, service, support, satisfying irrational idiotic demands, etc.

A lot of us (myself included) got into programming thinking it's all about the programming itself - coding beautiful and elegant pieces of software in a vacuum (or a relative vacuum at least). It rarely is. There might be some rare academic or R&D software jobs which come close to it, but for the most part, the overwhelming majority of software development work is nothing like that. Especially in the maintenance phase - which is typically 90%+ of a product's lifetime - and the bread and butter everyday routine of most permanent commercial software work.

For a long time, I had an internal conflict about this which often made me unhappy about my work (and it's part of what eventually lead to a burnout last year). I always felt that a job sucks if it isn't all about creating beautiful code and taking the time to do it propertly. But really, this is the reality - and some people actually thrive on a very service-oriented work flow. It's what makes them feel pragmatic and useful. Even if the actual "pure software engineering" aspects of a project get relatively rushed and sloppy.

Anyway, it's good that you're questioning this now. This is one of those things that they never really explain properly at school. And companies love to pretend that they follow very good engineering practices even if they don't. Hint: most don't.

All that said, things vary. Certain companies (mostly those for whom software is their core business, and those who work on highly safety-critical software such as medical gear) do follow a very strict engineering process. But overall, yes, I'll tell you point blank now that most commercial software work is relatively sloppy. There is usually some formal process, but adhering to it strictly almost always takes a back seat to reacting to client input and other commercial pressures. It's not really "sloppiness" per se, it's just plain pragmatic usefulness. The trick is to find your niche, and look at a role from the point of view from what service it provides, rather than how cool the "pure programming" aspect of it is.

EDIT: I think I might have sounded too one-sided in my initial assessment. I'd like to add that often there are also genuine problems with things being too sloppy, and lack of good process - to the point where it's driving the project into technical debt and is actually bad for the business. But seeing this comes with experience. The initial point still basically stands: most commercial software work today is not as rigidly engineering oriented as purists might like.


问:
Should organizations penalize developers for the amount of defect reports filed against code they worked on?
Should organizations penalize developers for defect reports filed against their work products?

I was having a discussion with my friend where he asks if a manager taking the number of defects filed against a developer is justified. My take is no, because developers can introduce defects, but by holding those against him can cause unnecessary negative feelings in the developer's mind.

What are the problems with penalizing developers based on defects that they inject? Does your organization penalize developers for creating defects in work products?

答: My opinion is no because if an organization does penalize developers for the amount of bugs filed against them then the developer may be less productive in order to avoid the penalties assuming they are substantial.  There can also be conflict over what bugs would be filed against a developer as there may be a QA person taking a liberal view of what constitutes a bug that is another factor here.  While one could try to balance the penalties, I'd be curious to see how well that is done in reality.</p>

ContentLicense: CC BY-SA 3.0


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答: The Soul of a New Machine

ContentLicense: CC BY-SA 2.5

Body: The Soul of a New Machine


问:
Why is there still case sensitivity in some programming languages?
I don't see any use for case sensitivity in a programming language, apart from obfuscating code.

Why implement this in a programming language?

Update:

It looks like someone you know made a statement on this.

答:
While case folding is fairly trivial in English, it's much less so in some other languages.
If a German programmer uses ß in a variable name, what are you going to consider the upper-case equivalent? Just FYI, "ß" is only ever used in lower case. OTOH, "ss" is equivalent -- would you consider a compiler obliged to match them? When you get into Unicode, you get even more interesting problems, such as characters with pre-composed diacritical marks versus separate combining diacriticals.  Then you get to some Arabic scripts, with three separate forms of many letters, rather than just two.

In the dark ages most programming languages were case-insensitive almost out of necessity. For example, Pascal started out on Control Data mainframes, which used only six bits per character (64 codes, total). Most such machines used the "CDC Scientific" character set, which only contained upper-case characters. You could switch to other character sets, but most had either upper-case or lower-case, but not both -- but used the same codes for both. The same was true of the ancient Baudot codes and such considered standard in the beginning days of COBOL, FORTRAN, BASIC, etc. By the time more capable hardware was widely available, their being case-insensitive was so thoroughly ingrained that changing it was impossible.

Over time, the real difficulty of case-insensitivity has become more apparent, and language designers have mostly decided ("realized" would probably be a more accurate term) that when/if people really want case insensitivity, that it's better handled by ancillary tools than in the language itself.

At least IMO, compiler should take input exactly as presented, not decide that "you wrote this, but I'm going to assume you really meant something else." If you want translations to happen, you're better off doing them separately, with tools built to handle that well.


问:
Importance of hobby projects
I want to know, how important is it to program in your spare time? Is it necessary to work your 9-5 as a programmer and then get home and work on your hobby to become a better programmer?

This said, I know you only get better at programming by, well, programming.

Do prospective employers take hobby programming into account in an interview or do they ask this just out of curiosity?

I feel guilty for not having a hobby project, but everything I can think of doing has already been done. So I am kind of in two minds about this, start something that has already been done or leave it until I come up with something original?

答:
I'm involving in interviewing and hiring at my shop.  A 'hobby project' is always a plus to us.

Having a more or less finished personal project shows you really enjoy creating software, and shows that you are motivated to learn new things and improve your skills.

If you want to make a really positive impression in an interview, bring a laptop with your personal project. Show it to the interviewer, tell him about the challenges you encountered while building it, let them see your code.  Tell them upfront where the rough edges are and what your future plans for the project might be.

You will be remembered, in a good way.

Title: Importance of hobby projects


问:
Where to put common shared methods
I have a bunch of methods that are commonly used everywhere. Right now the codefile is named globals, to represent the fact that they are... in fact... global.

However, I do not like this.

I want to group these into a class and pass an interface around. I'll make only one instance, but I'm not falling into the singleton trap here.

First of all, what should I name the class. I want to avoid the globals name because I'm afraid maintainers would get the wrong idea.

Also, how should I consider splitting up such a set of methods so that behavior can change and adapt?

The set of methods contains stuff like:

Conversion tables

Clipboard interaction

Managing built fonts

Common drawing methods

Providing an interface with access to often used resources

答:
If you are going to make one instance, you pretty much have a singleton.  Also, the thing people would normally be referring to if they talk about a singleton trap is that singletons are global, and most classes are better off not being global.  So you might as well have a singleton.  If you can reasonable pass an interface around to objects that might want to call it then it isn't really global.

Also, putting it all in one grab-bag of global methods makes it difficult to have the behavior change and adapt since not only does each change to one method necessitate a new subclass, but each combination of changes would need it's own subclass.

I would recommend having singletons for each one that truly is global (I'll take your word they all are) and some kind of registry or factory that gives you an instance (which means you can implement as singleton or not, since the interface will make no promises).  I would name them based on what they do from the caller's perspective.

Title: Where to put common shared methods


问:
one programmer, many languages -- the name dilemma
When you work across multiple programming languages, there is a problem you encounter...

A valid name (identifier) in one language is invalid in another. For example...

var new function this are a keywords in JavaScript, but you can use them freely in Python. Similarly list dict def can be used in JavaScript without problems.

This is a very common and something programmers generally quickly become acquainted with when they program in multiple languages.

However, when you're working in collaboration, you have to lay out some rules/guidelines for your team members to ensure consistency and uniformity in the code. With teams, this issue becomes more important than simply remembering what's valid and what's not while you program.

So, my question is, what strategies you adopt...

simply take a union of all the reserved words present in all the languages you use, hand out a list to everybody and abstain their use?

accept the diversity and take extra pains when "context switching"

adopt an intermediate ground where one language can use the other's, but not vice-versa

(Note: i am only talking about Python and JavaScript in this question ... but please answer the question more broadly)

-- UPDATE --

Thanks for all the answers. So the general consensus i see emerging is to let programmers use any name regardless of what they do other languages -- as long as names are descriptive, it doesn't hurt.

答:
You shouldn't waste your time on writing guidelines until you discover this is an actual, not hypothetic problem.

One situation I can think of where this can become a problem is when you share data structures between programming languages. For example, if you have a Javascript object on the client side that is reflected in a Python object on the server side, and you naturally want them to have the same names for their members. In that case the rule is simple: Don't use names that are reserved words in any of the languages. That's it. Write that in the guidelines if you want to. Now move on to more important tasks.

BTW, neither list nor dict is a reserved word in Python. They can be used as variable names, though pretty lousy ones.


问:
What traits do the best managers you've worked for have in common?
I have been listening to Scott Hanselman and Rob Conery's podcast, This Developer's Life.

In the latest episode, they discuss personality traits:

1.0.4 - Being Mean.

What makes people mean in our
  industry? What about aggressive?
  Confident? What's the difference?
  Would you rather have a drill sergeant
  for a boss, or a zen master? We talk
  to Cyra Richardson and Giles Bowkett.

It got me thinking, what traits did the best managers you've worked for have in common?

EDIT: Just to clarify, as there have been a few close votes, I'm interested in whether there are traits common to managers of developers that are not necessarily those traits that a manager of some other profession requires.

As for whether this is programming related or not, well I don't want to ask this question on a site that isn't about programming because, frankly, I'm not as interested in what people who make cans of soup for a living want from their managers as I am interested in what developers want from their managers.

答: Someone who is clear in what needs to be done, lets me work out the technical details, provides context when needed, and doesn't change requirements when I'm more than halfway done.</p>


答:
The namespace could be [application].Common.Shared

Classes could be named:

```<code>ConversionLookup
ClipboardCommunication
FontManager
DrawingUtility
</code>```

I would break up the classes because it sounds like they do different things.

Title: Where to put common shared methods

Body:
I have a bunch of methods that are commonly used everywhere. Right now the codefile is named globals, to represent the fact that they are... in fact... global.

However, I do not like this.

I want to group these into a class and pass an interface around. I'll make only one instance, but I'm not falling into the singleton trap here.

First of all, what should I name the class. I want to avoid the globals name because I'm afraid maintainers would get the wrong idea.

Also, how should I consider splitting up such a set of methods so that behavior can change and adapt?

The set of methods contains stuff like:

Conversion tables

Clipboard interaction

Managing built fonts

Common drawing methods

Providing an interface with access to often used resources

Body:
The namespace could be [application].Common.Shared

Classes could be named:

ConversionLookup
ClipboardCommunication
FontManager
DrawingUtility

I would break up the classes because it sounds like they do different things.


问:
Develop fast and buggy, then correct errors or be slow, careful for each line of code?

Possible Duplicates:

  Frankly, do you prefer Cowboy coding?

  Prototyping vs. Clean Code at the early stages

  Good design: How much hackyness is acceptable?

  Does craftsmanship pay off?

Which is better:

Coding fast, not caring about possible errors and limits, maybe forgetting to check the input, NULL returns etc, just to complete the task or to get to the milestone, and then correct all possible errors.

Coding slow, checking every line you write many times, writing tests, and checking every possible input to make a code as bug free as you can but taking weeks to write a working program.

Actually I'm using the 2nd way but it's frustrating to work, work, work and see only small improvements every day...

答:
Jarrod answered this along the dimension of the business situation.

Although that's valid, I also think the answer varies based on the type of program -- or even for different parts or "levels" of the same large program.

Deep in an "engine" used broadly by the program, it will pay off to go slow, steady, careful. Make use of tests. Do yourself a favor and define the interfaces narrowly enough that you don't need a bazillion tests to cover an excess of permutations.

But closer to the "edges" of the program, such as the UI or interfaces to evolving, external APIs, it is probably wiser to go faster. After all, the requirements are more likely to change. Plus you are more likely to find problems via direct observation by you and beta testers, than you are by wanking off writing elaborate test suites that have less hope of getting you full coverage.

Basically this is common sense, keyed off of your assessment of how stable or well-defined a given part of the program is likely to be.


答:
Programmers are notorious for optimizing what managers start rewarding. If you reward LOC, then you get lots of whitespace to pad out the lines of code metric. If you try to punish by bug count, you will start getting into wars where the developers claim that X is not their bug (the bug is in the compiler or API or just somewhere else) - and the bug filed against them is wrong.

The last place I worked had a developer "in charge" of a product. While the "in charge" dev never changed over the years, others would work on the project when the seasonal load made it necessary. No one pointed fingers and said "you wrote that bug!" Instead, the goal was to reduce bugs in the products.

The places I've worked that had penalties for bugs also had very high turn over. The finger-pointing contributed to a hostile environment which led to the departure of developers.

Title: Should organizations penalize developers for the amount of defect reports filed against code they worked on?

Body:
Should organizations penalize developers for defect reports filed against their work products?

I was having a discussion with my friend where he asks if a manager taking the number of defects filed against a developer is justified. My take is no, because developers can introduce defects, but by holding those against him can cause unnecessary negative feelings in the developer's mind.

What are the problems with penalizing developers based on defects that they inject? Does your organization penalize developers for creating defects in work products?


问:
Measures of Javascript engine performances over time?
Since the beginning of the Javascript race -- which I would situate around Google Chrome launch in 2008 -- the improvement in the Javascript engine performances have been impressive.

The web is crowded with comparisons such as "Firefox V3.42.7 vs. Safari 3.0-prealpha2", and the winner of those comparisons changes every few months and differs on each benchmark.

But the big picture, independently of who got their new version out last, is that the average speed of current up-to-date browsers has improved a lot over the last years. Yet this long-term improvement is difficult to quantify:

people usually compare the last version of each browser, and not different versions of one browser

announced performance improvements do not generally pile up: when someone announce V3 twice as fast as V2, and later V4 twice as fast as V3, this does not mean that V3 is fourth times as fast as V1, because they usually mean "in a favorable case", and the favorable case in the V3-4 transition are not necessarily the same as in the V2-3 transition

benchmarks themselves evolve over time; what is referred as "the Sunspider test" today is not the same as in 2008, so we cannot compare raw scores over time.

Does anyone know of a valuable measurement of javascript engines performance improvement over the last few years?

答:
As a side effect of keeping the benchmarks game files in CVS, anyone willing to do careful work should be able to gather together a little performance history.

For example,

You can find out when each new version text for V8 was committed.

You can find the data.csv file version just after the dates of your selected version files

You can "select for diffs" and diff the data.csv files for just after those dates

You can use page search to find all the V8 rows with status 0, and copy to a text file

Then you need to check that the data rows are for the same program. Firstly, that they have the same prefix (nbody,v8,1) and secondly that they reported the same program size gzip (1287).

So for - V8 version 1.2.5 (candidate) [console: dumb] - from Jun 9 2009 you could dig out these data rows

name,lang,id,n,size(B),cpu(s),mem(KB),status,load,elapsed(s)
fasta,v8,1,25000000,791,**125.240**,10088,0,2% 1% 1% 100%,125.241
nbody,v8,1,50000000,1287,**211.753**,10088,0,0% 0% 0% 100%,211.755
spectralnorm,v8,1,5500,311,**88.122**,12588,0,0% 0% 0% 100%,88.120
```</li>
<li><p>And you could match those with these data rows for - V8 version 3.4.7 [console: dumb] - from Jun 28 2011 </p>

<pre class="lang-none prettyprint-override"><code>name,lang,id,n,size(B),cpu(s),mem(KB),status,load,elapsed(s)
fasta,v8,1,25000000,791,**30.750**,5712,0,0% 0% 0% 100%,30.762
nbody,v8,1,50000000,1287,**71.068**,12852,0,0% 0% 0% 100%,71.118
spectralnorm,v8,1,5500,311,**33.462**,6580,0,0% 0% 0% 100%,33.474
</code>```

Start with a later version (like V8 version 1.3.11.1) and you should be able to match more of the programs.

Have fun.

And for Mozilla  (2008-2011)

You can find out when each new version text was committed.

You can "select for diffs" and diff the data.csv files for just after those dates (April 8 2011 is the last date to include tracemonkey)

You can use page search to find all the tracemonkey rows with status 0, and copy to a text file

etc

And for older Mozilla (2005-2007) on a different machine, using different programs

You can find out when each new version text was committed.

You can "select for diffs" and diff the data.csv files for just after those dates

You can use page search to find all the javascript rows with status 0, and copy to a text file

etc

The problem you'll see in that old data is that over time some tasks were removed and some new tasks were added, and there isn't a nice way to figure out when that happened. Probably the easiest approach would be to make a note of the earliest timestamp for each task description text, and then check the data file for a date just after that looking for a javascript program that implements the new task.

I should probably also say that you could dig out the source code for the programs, for example binarytrees.javascript

Body:
As a side effect of keeping the benchmarks game files in CVS, anyone willing to do careful work should be able to gather together a little performance history.

For example,

You can find out when each new version text for V8 was committed.

You can find the data.csv file version just after the dates of your selected version files

You can "select for diffs" and diff the data.csv files for just after those dates

You can use page search to find all the V8 rows with status 0, and copy to a text file

Then you need to check that the data rows are for the same program. Firstly, that they have the same prefix (nbody,v8,1) and secondly that they reported the same program size gzip (1287).

So for - V8 version 1.2.5 (candidate) [console: dumb] - from Jun 9 2009 you could dig out these data rows

name,lang,id,n,size(B),cpu(s),mem(KB),status,load,elapsed(s)
fasta,v8,1,25000000,791,**125.240**,10088,0,2% 1% 1% 100%,125.241
nbody,v8,1,50000000,1287,**211.753**,10088,0,0% 0% 0% 100%,211.755
spectralnorm,v8,1,5500,311,**88.122**,12588,0,0% 0% 0% 100%,88.120

And you could match those with these data rows for - V8 version 3.4.7 [console: dumb] - from Jun 28 2011

name,lang,id,n,size(B),cpu(s),mem(KB),status,load,elapsed(s)
fasta,v8,1,25000000,791,**30.750**,5712,0,0% 0% 0% 100%,30.762
nbody,v8,1,50000000,1287,**71.068**,12852,0,0% 0% 0% 100%,71.118
spectralnorm,v8,1,5500,311,**33.462**,6580,0,0% 0% 0% 100%,33.474

Start with a later version (like V8 version 1.3.11.1) and you should be able to match more of the programs.

Have fun.

And for Mozilla  (2008-2011)

You can find out when each new version text was committed.

You can "select for diffs" and diff the data.csv files for just after those dates (April 8 2011 is the last date to include tracemonkey)

You can use page search to find all the tracemonkey rows with status 0, and copy to a text file

etc

And for older Mozilla (2005-2007) on a different machine, using different programs

You can find out when each new version text was committed.

You can "select for diffs" and diff the data.csv files for just after those dates

You can use page search to find all the javascript rows with status 0, and copy to a text file

etc

The problem you'll see in that old data is that over time some tasks were removed and some new tasks were added, and there isn't a nice way to figure out when that happened. Probably the easiest approach would be to make a note of the earliest timestamp for each task description text, and then check the data file for a date just after that looking for a javascript program that implements the new task.

I should probably also say that you could dig out the source code for the programs, for example binarytrees.javascript


答:
Sounds like it would do more harm than good. Ignoring for a moment whether it is fair for a manager to do that, let's look at the logistics...

Problem 1: Are all bugs created equal?

Developer 1 introduces a bug: Erases all customer data and curses at them.

Developer 2 introduces two bugs: Form labels are not left aligned, and the calendaring feature is off by 1 second if an event is created that spans two leap years.

So clearly developer 2 deserves more grief from their manager because they have double the bug rate. Of course not, so you come up with a bug rating system so developers with trivial bugs don't get dinged so hard. But wait, should the system factor in a modifier for a developer who is clearly making the same trivial mistake repeatedly and wasting the tester's time because they never learn from their mistakes? Maybe, hmmm. This is complicated.

Problem 2: What counts as a bug?

Manager - This report was supposed to include a running total, that's one bug for you!

Developer - That wasn't in the requirements, that's a FEATURE not a bug.

Problem 3: How do you group bugs?

Developer - "[Manager's Name], the testers filed 10 bugs against me because the velocities were incorrect on 10 different screens, but that was all related to a single bug in the getVelocity function. We argued for 3 hours about it, but they won't budge. We would like a sit down meeting with you to decide how many bugs should be filed. Oh and by the way, there is no way we are going to hit the code complete deadline tomorrow."

Problem 4: More SLOC probably means more bugs

Developer 1 sits on his butt all day, but manages to write 3 bug-free lines of code between arguments on Reddit over Arizona's immigration law.

Developer 2 works hard all day and churns out a fully functional AI that won't kill John Connor the first chance it gets."

So obviously you want to penalize the developer who makes more progress and/or takes more risks by innovating, right?

Summary

There are probably workable solutions to several of these, but as a manager of a programming team trying to meet a deadline do you really want to have everyone spending time arguing about what counts as a bug, what counts as a discrete bug, the importance of a bug, etc.? None of these things move your project forward and this will be poison for teams who will be forced to compete on issues that have no meaningful impact on the actual software being created. Not to mention what it does to your employee culture to focus this much effort on finding ways to make sure that every employee's mistakes are meticulously recorded so they can be thrown back in their face later.

Inevitably you will have developers cajoling testers to work around your bug tracking system and report issues directly so they can fix them without it going in their "PERMANENT FILE". Then you don't even have an accurate accounting of bugs or what people are really working on.

Then there is the issue of adverse impact. That is HR talk for, you better have pretty good documentation before you start penalizing employees, especially financially. And if any of them are a protected class (minorities, veterans, women, handicapped, etc.) you better be triple sure that whatever system you have set up doesn't discriminate against one of them based on membership in that class (or that a judge could be convinced as such), even if it is just an unintended side-effect of the plan.

So ultimately, you are not creating incentives to create less bugs, which is hard, but rather to negotiate away bugs by minimizing their importance or blaming them on someone else.

Short Version No.


答: Developers are not naturally lazy or ignorant to what's best.  In my opinion, it would be more productive to give the developers a more accurate timeline, and better specifications prior to the project kicking off.


答:
I say that this is a bad idea that will do little but create a hostile work environment.

I would even go so far as to say that ANY NEGATIVE REINFORCEMENT as a motivator for job performance will create an unhappy workforce and high turnover.  Even good developers will feel stressed about slipping.

Negative reinforcement is even demeaning for children and dogs, why would you treat a professional in such a way?

Instead use positive reinforcements for LOW DEFECT NUMBERS and actively try to help members of your team who are struggling.  If it doesn't work out with somebody over the long run then just let them go.


问:
Is there a standard for when you include libraries or not?
I often come across a class which has a single reference to another library and was wondering if its better to include the library or to reference the object by it's full name. Is one better then the other? Is one more of a standard then another?

For example using System.Windows.Messagebox:

Option A:

```<code>using System.Windows;

public class MyClass
{
    SomeMethod()
    {
        MessageBox.Show("Something");
    }
}
</code>```

Option B:

```<code>public class MyClass
{
    SomeMethod()
    {
        System.Windows.MessageBox.Show("Something");
    }
}
</code>```

If B, how many references do you need before you decide to add the entire library?

答: Option A clearly identifies your class' dependencies.  If it has too many, you will notice that very easily.</p>


答: I normally put these types of things in their own assembly names something like "foo.Common" under a namespaces like "foo.Common.Collections" or "foo.common.UI" etc. then, I can reference the assembly in whatever project I need them.</p>

Title: Where to put common shared methods


问:
How do I store the OAuth v1 consumer key and secret for an open source desktop Twitter client without revealing it to the user?
I want to make a thick-client, desktop, open source twitter client. I happen to be using .NET as my language and Twitterizer as my OAuth/Twitter wrapper, and my app will likely be released as open source.

To get an OAuth token, four pieces of information are required:

Access Token (twitter user name)

Access Secret (twitter password)

Consumer Key

Consumer Secret

The second two pieces of information are not to be shared, like a PGP private key. However, due to the way the OAuth authorization flow is designed, these need to be on the native app. Even if the application was not open source, and the consumer key/secret were encrypted, a reasonably skilled user could gain access to the consumer key/secret pair.

So my question is, how do I get around this problem? What is the proper strategy for a desktop Twitter client to protect its consumer key and secret?

答: I found an answer that mirrors the path I was considering going down on hueniverse. The article, Beyond the OAuth Web Redirection Flow, offers some suggestsions, one of them being a web url that proxies the token exchange process. I have to work out a way to properly authenticate that my app is what is requesting the authentication to this proxy page. However, that is possible.</p>

ContentLicense: CC BY-SA 4.0


答:
Definitely not.

Its like demoting doctors because some of there patients die, without considering how serious the illness/injury was.

There are some projects where Defects are just unavoidable. If you have project sponsors with conflicting needs, user requirements that conflict with security guidelines, ill though out last minute changes then there will be defects raised no matter what the quality of your code.

There is also the perennial problem (at least in most large organizations) of the infrastructure changing around you. You code for V1.25 of the database on V3.8 of the OS but another department upgrades to V2.0 and V4.0 just before you go live. (Or downgrade, in one case we coded for V5.0 J2EE only to have the upgrade cancelled and had to defactor down to V4.0 days before the release -- there were a lot of defects.).

Lastly we have the pragmatic users who raise defects instead of change requests as the bureaucratic burden is significantly lower.


答:
Developers should hold themselves accountable for the quality of the code they produce, and they should expect that their manager will do the same. But that doesn't mean that some developer should get a demerit every time a bug is reported. No manager in their right mind would say:

Well, Johnson, you checked in 500 lines of code last week, and so far
  241 bug reports have been traced to that code.

It's a lot of work to figure out who to blame for every little defect, and the number of bug reports doesn't always tell you much about the quality of the code. But a good manager should notice problems and find ways to fix them. He or she might say:

Johnson, that was one stinker of a checkin last week -- we've been
  getting bug reports at three times the normal rate. We need to get
  that fixed ASAP, so I've asked 'Eagle-Eye' Ferguson to go over the
  code with you. I'm sure the two of you will figure it out, and ol'
  Eagle-Eye might show you a few tricks along the way.

Every developer should expect the manager to notice their performance, including the general quality of their code. Developers should also expect their colleagues to notice -- it's all right there in the repository, after all. So if you're that guy with the high bug count, don't be ashamed to ask for some help. The rest of the team probably already knows where you're at, and if you make a concerted effort to improve the team (and the manager) will notice that too.

So, yes, you should be accountable for the code that you write, but no, the organization shouldn't have a policy of penalizing individual developers for specific defects, or for exceeding some number of defect reports. That's just going to encourage people to find ways to avoid the blame, like pointing fingers or being so careful that productivity drops. It doesn't help the development effort if people are afraid to accept responsibility for what they write. BTW, it also doesn't help to turn it around and reward specific bug fixes. ;-)


答:
I'll buck the trend here, go out on a limb, and give a resounding YES!, but with a certain qualification:  only for developers who are at least a standard deviation worse than their peers.

Let me break that down a bit, because there are a some loaded issues here.  First up is the word "peers".  It's certainly not right to compare the work of a 10 year veteran with that of a new hire fresh out of college.  The newbie has less experience, but the pro is given more difficult assignments.

Next up is standard deviation.  Programmers will historically on one hand resist any attempt at quantitative measurement of their work with claims of gaming the metrics, and on the other both practice the art of daily finding ways to quantify the unquantifyable through software and quote metrics about how the rockstar programmers are X times more productive than the average.  There is some obvious truth on both sides.

My belief is that the best of use metrics, even simplistic ones like "lines of code", is for identifying stand-outs.  You set a boundary of a standard deviation or two away from the norm, such that individuals programmers will be unable to break from the pack. Don't look for the top or the bottom programmer.  The whole point here is that most of the time, no one is identified and so there's nothing to game.  But every now and then it'll help you find that gem of a programmer, or tell you who your real under-performer is.  And then you know what you do? Nothing.  At least at first.  Instead, think of it as unconfirmed intelligence.  Use the information to watch the person, and look to confirm it elsewhere.

If you have a programmer who is checking bugs an order of magnitude more often than his peers, first find something to corroborate his overall performance and then go have a talk with him.  And the first time, it probably should just be a talk.


问:
What to say when you don’t know the answer to an interview question?
When you have no clue about the question, how do you answer/act when you do not know the answer at all? Telling the truth is pretty obvious. But how could you try to transform this weakness into a strength?</p>

答:
"I have never worked with ????.  When i a had a problem that ???? solves, i instead used  (insert real example that relates to my resume here)"  </p>

<p>Having every opportunity to prove that you are not lying about projects you worked on, can be much more powerful than knowing a detail </p>

Body:
"I have never worked with ????.  When i a had a problem that ???? solves, i instead used  (insert real example that relates to my resume here)"

Having every opportunity to prove that you are not lying about projects you worked on, can be much more powerful than knowing a detail


问:
What is the most frequently used design pattern?
Which design pattern do you think is the most popular?</p>

答:
Decorator

Add functionality to an object at runtime through composition. My personal favorite.

Edit: Also Factory is probably one of the most common.


答: Someone who understands that development is not factory work.  Putting in more hours per day is not likely to get significantly higher yield.  Programmers need to pick their nose up from the grindstone pretty often and just not think about what they are working on to solve a problem and get things done.</p>

Title: What traits do the best managers you've worked for have in common?

Body:
I have been listening to Scott Hanselman and Rob Conery's podcast, This Developer's Life.

In the latest episode, they discuss personality traits:

1.0.4 - Being Mean.

What makes people mean in our
  industry? What about aggressive?
  Confident? What's the difference?
  Would you rather have a drill sergeant
  for a boss, or a zen master? We talk
  to Cyra Richardson and Giles Bowkett.

It got me thinking, what traits did the best managers you've worked for have in common?

EDIT: Just to clarify, as there have been a few close votes, I'm interested in whether there are traits common to managers of developers that are not necessarily those traits that a manager of some other profession requires.

As for whether this is programming related or not, well I don't want to ask this question on a site that isn't about programming because, frankly, I'm not as interested in what people who make cans of soup for a living want from their managers as I am interested in what developers want from their managers.


问:
How do you respond to: "Ever since the update..." questions from clients?
Ever since the update, people keep calling and saying "Ever since the update X, Y and Z are slow, bad and crashing"

This has happened ever since the dawn of updates.

What do people expect? Gamma comes after beta, and gamma testing always turns our users into The Incredible Hulks...

Perhaps you've never heard this from a client, perhaps you're in college or a FLOSS Dev who can spread the blame around more than 5 or 6 guys, perhaps you unit test your code, perhaps you're not in that interesting situation where customers actually call you requesting the exact time of day you'll be releasing today's patch (I'd love to do that to Microsoft) or perhaps you're a sorry son-of-a-biscuit like me who just shipped a new update and went home and is dreading going back to work tomorrow.

Anyway, ya'll are smarter than me anyway. How do you field criticism framed in "You must be a bad programmer because you're making your software worse"?

答:
If this happens to you every time you deploy, there could be a serious flaw in your development process. I would suspect a couple of things that are causing the problems.

Do you develop against a
database that is the same size
(roughly) as production? If not then
you will always have these problems
because queries that are fine with
small data sets are often dogs with
bigs ones.

Do you load test in QA? What
works fine with one user testing is
very different from how things will
respond with 1000 users trying to do
things at the same time.

Do you assume the user's
perception is wrong and treat them
like they are stupid for
complaining? If so, then your
attitude is causing more complaints
not lessening them.

Are you doing a good job of
testing? Do you regression test features not changed to see if they are affected by the change? Do you even care how long
things take until they hit prod?

Do you pay attention to when is a
    good time for the users when you
    deploy or do you merrily deploy a
    change to the accounting system the
    day payroll is run and wonder why
    users are angry at the slow down?

Do you have environmental
differences between dev and prod.
Sometimes those pesky differences in
operating systems or database
versions will cause issues like this
as well. It is often a good idea to have a staging enviromnet that is exactly like prod, some equipment same operating system, same database with dat that is as close to prod data as possible. This is used to test your deployment. Run it first on this server and tehn have some users or testers go to it and run through some tests.

How good is your deployment process,
do you often miss steps?  Can it be
run by someone other than the
developer because it is clear what
code goes in the branch you are
deploying? We got a lot better at
deploying code when we got a
configuration management team and
nobody had the rights to sit with
prod and babysit it making "oopsie"
changes. Automating your build can help tremendously. No one should be guessing what needs to go to prod as it should have gone to QA and staging first and any deplyment issues worked out. Scripting database changes is key too. They shoud be in scripts and in source control, so the build process can pick them up without someone having to remember, oh yeah, we need to change the length on Column B to 241 from 50. I find that people often forget to treat database changes as code preferring to use the GUI which is virtually always a bad idea on prod.


问:
What's the difference between an Asset and a Resource?
I've used several IDEs and created several default projects. Upon creation, I'll find folder structures created for me. Sometimes I'll see a Resources folder, sometimes an Assets folder, and sometimes both. Is there actually a (standard) difference?</p>

答:
It's a just a difference in terminology.  In this context assets are the non-source code resources you use in your solution.

We follow a /res/ name convention, which typically stores javascript, css, images, and more.  Javascript and CSS are source code resources, so assets is more concerned with media (images, video, documents) etc. a subset of resources, if you will.


答:
Most of the time I would consider them synonyms. They both serve as valid places to store non-source code items.

When both appear in the same project, the only difference I can come up with

Resource - Configuration files, something that has code or markup in it

Asset - Images, video, other things that aren't code, markup, or configuration. Think very static

I will say though that the difference is minor and outside of a few circumstances they should be considered synonyms.

Title: What's the difference between an Asset and a Resource?

Body: I've used several IDEs and created several default projects. Upon creation, I'll find folder structures created for me. Sometimes I'll see a Resources folder, sometimes an Assets folder, and sometimes both. Is there actually a (standard) difference?</p>


问:
Do you throw an argumentexception or argumentnullexception from private methods?
I was just reviewing some code I wrote a while back, and can see that I have a couple of private methods that throw argumentnullexceptions and/or argumentexceptions if there are issues with the methods parameters.

I guess my rationale is that helps future proof the application if someone attempts to "misuse" the method in future. However, given it is a private method and the people who are likely to call this method can see the associated comments and code, it is just unnecessary to throw this. It certainly doesn't hurt to have them, although it does add clutter.

My feeling is that these exceptions are generally more useful on something like a API that is going to be exposed publically.

答: There are better ways to avoid null reference check: use code contract or an AOP framework to do the check for you. Google "c# code contract" or "postsharp".</p>


答:
No, they should not. This is no manual labour and none creates bugs intentionally.
How can we expect productivity from a sad horrified programmer? Things should be cool around him. Ultimately noone get benefitted from penalizing.


答:
Normally, for private methods you do not throw exceptions since as you wrote it, the developer is supposed to know how and where he is calling the method from. As such, the variables passed as parameters to the private method should be checked outside of the method, that is, before calling it.
Throwing "InvalidArgumentException" and other such exceptions is considered good practice for public methods (whether you are writing an "API" or not).

For those cases where you want to throw "InvalidArgumentException" it's worth mentioning that there is an Assert class in the Spring API for Java since version 1.1.2. It has been very helpful - to me at least - in writing less code to perform checks.

You may however use "asserts" to check parameters in private methods. That is one of their true purpose. They are more reasons to use them, check out the following link which also explains thoroughly when to use asserts and when to use exceptions.
Asserts are not to be included in production code and the compiler removes them by default. So they are what you are looking for: helping the developers, invisible for the users. In Java you have to use a special flag ("-ea") to tell the compiler to enable assertions. You may consider them as "debugging" friends.

Here is how to use asserts in:

Java: http://download.oracle.com/javase/1.4.2/docs/guide/lang/assert.html

.NET: http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.assert(v=VS.100).aspx

Title: Do you throw an argumentexception or argumentnullexception from private methods?

Body:
I was just reviewing some code I wrote a while back, and can see that I have a couple of private methods that throw argumentnullexceptions and/or argumentexceptions if there are issues with the methods parameters.

I guess my rationale is that helps future proof the application if someone attempts to "misuse" the method in future. However, given it is a private method and the people who are likely to call this method can see the associated comments and code, it is just unnecessary to throw this. It certainly doesn't hurt to have them, although it does add clutter.

My feeling is that these exceptions are generally more useful on something like a API that is going to be exposed publically.


问:
What to do when the programming activity becomes a problem?
I once saw a program (can't remember which) where it talked about people "experiencing flow" when they are doing something they are passionate about. When "in flow", they tend to lose track of time and surrounding, concentrating only on their activity at hand.

This happens a lot for me when I program; most particularly when I face a problem. I refuse to give up until it's solved. This usually leads to hours just rushing by and I forget to eat lunch, dinner gets pushed into far into the evening, and when I finally look at the clock, it's way into the wee-hours of the night and I will only get a few hours of sleep before having to rise early in the morning. (This is not to say that I'm in flow only when facing a problem - but I find it particularly hard to stop programming and step back when there's something I can't solve immediately.)

I love programming, but I hate it when it disrupts my normal routines (most importantly eating and sleeping patterns). And sitting still for so many hours, staring a screen, is not healthy.

Please, any ideas on how I can get my rampant programming activity under control?

答: Set an alarm clock to when you want to stop and decide if you want to continue crunching or call it a day. </p>


问:
How to begin writing a relational SQL database
I was wondering about how databases like MySQL and SQLite are developed to run as quickly and as well as they do.

I'm looking for answers to questions like:

How is SQL token-ized? Do you build an AST and compile/interpret like any other language?

How should one handle connections to the database? TCP? IPC? How do big-name databases do it?

How is the data is these fast relational databases stored? I know SQLite uses a flat file -- seems like a synchronization nightmare.

Obviously, I don't expect anyone to just explain all of relational database theory to me -- but I've been looking around and I'm really at a loss for references to start learning about this stuff.

To answer the inevitable "why don't you just use MySQL?": (a) because I'm curious and (b) maybe someday I'll want to design my own database with a specific use in mind.

EDIT: I guess I should've made this more clear. I realize this is a broad topic. I am not looking for someone to say "oh, you design a database by..." If this is a topic covered in a large number of books, what are those books? If this is covered well in a P.h.D. thesis you know of, what is that thesis? I am very aware that this is a broad topic -- I'm not asking for a specific answer for a broad question, I'm asking for specific resources for a broad question. As always, thanks for all the help!

答:
Download a copy of SQLite and start going through the code.  That should give you a very decent grounding in the fundamental concepts of DBMS design.

The SQLite author has extensive notes on his website about how SQLite was designed, and the database engine is small enough that you should be able to wrap your mind around it.

http://www.sqlite.org/

SQLite is written in C.  If you prefer a more "modern" language to read the code, try the C# version of the SQLite engine here: http://code.google.com/p/csharp-sqlite/

OwnerDisplayName: Ryan Marcus


问:
Should one test for algorithmic complexity? If so, how?
Let's say I am implementing something simple like searching a sorted list/array. The function (in c#) would look similar to:

```<code>static int FindIndex(int[] sortedList, int i);
</code>```

I could implement and test this in terms of functionality, but for obvious reasons I would usually prefer a binary search over a linear search or something intentionally stupid.

So my question is: Should we attempt to write tests that guarantee performance in terms of algorithmic complexity and if so, how?

I have started making arguments on both sides of the "should you" part of this question, but I'd like to see what people say without my arguments to prompt them.

In terms of "how", that gets very interesting:) You could see parameterizing the comparison operator and having a test whose comparison operator counts comparisons or something like that. But just because you can doesn't mean you should...

Has anyone else considered this (probably)? Thanks.

答:
While I'm not sure if this tool will be particularly useful for unit tests, the paper "Empirical Computational Complexity" by Goldsmith, Aiken, and Wilkerson describes a method for instrumenting code and observing its dynamic behavior on a set of various inputs to empirically derive its asymptotic complexity.  The program described in the paper is open-source and is available here.

Hope this helps!

OwnerDisplayName: Tobias Brick

OwnerDisplayName: templatetypedef


答:
The main thing is try it with big data and see if it takes too long.

In my performance tuning experience, as in this example, what happens is if some algorithm is (for example) O(n^2) it may be just fine as long as the percent of time it takes never gets onto the radar.

However, when it is given a dataset of a size that might not be seen but once a year, the fraction of total time sucked up by that algorithm may become catastrophically dominant.

If you can make that happen in testing, that is a very good thing, because it's supremely easy to find the problem, just as if it were an actual infinite loop.

Title: Should one test for algorithmic complexity? If so, how?

Body:
Let's say I am implementing something simple like searching a sorted list/array. The function (in c#) would look similar to:

```<code>static int FindIndex(int[] sortedList, int i);
</code>```

I could implement and test this in terms of functionality, but for obvious reasons I would usually prefer a binary search over a linear search or something intentionally stupid.

So my question is: Should we attempt to write tests that guarantee performance in terms of algorithmic complexity and if so, how?

I have started making arguments on both sides of the "should you" part of this question, but I'd like to see what people say without my arguments to prompt them.

In terms of "how", that gets very interesting:) You could see parameterizing the comparison operator and having a test whose comparison operator counts comparisons or something like that. But just because you can doesn't mean you should...

Has anyone else considered this (probably)? Thanks.

OwnerDisplayName: Mike Dunlavey


答:
I do not think what you wanna do is Unit Testing.

AFAIK, unit testing is only to make sure the code does what it should do and it does not focus on performance.

From Wikipedia: Testing cannot be expected to catch every error in the program: it is impossible to evaluate every execution path in all but the most trivial programs. The same is true for unit testing. Additionally, unit testing by definition only tests the functionality of the units themselves. Therefore, it will not catch integration errors or broader system-level errors (such as functions performed across multiple units, or non-functional test areas such as performance). Unit testing should be done in conjunction with other software testing activities. Like all forms of software testing, unit tests can only show the presence of errors; they cannot show the absence of errors.

There are other kinds of tools and patterns to measure performance. One of that I can remember now is Acceptance testing focused on non functional requirements.

There are few others like  performance testing (which uses stress testing, load testing, etc).

You also could use some stress tools together with a build tool (ant, automated build studio) as part of your deployment steps (that is what I do).

So the short answer is no, you should not worry about that when unit testing a code.

OwnerDisplayName: Rafael Colucci


答:
Algorithmic complexity is a theoretical construct and as such it's best "tested" with a pencil and paper. It can't be usefully tested mechanically.

Absolute performance can be tested mechanically and can make useful unit tests. If performance matters, then you can specify a threshold: "this query should take no more than 50ms to run on 106 numbers, and no more than 60ms on 107 numbers." That you can build a unit test for.

The end user doesn't care whether your algorithm is linear or logarithmic; they care whether their UI still responds instantly even when they've got a year's worth of data in the app.

OwnerDisplayName: Crashworks


问:
Why is there still case sensitivity in some programming languages?
I don't see any use for case sensitivity in a programming language, apart from obfuscating code.

Why implement this in a programming language?

Update:

It looks like someone you know made a statement on this.

答:
In Java case sensitivity is NOT used to provide more options in code, but rather for a very clear and consistent semantic meaning. ClassesLookLikeThis. objectsLookLikeThis. methodsLookLikeThis(). STATIC_VARIABLES_LOOK_LIKE_THIS. Classes.WithInnerClassesLookLikeThis. It does NOT provide greater freedom: it allows you to pack some information concisely into what is an otherwise overly verbose language.

I think that in explicitly statically-typed languages with mucho compiler and IDE support, case-sensitivity is a great way to communicate information (e.g., Java). With languages like Ruby, case insensitivity would probably cause even MORE unexpected results, though I'd be open to trying case-insensitive Ruby.

I think that case sensitivity with a strict system does not obfuscate code but actually makes it clearer. Consider possible Java code:

```<code>      joe blah = new hUf();
</code>```

that's pretty clear, but what about:

```<code>      hUf.WTF();
</code>```

In Java as-it-is, you would automatically know what this is. In case-insensitive Java, it's ambiguous, so you'd need to resort to some other mechanism to differentiate classes from instances from packages from methods. And THAT mechanism would probably make you vomit with how ugly it is :)

Body:
In Java case sensitivity is NOT used to provide more options in code, but rather for a very clear and consistent semantic meaning. ClassesLookLikeThis. objectsLookLikeThis. methodsLookLikeThis(). STATIC_VARIABLES_LOOK_LIKE_THIS. Classes.WithInnerClassesLookLikeThis. It does NOT provide greater freedom: it allows you to pack some information concisely into what is an otherwise overly verbose language.

I think that in explicitly statically-typed languages with mucho compiler and IDE support, case-sensitivity is a great way to communicate information (e.g., Java). With languages like Ruby, case insensitivity would probably cause even MORE unexpected results, though I'd be open to trying case-insensitive Ruby.

I think that case sensitivity with a strict system does not obfuscate code but actually makes it clearer. Consider possible Java code:

      joe blah = new hUf();

that's pretty clear, but what about:

      hUf.WTF();

In Java as-it-is, you would automatically know what this is. In case-insensitive Java, it's ambiguous, so you'd need to resort to some other mechanism to differentiate classes from instances from packages from methods. And THAT mechanism would probably make you vomit with how ugly it is :)


问:
What is a "powerful" language?
I have often seen people fighting over that their favorite language is more "powerful" than others. When it comes to describing a programming language, I can understand what an object oriented language is or what a dynamic language is, but I still can't figure out what exactly a "powerful" language is. What are your thoughts?</p>

答:
I maybe biased because I'm a system programmer. I would think a programming language used for all of kernel, system, server and application programming, or support multiple programming paradigms, or both can be called "powerful".

C, C++, D are powerful, but obviously this is just my humble opinion.

Title: What is a "powerful" language?


答:
The right balance of brevity and flexibility.

Great question. Given that many languages are "Turing complete", we can put them all on equal grounds with regards to what they're theoretically capable of. But we don't do that because languages obviously differ from one another. And what is the difference?

The difference is the ability to say a lot of different things with very little. If we could jump right to the extremes, I could make a language that is the best language for automatically initializing a content management system using just one character, 'c'. But what would the point of that be? Sure, it's powerful in a sense of being very brief, but it's not flexible. What you want is a language that allows you to say many different complex things without being too verbose. Without being like assembly, capable of everything under the sun, infinitely flexible but extremely verbose.

A powerful language is a language that allows you to say many different things with the least amount of length possible.

Title: What is a "powerful" language?

Body: I have often seen people fighting over that their favorite language is more "powerful" than others. When it comes to describing a programming language, I can understand what an object oriented language is or what a dynamic language is, but I still can't figure out what exactly a "powerful" language is. What are your thoughts?</p>


答:
Get married

A partner yelling "Dinner is ready." or "Get to bed now, or you'll be grumpy in the morning" will kick your right out of that zone.

Seriously. The only reason I get to bed on time is because my wife hates me in the morning after late nights of programming.

There's other benefits too.

Title: What to do when the programming activity becomes a problem?

Body:
I once saw a program (can't remember which) where it talked about people "experiencing flow" when they are doing something they are passionate about. When "in flow", they tend to lose track of time and surrounding, concentrating only on their activity at hand.

This happens a lot for me when I program; most particularly when I face a problem. I refuse to give up until it's solved. This usually leads to hours just rushing by and I forget to eat lunch, dinner gets pushed into far into the evening, and when I finally look at the clock, it's way into the wee-hours of the night and I will only get a few hours of sleep before having to rise early in the morning. (This is not to say that I'm in flow only when facing a problem - but I find it particularly hard to stop programming and step back when there's something I can't solve immediately.)

I love programming, but I hate it when it disrupts my normal routines (most importantly eating and sleeping patterns). And sitting still for so many hours, staring a screen, is not healthy.

Please, any ideas on how I can get my rampant programming activity under control?


答:
Once you hit Turing complete (and it's easy for a language to do this), "power" doesn't mean much, in the sense that anything you can say in one Turing complete language you can say in another. Mark Canlas' answer nails it: brevity and flexibility makes the difference.

Having said that, Matthias Felleisen's paper On the Expressive Power of Programming Languages makes for interesting reading. In it he attempts to formalise the notion of expressiveness in languages.

Title: What is a "powerful" language?


问:
How much documentation is enough?
How much technical (for future developers) documentation is enough? Is there a ratio between hours coding and hours documenting that's appropriate?

Papadimoulis argues that you should

produce the least amount of documentation needed to facilitate the most understanding,

Is that a good guideline, or are there specific things I should be creating?

答:
Enough to make you stop second guessing yourself.

If at any time during your work you're like "hmm maybe I should document this", go ahead and do it. Then, if you've written some documentation and you're like "maybe I should explain this more", go ahead and do that.

Rinse-repeat until that feeling goes away.

Title: How much documentation is enough?


问:
Best practices working with frameworks that invent their own types [more of a C/C++ question]
Is there a correct way to handle APIs that invent their own types?

For example, WinAPI, QT, Boost.

Many frameworks have their own integer and boolean types, along with more complicated data-types.

So, is it better to use native C/C++ type like bool or alternatives like QBool/BOOL/etc., and native container types like std::map/std::set/std::vector vs reinvented ones like QList/boost::something/ATL::map/etc.

And how do those choices respond to cross platform portability.

TL;DR

Which one QBool IsInteresting(const QString &str) vs bool IsInteresting(const std::string &str)?

答:
Frameworks that have their own replacements for standard library types usually do so because they are also compatible with platforms that do not have a good standard library implementation (such as phones and other embedded systems).

Boost is a special case - it is often practically considered part of the standard library, and several of the highly-used boost libraries were considered for C++0x (some made it, e.g. shared_ptr).  Where possible and useful boost is compatible with the C++ standard (library) types.

If you are going to use the same framework for all your product releases and it covers the majority of your needed functionality, it is probably a good idea to save yourself the headache and use the framework's types.  That way you don't have to convert back and forth all the time.

If you are going to use multiple GUI frameworks (e.g.if you are targeting multiple platforms not all supported) or if you are using multiple third-party libraries with incompatible types things get more complicated, and you'll have to put some thought into whichever solution has the lowest total impact for your particular project.


问:
Should organizations penalize developers for the amount of defect reports filed against code they worked on?
Should organizations penalize developers for defect reports filed against their work products?

I was having a discussion with my friend where he asks if a manager taking the number of defects filed against a developer is justified. My take is no, because developers can introduce defects, but by holding those against him can cause unnecessary negative feelings in the developer's mind.

What are the problems with penalizing developers based on defects that they inject? Does your organization penalize developers for creating defects in work products?

答:
What is the motivation for penalizing developers for their defect rates?

Surely the goal is to try and measure the quality of the code being written by the developer.

The problem is, quality is a bit amorphous: it is really hard to measure. In fact, you can't measure it directly, you have to try and approximate it by measuring other things.

Also, picking a single KPI - such as # defects - results in gaming of the system. If you suggest penalising each developer $10 per defect, how long do you think it would be before one of the developers makes a deal with a tester ... I'll pay you $5 for each defect you tell me about that doesn't get logged.


答: Always use Standard containers and types where possible. Reinvented containers and types only exist because the libraries in question pre-date Standardisation.</p>

Title: Best practices working with frameworks that invent their own types [more of a C/C++ question]

Body:
Is there a correct way to handle APIs that invent their own types?

For example, WinAPI, QT, Boost.

Many frameworks have their own integer and boolean types, along with more complicated data-types.

So, is it better to use native C/C++ type like bool or alternatives like QBool/BOOL/etc., and native container types like std::map/std::set/std::vector vs reinvented ones like QList/boost::something/ATL::map/etc.

And how do those choices respond to cross platform portability.

TL;DR

Which one QBool IsInteresting(const QString &str) vs bool IsInteresting(const std::string &str)?


答:
Let them repare all bugs related to their code, forward them the complaints from the testing department, and they should already learn that less bugs is better for them.

And when everything goes alright, and no bug reports are coming in, a clap on the back as reward and a few kind words should do the rest.


答:
There are a few definitions of power beyond Turing completeness.  Mark's cited what I tend to think of as "the Paul Graham definition."  It's a pretty good definition, with one serious flaw: it's wrong.  It's theoretically a very good definition of language power, but you know what they say about the difference between theory and practice...

If everyone was capable of writing perfect code, not only perfectly bug-free but also perfectly future-proof, consistently, then the Paul Graham definition would be correct.  But that's obviously not the case.  In the real world, the majority of time and effort that goes into software engineering is not taken up by initial creation of the product, but by maintenance afterwards.  Depending on which statistics you listen to, (and it probably varies quite a bit from project to project,) maintenance can account for anywhere from 60% to 90% of the total effort that goes into a program.

Maintenance is often performed by people other than the person who wrote the code initially, and frequently months or even years after the initial writing of the code, which means that even to the original coder it may as well be "other people's code" by that point.  If you want to be productive during maintenance, you need to be able to quickly ascertain the original intent of the code by reading it.

Therefore, a more powerful language is one that makes code easier to read quickly, not one that makes code easier to write quickly.  There tends to be a fair amount of overlap between the two, but the concepts are often at cross purposes as well, since terse syntax will often omit details that a compiler/interpreter is able to infer a lot more easily than a maintenance programmer.

EDIT: There's another important point in describing a language's power: the range of concepts that you're able to express, and how easily you can hit both ends of it.  Paul Graham likes to evaluate this one on how high a level of abstraction you can reach, but that's only half of it.  Any language that imposes a lower limit of abstraction, beneath which you can't go when necessary, is crippled because the details that are being abstracted away are there for a reason.  This is the difference between an easily-readable toy language like COBOL and an easily-readable powerful language: COBOL has no pointers and no access to inline assembly, where you can express any computation, even ones that COBOL is not well-suited to.

COBOL is also not particularly good at hitting the high end of the abstraction spectrum either.  According to Wikipedia it has "no user-defined types, and no user-defined functions," which makes it very difficult to create algorithms and data structures.

Title: What is a "powerful" language?


问:
Tools and/or methods for regular Code review of Remote development team
We are outsourcing a development to a small team of offshore developers.  Our in house process for code review is manual, paper based, based on a waterfall model requiring "big bang" delivery. It cannot be changed. Past experience is these devs are proficient and reliable, however come time to deliver, the overhead of reviews becomes a difficult burden for everyone involved and issues are being found too late.

We use CVS for our source repository. They take a copy of the CVS repo, receiving regular updates to the most recent code base, and use GIT locally to manage their changes. When ready to deliver, send us a tarball of an upto date  CVS clone with their work merged into it. We then code review and check it in.

We are looking for a tool chain to support a code review process where we can do regular, light weight reviews outside our inhouse process, so that when the inhouse process kicks in, we can do it "go fast" mode as we have already reviewed most of the code.

Limitations are that there systems and ours are disconnected. We use sneaker net to transfer files between us. The best we can do is have one machine in house that VPN's into their system.

The source is commercial code and cannot be placed anywhere where it is exposed to the internet.

One option they have suggested is Gerrit - which they plan to use on their site. Is there a way to share and synchronise the gerrit database between sites, given the limitation of the sneaker net?
Does anyone else have a solution to tis kind of problem?

答:
yuk, waterfall -> cvs -> git... sounds like its a mess waiting to happen but...

Your best approach for code reviews IMHO is Redmine with the code review plugin. You create a project in redmine and tell it the repository where the code lives, then you can view the code using the built-in repo browser.

The benefit here is that just looking at the repository linked to the project shows you the changesets and the diffs between changes. With the code review plugin, you can then easily mark sections of code with comments. This generates a ticket (ie a bug) in the project.

This is fast and simple, you end up with a set of tickets that can be assigned and tracked. It doesn't require sharing your source code as it hooks directly to your local CVS repo. However, the tickets might be difficult to view if the redmine system is not available to the outsource team, but you can export them to excel or pdfs and email.


问:
Project problems from a Java beginner
A week ago I asked the question; First big project, how to get started. Make menus, save to harddrive etc. I tried to do everything without doing a GUI with Swing but I realized that for every view I wanted to present to the user I had to make a new class. Right now I have 3 menu classes (the mainMenu, computerCategoryMenu,laptopCategoryMenu) I stopped because I would need to make another 6 menu classes and then another 6 if the user registered and another 6 for the administrator of the site. It doesn't look right to me. Furthermore everything looks too static for me. I don't know how to make the administrator add or delete products.

Should I store all my products in a hashmap and then get them to show in different menus? Do you think that doing a GUI with Swing will make things much easier?

答:
By all means, yes, for this type of application you should write a GUI.
From your problem description, it seems that you should have only one menu called "Products" with two menu entries, one for browsing the list of products and the other for adding a new product. Now, you don't know to duplicate menus for each "user role" in your application. You should enable/disable your menu, menu items and windows and buttons, and all "action" graphical elements depending on the role(s) of the user. For example only if he's an administrator would you enable the action consisting in "adding/modifying/removing" products. However, all users are able to browse the list of products.
But, really, this is the very tip of your iceberg here...

Regardless of your GUI problems I suspect you have another major problem in that you don't have a database. You wrote about storing your products in a HashMap, that's why I am being suspicious. Now you could get away with just a HashMap if you serialize/deserialize it somewhere in a file but that's just a (very) quick and dirty solution for you to concentrate on coding your GUI.

Also, an even bigger problem... Since you are talking about different user roles, I also suspect that different people should be using the application at the same time. If that is the case you will need to have a database to connect to and store/retrieve user information. You will not be able to achieve this with simple hashmaps.
Take a look at how a multi-tiered application should be done theoretically.
Even very simple and quickly written applications take this approach.

Finally, check out the following link where they given an example of an implementation of the MVC architecture, using Java SE: http://www.oracle.com/technetwork/articles/javase/mvc-136693.html. All the source code is available for you to quickly understand how it works.

ps: you can do all of that in a desktop application, but also in a web application... Maybe you first have another decision to make here ?

Title: Project problems from a Java beginner


答:
I find this problem odd because of the strange relationship you have with your offshore development organization.

My experiences in working with an offshore development team SUCCESSFULLY is that they integrate 100% into your existing project team, and this includes:

Tools - The offshore team should work in the same source control environment as you.  Going to Git is a much better choice mind you than CVS however they should better integrate into YOUR source control.  You are their client after all.

Environments - Why are YOU VPN'ing into THEIR network?  It should be the other way around and they should do this to remotely check code into YOUR source control.  This gives the added benefit of getting rid of the manual clutter you are suffering from now.

Communication - This one is hard and doesn't have an easy answer.  The timezone differences are always a huge hurdle.

So in short, the only answer to your pain is the very political process that prevents them from fully integrating into YOUR development team that you identified as "cannot be changed".  Any suggestions to improve this messed up situation will be like giving Tylenol for a broken leg.  It won't get fixed until these supposed impossible hurdles are overcome.

Title: Tools and/or methods for regular Code review of Remote development team

Body:
We are outsourcing a development to a small team of offshore developers.  Our in house process for code review is manual, paper based, based on a waterfall model requiring "big bang" delivery. It cannot be changed. Past experience is these devs are proficient and reliable, however come time to deliver, the overhead of reviews becomes a difficult burden for everyone involved and issues are being found too late.

We use CVS for our source repository. They take a copy of the CVS repo, receiving regular updates to the most recent code base, and use GIT locally to manage their changes. When ready to deliver, send us a tarball of an upto date  CVS clone with their work merged into it. We then code review and check it in.

We are looking for a tool chain to support a code review process where we can do regular, light weight reviews outside our inhouse process, so that when the inhouse process kicks in, we can do it "go fast" mode as we have already reviewed most of the code.

Limitations are that there systems and ours are disconnected. We use sneaker net to transfer files between us. The best we can do is have one machine in house that VPN's into their system.

The source is commercial code and cannot be placed anywhere where it is exposed to the internet.

One option they have suggested is Gerrit - which they plan to use on their site. Is there a way to share and synchronise the gerrit database between sites, given the limitation of the sneaker net?
Does anyone else have a solution to tis kind of problem?


问:
How to flag a class as under development in Java
I'm working on a internship project, but I have to leave before I can finish up everything.

I have 1 class that is not stable enough for production use. I want to mark/flag this class so that other people will not accidentally use it in production. I have already put the notice in Javadoc, but that doesn't seem enough. Some compiler error or warning would be better.

The code is organized like this:

```<code>[Package] | company.foo.bar.myproject
          |-- Class1.java
          |-- Class2.java
          |-- Class3.java <--(not stable)
</code>```

If there was a single factory class that calls those classes in public methods, I could have set the method to class3 as private. However the API is NOT exposed that way. Users will directly use those class, e.g. new Class1();, but I can't make a top-level class private. What's the best practice to deal with this situation?

答:
You could introduce compile time annotation processing but this would enforce all members of the team to adjust their compile process.

However I find the whole process a little confusing. An unstable API should be clearly separated by creating a branch in your version control system. If it really has to be in the rest of the codebase, has been documented as unstable and nevertheless get's used the problem is not really technical but lies within the organisation and the communication. Yes, you could introduce technical verifications (like annotation processing) but that wouldn't solve the problem - just move it to another level.

So my recommendation is: If you cannot separate the code base by putting it in different branches then talk to people and explain to them why they mustn't use the API.


答:
Why would anyone WANT case insensitivity? In what scenario is it useful to be able to refer to a single variable as VARIABLE in one place, Variable in another, and variable in a third? Case insensitivity is exasperating. I’d much rather get a compiler error when I accidentally type VAriable instead of Variable rather than let case-typos like that slip into my code.

In conclusion, many programming languages have case sensitivity not just for historical/inertial reasons but because case insensitivity is a Bad Idea.

Title: Why is there still case sensitivity in some programming languages?

Body:
I don't see any use for case sensitivity in a programming language, apart from obfuscating code.

Why implement this in a programming language?

Update:

It looks like someone you know made a statement on this.


问:
Correlation between two curves
I am trying to solve a mathematical problem in two different ways and output is a curve in both the cases. I want to compare these output curves for similarity in python. Is there any function or framework which provides this functionality?

Thanks.

答:
The classic Pearson's correlation coefficient is perhaps the most popular measure of curve similarity. SciPy's pearsonr function gives you that.

Correlation coefficient measures shape similarity and is (somewhat, not completely) insensitive to bias and scaling.

Another way to measure similarity is to directly measure the average difference of the curves. You could use RMS difference. No libraries needed, simply something like this:

```<code># rms difference of vectors a and b:
rmsdiff = 0
for (x, y) in zip(a, b):
    rmsdiff += (x - y) ** 2  # NOTE: overflow danger if the vectors are long!
rmsdiff = math.sqrt(rmsdiff / min(len(a), len(b))
</code>```

RMS difference accentuates large deviations, even if they're local, and masks small deviations, even if they're global. For example, vectors

```<code>[1 2 3 4 5] and [2 1 4 3 6]
</code>```

are more similar in RMS sense than

```<code>[1 2 3 4 5] and [1 2 3 4 2]
</code>```

There's no one and only "right" measure of similarity. Different methods accentuate different (dis)similarities.

Title: Correlation between two curves

Body:
The classic Pearson's correlation coefficient is perhaps the most popular measure of curve similarity. SciPy's pearsonr function gives you that.

Correlation coefficient measures shape similarity and is (somewhat, not completely) insensitive to bias and scaling.

Another way to measure similarity is to directly measure the average difference of the curves. You could use RMS difference. No libraries needed, simply something like this:

# rms difference of vectors a and b:
rmsdiff = 0
for (x, y) in zip(a, b):
    rmsdiff += (x - y) ** 2  # NOTE: overflow danger if the vectors are long!
rmsdiff = math.sqrt(rmsdiff / min(len(a), len(b))

RMS difference accentuates large deviations, even if they're local, and masks small deviations, even if they're global. For example, vectors

[1 2 3 4 5] and [2 1 4 3 6]

are more similar in RMS sense than

[1 2 3 4 5] and [1 2 3 4 2]

There's no one and only "right" measure of similarity. Different methods accentuate different (dis)similarities.


问:
Naming UI components in web based editor
I'm developing a web-based source code editor. I'm developing everything(tabs, context menu etc) out of HTML elements. How do I come up with names for UI controls? Is there a book or guide or project from which I can learn how to name things?</p>

答:
I agree with most of what greengit says, but like to add the following. The bottom line is indeed to ensure readability. That's why I prefer not to use abbreviations like btn, dlg, etc. I've seen this lead to unreadable abbreviations (i.e. what's icb, it was a custom control, but definitely unreadable).

Also, I like to put the function of the control first.

So: SignupButton, AddLink, RegistrationDialog, etc.

Do choose something you feel comfortable with, go for readability, and stick to it. Consistency also increases readability.


答: My former coworker told me a story of a place where this practice was actually enforced: developers were penalized for each bug found in their code, and QA was rewarded for each bug they discovered. The result was that developers simply stopped developing new code because that was the only way to protect themselves from penalties.</p>


问:
Programming late at night problem
I recently found out that programming late at night causes sleeping problems, so what are the best hours for 'after-job' programming? Maybe there is some time interval that should be set after finishing programming and going to bed, or some activity involved?</p>

答: Any activity that promotes relaxation can be used to bridge from working to ready to sleep mode. I usually watch some TV, but whatever floats your boat.</p>

Title: Programming late at night problem


答:
I tend to find that programming late will keep me from sleeping.  Anything that I find stimulating will tend to prevent my mind from winding down, I'll be laying in bed visualizing what I want to do with code or figuring out how things will work.

I also find that if I push myself too long, my code needs revision the next morning.

I find I need to put things down at least an hour before I intend to head to bed.  I tend to watch reruns (M*A*S*H in particular) that I've seen a million times and won't try to stay up to finish :)

That's me... hope you figure out what works for you.

Title: Programming late at night problem

Body: I recently found out that programming late at night causes sleeping problems, so what are the best hours for 'after-job' programming? Maybe there is some time interval that should be set after finishing programming and going to bed, or some activity involved?</p>


答: Listen to your body. It knows when you should take rest and when you should be coding.</p>

Title: Programming late at night problem


答:
For me, right before dinner.

Hunger provides pressure and helps me code faster and more efficiently (think of it as a project milestone deadline). It also forces me to stop well before midnight so that it doesn't negatively impact my health.

Title: Programming late at night problem


答:
I'm still somewhat struggling with this issue myself, but here are some of my findings:

Late-night coding is not the cause, it's a symptom

Some possible causes (YMMV):

Caffeine

Irregular times of meals

For me, lowering caffeine intake helped with sleeping when I planned, and eating regularly helped with waking up when I want (this later one had especially dramatic effect on me).

I also experienced a "critical point" in exhaustion, meaning that if I stay up too late, my body will prevent me from sleeping for 2-3 additional hours.

Title: Programming late at night problem


答:
No.  It sounds trying to treat a symptom, not the root problem.  Instead of focusing on how many bugs there are in a piece of code and who introduced them, why not focus on developing a system that helps eliminate bugs in the first place?

Tools like Unit Testing, Integration Testing, Test Driven Development, Static Code Analysis, Design Reviews, and Code Reviews can often catch a fair number of bugs before they get into the code base.  Continuous Integration also help identify issues early rather then later.

BTW, the logical follow on to the OP question:  If I inherit a piece of code filled with bugs, should I be penalized for all of the remaining bugs if I fix one?  By the original proposition, since I worked on the code, I am now responsible for the bugs.


答:
There seems to be a lot of disagreement over what constitutes linguistic power. Is it terseness, legibility, adaptability, or just plain Turing completeness? I think that all of these factors come into play, so perhaps the best way to look at it is in terms of stat points. Yes, I'm talking pen-and-paper RPG, here.

The idea is that each language has (roughly) the same number of "points", which can be distributed arbitrarily across a number of categories. For the purposes of discussion, say the only factors are brevity, legibility, and flexibility. A language then might be extremely terse and flexible, but consequently very difficult to read; or very legible and flexible, but extremely verbose.

(Arguably, the number of points that a language has to distribute is defined by the skill of the designer and implementor, but let's pretend that all language designers are equally good at what they do.)

When a language designer decides to increase the strength of a language in one category, they logically take away a fraction of that potential strength from every other category. This is why it's so often said that programming language design is all about trade-offs. From this point of view, the overall power of a language is still not definable, and we have to revert to the tried and true method of categorising languages based on their relative strengths. Not satisfying? Too bad.

You can argue two ways: that a powerful language is one with a relatively even distribution of points (jack of all trades, master of none), or with as many points as possible in one area without leaving others unattended (specialist). There is no such thing as a "renaissance man" language, with perfect mastery in numerous fields. And if that's your definition of the most powerful possible language, then you're just plain out of luck.

For further reading, this article (coincidentally also by Paul Graham, who seems to have mixed opinions) touches on the idea that, difficult though it may be to determine how, programming languages do indeed vary in power. He argues rather persuasively that it's very easy to see how a language is less powerful than your preferred one—it's missing feature X—but very difficult to see how a genuinely more powerful language is in fact so—it's basically equivalent to language X, but with a bunch of other stuff thrown in. I leave you with a quote from that paper:

By induction, the only programmers in a position to see all the differences in power between the various languages are those who understand the most powerful one. (This is probably what Eric Raymond meant about Lisp making you a better programmer.) You can't trust the opinions of the others, because of the Blub paradox: they're satisfied with whatever language they happen to use, because it dictates the way they think about programs.

Title: What is a "powerful" language?


答:
The light from computer screens is typically very good at keeping you awake.  For this reason, you should have a gap between computer use (of any kind) and trying to sleep, and you should be wary of staying up past your bedtime to "just do a little bit more". Otherwise, you may end up lying awake at night, unable to drop off.  The duration should be reached by experimentation, as everyone is different, and the kinds of computer usage vary.

You may find some success using f.lux to allow you to keep coding right up until bedtime.

Title: Programming late at night problem


答:
so what are the best hours for 'after-job' programming?

I think the best time is in the early morning, at the day break, right after waking up and when your mind is fresh... It doesn't cause any sleeping problems either; it encourages sleeping early... Remember:

```<code>Early to bed, early to rise, makes man healthy, wealthy and wise...
</code>```

Title: Programming late at night problem

Body:
so what are the best hours for 'after-job' programming?

I think the best time is in the early morning, at the day break, right after waking up and when your mind is fresh... It doesn't cause any sleeping problems either; it encourages sleeping early... Remember:

Early to bed, early to rise, makes man healthy, wealthy and wise...


答:
Many years ago I was coding something and checked the watch. It was around 7pm and I thought "ok, two more lines and then eat dinner". After those two lines (?) it was 2am...

Every now and then I find myself sleeping and thinking about code, what to do with, how to fix a bug or wake up in the morning and having/making plans for coding later on.

IMHO, it's all related to how much you identify yourself - not literally - with your profession/hobby and how much you like it. If the above happens it means that you are doing something that you like. You don't need to force yourself to think about coding. It comes naturally. In general that's a good thing.

To keep this in non-excessive limits I made some rules for myself:

in the office I have an Outlook-alarm set up telling me when to go home

at home I don't have an alarm, but whenever the time roughly is in a timeframe where I usually eat, I stop and eat.

to cool off before bed I either watch TV, play some game, read something, ... Basically I do something that makes my brain think of something else. I usually end up being tired.

You can also try to set up a daily routine that you do before going to bed to draw your brain's attention away from the code, like writing mails, reading newspapers, doing the dishes, separating laundry, going for a walk, go to supermarket (if it is open that late), call or talk to somebody, ...

The time you need really depends on yourself. For some it takes a few minutes, some need an hour or more.

In other words it's important to get your sleeping pattern right. If you can't come up with one, don't code for a week or two and set your focus onto something else.

THEN - and only then - you can think about your productive hours. Why? Because then you have slept properly and wake up fresh in the morning. Otherwise you end up with relaxing from your more or less bad sleep and thus run into another daily time pattern of your organism.

Usually your body tells you what's good and what's bad. If it conflicts with other people's habits, well, it's nobody's fault, it's just the way it is. We are all different after all :).

Early bird vs. night owl. There's no right or wrong on this question. What works for others doesn't necessarily work for you. So whatever you read here can only be suggestions.

Title: Programming late at night problem


问:
Using Backbone.js with ASP.Net MVC
I'm currently looking into the advantages of using Backbone.js, but I'll be using ASP.Net MVC as the main bulk of the site.  My question is, is it worth blending the 2 together or am I making a rod for my own back?  Should I just use an ASP.Net Web Forms site instead?</p>

答:
Should I just use an ASP.Net Web Forms site instead?

Not unless you have strict deadlines or other limitations. It's always worthwhile investing time and resources in better technologies like ASP.NET MVC.

As for using backbone.js it will work with any REST API. You can expose a REST API with ASP.NET MVC (and it's a lot easier to do then using ASP.NET winforms)

As long as you expose your data as a service backbone can work with it nicely. Alternatively you can use ASP.NET MVC on it's own and not make use of the client-side MVC backbone offers.

is it worth blending the 2 together or am I making a rod for my own back?

As mentioned if you just use ASP.NET MVC to expose data as an REST API then this is fine. If you use ASP.NET MVC to serve an entire website (including server-side views) then you'll have a lot of code duplication.

However with modern ajax and JavaScript driven websites you will have this code duplication anyway. You might as well use backbone or not use any client-side JavaScript / ajax code.

If your writing a heavy client based website with lots of interactive JavaScript based ui you might aswell use these libraries to structure and organise your code

However if your using backbone.js I would recommend you couple it with node.js to minimize code duplication or couchapp to remove the server-side stack. You don't really need .NET if your using backbone.

Title: Using Backbone.js with ASP.Net MVC


问:
What does Google or Microsoft get by hosting JS files on their Content Delivery Networks (CDN)?
As you know Google, Microsoft and jQuery.com offer JS files on their CDN. To do this, they must need to operate significant servers which must come at a cost to them. Why do they do this and what do they get from it?</p>

答:
Goodwill

Training ease for their products (tutorials don't fail
because of misplaced file)

Net traffic analysis


答: My guess is to foster goodwill among developers, so that in the back of your mind you're more willing to use one of their platforms or tools to develop in the future. Since Google already /has/ an enormous scalable network infrastructure, it probably doesn't cost them a lot anyways.</p>

Title: What does Google or Microsoft get by hosting JS files on their Content Delivery Networks (CDN)?

Body: As you know Google, Microsoft and jQuery.com offer JS files on their CDN. To do this, they must need to operate significant servers which must come at a cost to them. Why do they do this and what do they get from it?</p>


答: one small advantage of this is, that they have an overwiew on how much the Softare is used, and the could track users (Google eg can see users on other websites even if they don't have Google Analytics or Advertising, and you know: knowing the user gets you more Money (for personalized Ads ) ;-)).</p>


答: They do it because they perceive a business value in doing it. To know what specific business value, you'll have to ask them each individually. </p>