问:
I'm a manager. How can I improve work relationships and communication with programmers?
A little background first. I'm a project manager at medium-sized company. I started as a CS major and had a little exposure to programming, but after a few months I knew it's not my path, so I switched over to management. That proved to be a good decision, and after graduating I've worked in software management at various companies (for 5 years now).

Recently, we had a very painful project. It was the worst of the worst, with many mistakes both on our side and on the customers side and just barely ending it without losses. It has led to many frustrating situations, one of which escalated to the point where one of our senior developers left company after a vocal argument with us (the management). This was a red flag for me: I did something terribly wrong. (for the record, the argument was about several mistaken time estimates)

I searched many places for answers and a friend pointed me to this site. There are many questions here about frustrations with management. I can understand that the general bad experiences lead to a general reluctance against "those guys in the suits".

I'm that guy in the suit. It may not look like it, but all I want is a successful project, and with limited resources it takes painful decisions. That's my job. One of the things the aforementioned senior developer complained about was work equipment. Frankly, I had no idea that the computers we had were not suited for working. After this, I asked many programmers and the general consensus was that we need better machines. I fixed that since then, but there was obviously a huge communication gap between me and the programmers. Some of the most brilliant developers are the most shy and silent people. I know that, and it was never a problem during an interview. People are different, and have strengths at different areas.

The case of the underpowered PCs is just one of the many that led me to thinking that there is a communication issue. How can I improve communication with programmers without being intimidating and repetitive?

What I'm hoping is that people don't complain about good things. If you love your workplace and love (or at least like :)) your manager, please tell me about them. What are they doing right? Similarly, if you hate it, please describe in detail why. I'm looking for answers about improving communication because I think that is my problem, but I might be wrong.

答:
Read a couple great novels which give insight into the perspectives of the technical workforce:

Hackers, Steven Levy - http://en.wikipedia.org/wiki/Steven_Levy

Microserfs, Douglas Coupland - http://en.wikipedia.org/wiki/Douglas_Coupland

Cathedral and the Bazaar, Eric Raymond - http://en.wikipedia.org/wiki/Cathedral_and_the_Bazaar

These are as important as any typical memoir on management (Drucker et al).


问:
When should you rewrite?

Possible Duplicate:

  When is a BIG Rewrite the answer?

In Joel Spolsky's famous (or infamous) article Thins You Should Never Do, Part I, he makes the case that doing a rewrite is always a wrong move because:

It automatically puts you behind (your competitors/schedule/etc.)

The code probably isn't as bad as the programmers believe (anything someone else wrote is always a mess, although some are bigger messes than others - and even then)

It's probably easier/quicker/cheaper to fix what's truly wrong with it than to rewrite from scratch.

In rewriting from scratch, you are probably going to re-introduce bugs that were fixed in previous versions the original code.

Instead, he recommends fixing what's wrong with the code.

I assume this is a good summary of his post, and I'll postulate that it is generally true.

I'm trying to collect a set of rules/guideline for my team, and one of them (based on Joel's article) is

```<code>We don’t re-write ... ever!
- But we can refactor large portions of the code.
  (this exception takes care of ugly/problematic code issues)
</code>```

One question that has cropped up is "What about when technology changes and you can no longer get support for older versions?". This is what I think of as the Sisyphean Upgrade path.

E.g., I recall when Oracle moved from SQL*Forms 2.x/3.x through to Forms 6i and beyond, Forms that were originality developed in the old .inp format were no longer supported with the current version of Oracle and Oracle Forms.

So you had a choice of sticking with an unsupported database with unsupported tools or rewriting the Forms from scratch (or converted with 3rd party tools and then gone over with a fine toothed comb). Which I will call porting, particularly when you are doing a faithful line by line/function by function translation into the new tech and not adding any functionality.

The rule then became:

```<code>We don’t re-write ... ever!
- But we can refactor large portions of the code.
- And we can port the code to a new platform when we *truly* have no other
  choice.
</code>```

(and by truly I mean, you can't even buy your way out of the problem for 2x the cost of porting it)

Are there any other exceptions that I've missed?

答:
I've read his article, and 1,2, and 4 are good points, but 3 is a circular argument.  Also, his code examples aren't even close to the worst code I've seen.  Surely, at some point, there must be code worth rewriting from scratch?  It's one thing to say never do it, but it would be more helpful to try to come up with a way to reasonably decide where to draw the line.

What if someone wants to upgrade an obsolete software stack that uses files instead of a database, is written a private language with a buggy custom compiler into COBOL, has no comments, no tests of any kind, and uses nothing but GOTO for flow of control and global variables for state, and is an entire enterprise application in one layer with everything dependent on everything else (but the users love it)?  I'm making this up, but in that situation, would it truly be cheaper to fix than to rewrite?

I think point number 3, is it cheaper to start over then to fix up (including any porting), is the key point.  In your case, if a line by line port really wouldn't work maybe you could admit your basically rewriting and plan accordingly.

ContentLicense: CC BY-SA 3.0

Title: When should you rewrite?


答:
if your design turned into unmaintainable spaghetti (common issue with single programmer/small code-base projects) and you're still early in the project (or the part affected is small enough) it's better to take out the garbage and restart

but that's pretty much the only reason you should ever rewrite

and when you start rewriting make a clear plan on what the new design is going to be and STICK TO IT, you should already have an idea of what is needed and where it went wrong the first time and create a design from that hindsight (keep old bug reports and recreate the circumstances with the new project coughunittestscough to fix respawning bugs)

if you want to recreate an existing prior project as the next major version keep it as a side project and keep the main project active and supported for a backup when the rewrite fails and only ship the rewrite when it matches the requirements that the old one reached or throw it out when it fails; Joel's article mentioned M$ tried to rewrite word but it failed but they kept the old codebase active so the were fine besides lost dev time.

Title: When should you rewrite?

Body:
Possible Duplicate:

  When is a BIG Rewrite the answer?

In Joel Spolsky's famous (or infamous) article Thins You Should Never Do, Part I, he makes the case that doing a rewrite is always a wrong move because:

It automatically puts you behind (your competitors/schedule/etc.)

The code probably isn't as bad as the programmers believe (anything someone else wrote is always a mess, although some are bigger messes than others - and even then)

It's probably easier/quicker/cheaper to fix what's truly wrong with it than to rewrite from scratch.

In rewriting from scratch, you are probably going to re-introduce bugs that were fixed in previous versions the original code.

Instead, he recommends fixing what's wrong with the code.

I assume this is a good summary of his post, and I'll postulate that it is generally true.

I'm trying to collect a set of rules/guideline for my team, and one of them (based on Joel's article) is

```<code>We don’t re-write ... ever!
- But we can refactor large portions of the code.
  (this exception takes care of ugly/problematic code issues)
</code>```

One question that has cropped up is "What about when technology changes and you can no longer get support for older versions?". This is what I think of as the Sisyphean Upgrade path.

E.g., I recall when Oracle moved from SQL*Forms 2.x/3.x through to Forms 6i and beyond, Forms that were originality developed in the old .inp format were no longer supported with the current version of Oracle and Oracle Forms.

So you had a choice of sticking with an unsupported database with unsupported tools or rewriting the Forms from scratch (or converted with 3rd party tools and then gone over with a fine toothed comb). Which I will call porting, particularly when you are doing a faithful line by line/function by function translation into the new tech and not adding any functionality.

The rule then became:

```<code>We don’t re-write ... ever!
- But we can refactor large portions of the code.
- And we can port the code to a new platform when we *truly* have no other
  choice.
</code>```

(and by truly I mean, you can't even buy your way out of the problem for 2x the cost of porting it)

Are there any other exceptions that I've missed?


答:
As with any hard and fast claim that Joel Spolsky spews out...

You are not supposed to take it literally!

He likes to paint a dramatic argument for a common problem and common situation, but like anything in the real world there is always that gray area, no matter how small.

He intends to get people thinking and to create an aversion to being "re-write happy" which I completely agree with.  95% of re-write situations don't warrant it but of course you will have that exceptional case where "Our client is moving to Linux servers and they won't install Mono.  We should rewrite this .NET app in some other technology."

The fact that what he said worried you enough to post a question means that he does his job well.  He got you thinking and that is his ultimate goal I believe.

Title: When should you rewrite?


问:
Is it time to do away with 'front-end' and 'back-end' as tech jargon?
It seems that the primary usage of these terms is either:

mutual mystification of contractors and/or clients who don't know what they are talking about or how to talk about it,

the innocent and ignorant (see this question) , or

laziness to avoid having to say user-interface/user-facing or business logic/database/infrastructure.

Granted, you don't always want to explain to the boardroom what the aforementioned terms mean. Is that justification for adding confusion by using these terms to generalize and mis-generalize all kinds of technologies?

答: As long as they are used in the right context which does not imply or propose any ill-formed behaviors, I think they should be used until we can come up with better appropriate terms. </p>


答:
My view is this:  You should rewrite when it would be easier to start from scratch than to refactor.  For instance, if the refactoring effort would involve months of retrofitting procedurally-written OOP code to proper OOP before you could even start to refactor the code, then a rewrite is the better option because you have to change everything.  Another example would be if there are zero unit tests and the infrastructure doesn't support unit testing (i.e. tightly-coupled code, no separation of concerns), you cannot begin to refactor the code without a test suite, but creating the test suite requires taking the guts of the application and making some pretty serious modifications to enable creating those tests in the first place.  It's an infinite loop, of sorts: You can't refactor without the tests, but the tests can't exist without refactoring.

I disagree vehemently with Joel's article on rewriting, because I've been in many situations where a serious refactoring cannot happen because literally NOTHING is done correctly to support refactoring at all.  In a situation like this, the choices are often: 1) Rewrite the application, or 2) Don't touch anything and keep slopping on code.

You should also consider a rewrite when you need to introduce some serious architectural changes to the code that can't be retrofitted, again the quintessential example would be working on an app that's been thrown together without rhyme or reason, no unit tests, no separations, hard-coded SQL, magic numbers everywhere.. you get the idea.  Trying to change a beast like that is like Sisyphus trying to push the boulder, especially if you want to introduce proper design concepts like SOLID, or introduce a proper ORM, or say move to ASP.NET MVC when everything is WebForms with all logic in code-behind to it.

To stay with the whole "technical debt" theme, I put forth this:

Refactoring is going through a (technical) debt consolidation and slowly paying back the debt over a (usually long) period of time.

Rewriting is (technical) bankruptcy.

Just like in real finances, sometimes your debt is so great that bankruptcy is the best (if not the only) option to just wipe everything clean and start again, provided you don't make the same mistakes again.

Title: When should you rewrite?


答:
This question must have been inspired by this one, and the answer is approximately the same. The "front end" and "back end" terms often make sense in a particular context. Most developers would understand the terms as they relate to compilers, for example. And the terms may also have well defined meanings in the context of a particular project. If you're not clear on what's meant by those terms in your own interactions, you should ask for clarification.

Since there's no practical way to "do away" with any particular jargon (are you going to send a memo out the the entire software development community?), the best you can do is to avoid terms that don't make sense to you. If you have some influence on your own project, you can certainly propose or dictate different terms. Aside from that, "front end" and "back end" are in common usage despite their ambiguity, and that's probably not going to change anytime soon.

Title: Is it time to do away with 'front-end' and 'back-end' as tech jargon?

Body:
It seems that the primary usage of these terms is either:

mutual mystification of contractors and/or clients who don't know what they are talking about or how to talk about it,

the innocent and ignorant (see this question) , or

laziness to avoid having to say user-interface/user-facing or business logic/database/infrastructure.

Granted, you don't always want to explain to the boardroom what the aforementioned terms mean. Is that justification for adding confusion by using these terms to generalize and mis-generalize all kinds of technologies?


问:
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?

答:
The mental state you're describing sounds like Flow, a phenomenon studied extensively by the Hungarian Psychologist Mihaly Csikszentmihalyi. Briefly, its main characteristics are:

Clear goals

High degree of concentration on a limited field of attention

Loss of self-consciousness

Distorted sense of time

A sense of personal control over the situation or activity.

The activity is intrinsically rewarding, so there is an effortlessness of action.

A lack of awareness of bodily needs (like hunger or fatigue)

Computer programmers seem to be better able to achieve Flow, and it has been hypothesized that people with an autotelic personality are also better able to achieve Flow.

Flow is generally considered a positive experience correlated with maximal productivity. In his book Emotional Intelligence, the psychologist Daniel Goleman wrote, "The hallmark of flow is a feeling of spontaneous joy, even rapture, while performing a task."

So, given all that, why on earth do you want to stifle it? My advice would be to savor it and foster it as much as possible.

However, given that you want to extirpate Flow, here are a couple of ideas:

Boredom and anxiety block flow. So cultivating these mental states might work. But I highly recommend against it.

There are a few conditions that make flow possible (clear goals, balance between your skill level and the level of the challenge, and the task you're working on must have immediate feedback). Getting rid of any one of these conditions may also get rid of Flow.

In my personal experience, Flow decreases in frequency and intensity with age. So you may just want to "wait it out."

ContentLicense: CC BY-SA 2.5


答:
I see no problem with the terms.  In many cases, they make perfect sense.  Just because they do not meet your myopic view of the development environment you exist within does not mean they are incorrect or inappropriate in general.

In the context of which I exist, I am 100% a back-end coder.  I write frameworks, tools, and API's with which our web team and internal application developers interact to get to corporate data.  I haven't written any user interface code (in my job) in at least 2 years.


答:
It's all relative. Everything has a "front" and a "back". It depends on what thing you're talking about.

The implication is that you need to define the context. Which, I thought, is important in any scenario.


答:
In what way is it worse to say "back-end developer" than "developer who deals with one or more of: databases (coding, optimisation, design), business coding (except where implemented in the user interface), security, infrastructure, database optimisation, deployment, reporting, DR, scheduling, load balancing.

In what was is it worse to say "front-end developer" than " developer who deals with one or more of: user interface design, formulation of corporate standards, javascript, CSS and/or HTML coding, image manipulation, UX considerations, cross-browser compatibility validation.

The terms work, they are vague enough to cover a broad set of skills but specific enough to server a purpose.

I know many people (my wife, for example) who just hate front-end coding. She hates having to deal with user interfaces, coming up with the pretty - she just wants to write code to deal with a business function.


答: It's clear that what's bothering you is having to wake up early in the morning and NOT staying up to the wee-hours of the night, nor missing lunch. Talk to your boss, wife, client, or whomever, and try to get some hours that respect your workaholic obsessive work binges. Assuming that you program effectively in those moments, who would want you to be balanced and "healthy" (big quotes around that: as if boring cycles are healthy)?</p>

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?


问:
Constructor parameter validation in C# - Best practices
What is the best practice for constructor parameter validation?

Suppose a simple bit of C#:

```<code>public class MyClass
{
    public MyClass(string text)
    {
        if (String.IsNullOrEmpty(text))
            throw new ArgumentException("Text cannot be empty");

        // continue with normal construction
    }
}
</code>```

Would it be acceptable to throw an exception?

The alternative I encountered was pre-validation, before instantiating:

```<code>public class CallingClass
{
    public MyClass MakeMyClass(string text)
    {
        if (String.IsNullOrEmpty(text))
        {
            MessageBox.Show("Text cannot be empty");
            return null;
        }
        else
        {
            return new MyClass(text);
        }
    }
}
</code>```

答: My preference is to set a default, but I know Java has the "Apache Commons" library that does something like this, and I think that's a fairly good idea as well.  I don't see an issue with throwing an exception if the invalid value would put the object in an unusable state; a string isn't a good example but what if it was for poor man's DI?  You couldn't operate if a value of null was passed in in place of, let's say, a ICustomerRepository interface.  In a situation like this, throwing an exception is the correct way of handling things, I would say.


答:
I'm late to the party, but just saw this question.

One thing I don't see very well addressed is this:

Grunts don't ever tell the whole truth to the suits. Rands says this in DNA but doesn't address it head-on, he's on a different topic.

You are wearing a suit, and you sign the checks. You represent the interest of the company. You are not representing the engineers. If you did, you'd not be signing their checks, they'd be signing yours.

This is of course not news to you or the engineers. But when an engineer knows that bring up certain issues - problems - with his workplace would cause significant conflict  - the risk/reward tradeoff does not favor the engineer. Engineers are paid to produce product, not kick off workplace culture fights. Getting involved in those is a fast track to doing the job wrong.

So part of the management task is to provide a way for the engineers to be open about problems, without incurring corporate politics & career backlash. It's nice to have raises, after all, and there are other companies, if this one doesn't feel congenial.

Title: I'm a manager. How can I improve work relationships and communication with programmers?

Body:
A little background first. I'm a project manager at medium-sized company. I started as a CS major and had a little exposure to programming, but after a few months I knew it's not my path, so I switched over to management. That proved to be a good decision, and after graduating I've worked in software management at various companies (for 5 years now).

Recently, we had a very painful project. It was the worst of the worst, with many mistakes both on our side and on the customers side and just barely ending it without losses. It has led to many frustrating situations, one of which escalated to the point where one of our senior developers left company after a vocal argument with us (the management). This was a red flag for me: I did something terribly wrong. (for the record, the argument was about several mistaken time estimates)

I searched many places for answers and a friend pointed me to this site. There are many questions here about frustrations with management. I can understand that the general bad experiences lead to a general reluctance against "those guys in the suits".

I'm that guy in the suit. It may not look like it, but all I want is a successful project, and with limited resources it takes painful decisions. That's my job. One of the things the aforementioned senior developer complained about was work equipment. Frankly, I had no idea that the computers we had were not suited for working. After this, I asked many programmers and the general consensus was that we need better machines. I fixed that since then, but there was obviously a huge communication gap between me and the programmers. Some of the most brilliant developers are the most shy and silent people. I know that, and it was never a problem during an interview. People are different, and have strengths at different areas.

The case of the underpowered PCs is just one of the many that led me to thinking that there is a communication issue. How can I improve communication with programmers without being intimidating and repetitive?

What I'm hoping is that people don't complain about good things. If you love your workplace and love (or at least like :)) your manager, please tell me about them. What are they doing right? Similarly, if you hate it, please describe in detail why. I'm looking for answers about improving communication because I think that is my problem, but I might be wrong.


问:
How can a web site be set up using the MVC Pattern? (Without MS ASP.NET MVC)
We used a contractor to create the initial version of our site; they used their own MVC-pattern code-generator to create the (ASP.NET / C#) site and customized from there. That was turned over to us two years ago, and we've been working on it since. That's the environment I'm coming into, with little practical MVC experience. Thus I need to grok MVC in general but it seems that every article/tutorial/book I find is either extremely general in nature or very specific to MS ASP.NET MVC.

Can someone here help with examples, a tutorial or walk-through of setting up a basic site using the MVC Pattern without using Microsoft ASP.NET MVC so that I can better understand the concepts and see how they can be applied in real life?

答:
Model View Controller is a design pattern for separation of concerns; it's difficult to find a middle ground for explaining such a concept, since there isn't an additional step/point between a design pattern and a framework that implements that pattern.

That being said, I think it's helpful to see the concepts played out in multiple implementations side-by-side so that you can understand the concept specific cases without losing the forest for the trees.

I'd highly recommend Ajax in Action (Manning), which--although not expressly about MVC--does an excellent job of laying out several examples of MVC in a couple different server-side situations, as well as in the client-side Javascript.

http://www.amazon.com/Ajax-Action-Dave-Crane/dp/1932394613/ref=sr_1_1?ie=UTF8&qid=1313181118&sr=8-1


问:
Should we choose Java over C# for a new project?
We have a team of .NET developers (C#) with a range of experience from 2 to 6 years. Over the last few years we have been developing Silverlight, ASP.NET MVC, and WPF applications. However, there is a new two year project which means we will develop a HTML5 application on Linux.

The company I work for would like all developers across their offices to use the same programming language which is Java. Although there is talk of using Mono but using the same language and sharing modules, services, etc. already created in Java is the main reason for moving to Java.

Some of the developers here are upset. How do I find something positive in moving over that will convince the other developers?

There will be a training budget, but the thought of learning to work with Java libraries and a new platform (Linux) will be scaring a lot of the guys.

What should I do?

答:
A couple points I'd like to add.

Yes, as a dev, moving from .Net to Java will be a bit of a challenge.

And Yes, it does pay off for the developer, by expanding skills.

And Yes, it does in one hand pay off for the company, in that devs are more easily transitioned between projects (since language isn't a barrier)

But, there is a downside when an organization is stuck with one language.  And it's the same issue as being a developer stuck in one language.  When you go to purchase apps, and integrate them with your existing code, you're stuck to the stack you know and stack you work in.

You end up ignoring a great product because you don't have people trained to customize it to your needs.  Or you still buy it, and do a half arsed job integrating it because you don't fully understand it.  But then, you're stuck in two stacks again, with the same problems you had before.


问:
Why don't all companies buy developers the best hardware?
I must be missing something.

The cost of employing a programmer in my area is $50 to $100 an hour. A top end machine is only $3,000, so the cost of buying a truly great computer every three years comes to $0.50/hour.  ($3000/(150 wks * 40 hours))

Do you need a top-end machine? No, the $3000 here is to represent the most that could possibly be spent not the amount that I would expect. That's roughly the cost of a top-end iMac or MacBook (17 inch).

So suppose you can save $2000 every three years by buying cheaper computers, and your average developer is making $60. (These are the most charitable numbers that I can offer the bean-counters. If you only save $1000, or $750, it only strengthens my case.) If those cheaper computers only cost you 10 minutes of productivity a day. (Not at all a stretch, I'm sure that my machine costs me more than that.) then over 3 years the 125 lost hours would add up to a loss of $7500. A loss of 1 minute a day ($750) would give a net gain of $1250, which would hardly offset the cost of poor morale.

Is this a case of "penny-wise and pound-foolish" or have I oversimplified the question? Why isn't there universal agreement (even in the 'enterprise') that software developers should have great hardware?

Edit: I should clarify that I'm not talking about a desire for screaming fast performance that would make my friends envious, and/or a SSD. I'm talking about machines with too little RAM to handle their regular workload, which leads to freezing, rebooting, and (no exaggeration) approximately 20 minutes to boot and open the typical applications on a normal Monday. (I don't shut down except for weekends.)

I'm actually slated to get a new machine soon, and it will improve things somewhat. (I'll be going from 2GB to 3GB RAM, here in 2011.)  But since the new machine is mediocre by current standards, it is reasonable to expect that it will also be unacceptable before its retirement date.

Wait! before you answer or comment:

$3000 doesn't matter. If the machine you want costs less than that, that's all the more reason that it should have been purchased.

I'm not asking for more frequent upgrades. Just better hardware on the same schedule. So there is no hidden cost of installation, etc.

Please don't discuss the difference between bleeding edge hardware and very good hardware. I'm lobbying for very good hardware, as in a machine that is, at worst, one of the best machines made three years ago.

$50 - $100 / hour is an estimate of employment cost - not salary. If you work as a contractor it would be the billing rate the contracting agency uses which includes their expenses and profit, the employers Social Sec. contribution, employers health care contribution etc. Please don't comment on this number unless you know it to be unrealistic.

Make sure you are providing new content. Read all answers before providing another one.

答:
I must have missed the author's perspective.

First, Google as one example was founded using cheap, "disposable" hard drives attached to older servers run as a farm.  OK that might be hyperbole, yet see: http://en.wikipedia.org/wiki/Google_platform#Original_hardware

Second, it doesn't take much CPU or graphics resource to run gvim.  So maybe your choice of development environment is the problem.

Third, there are dozens if not hundreds of CPU-intensity-reducing ways to enhance productivity which have little to do with whether or not you have 2 gig of RAM or 3 gig of RAM.  Watch an average programmer over their shoulder to see this: for example, using a lightweight PDF reader vs. Adobe suite for the documentation; using a minimal installation of a VM for testing apps rather than a full install; removing all those startup daemons bundled with Win DELL machines (using regedit); using a lightweight browser to webmail instead of keeping outlook running; not opening 50 gazillion tabs in firefox chasing solutions to MSFT implementation issues on the web; etc etc etc..   So this point boils down to the following:  Prove you need more Memory and Mhz to solve this software design problem faster.


问:
MVVM light Communication
I am working on a large MVVM application. I am using the MVVM light toolkit for this. The application is like a web browser with back and forward buttons. The main view is an user control. I laid the back and forward buttons in the main view user control. The main view in turn has user controls. The user controls change when the back and forward buttons are clicked. The main ViewModel keeps track of the current user control and loads the next one depending on the button click.

All these user controls are loaded depending on the selection(ID) made on the first step. Lets say, the main view is a search screen and we select a customer. The next screens would be Address, Billing, Requests, etc. These screens does not share any data. But the data is for the same customer.

So, is it a good practice, to store the customer ID in the main view? If I do this, I should have a UserControl_Loaded event bound to a command, where I would then request for Address and Billing Info.

Or I can move the buttons(back and forward buttons) to each user control instead of the main view, Pass the customer ID with the message which would load the next view.

Which is better?

答:
In your main CustomerViewModel I would have

Customer object

ObservableCollection<ViewModelBase> CustomerSubViewModels

int CustomerSubViewModelIndex

BackCommand

ForwardCommand

ViewModelBase CurrentView which is returns CustomerSubViewModels[CustomerSubViewModelIndex]

Your main CustomerView would contain a ContentControl with it's Content bound to CurrentView, and Back/Forward buttons which would change the CustomerSubViewModelIndex +- 1, which in turn alters the page displayed in the CurrentView. DataTemplates would be used to define how they should be drawn inside the ContentControl.

Your pages like Addresses, Billing, Requests would all be stored in the CustomerSubViewModels Collection, and I would pass them the Customer properties they need from within the CustomerViewModel. That could be a value like CustomerId, a property like Customer.Addresses, or even the entire Customer object. I would use

Title: MVVM light Communication


问:
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>

答:
This was written in regard to natural languages, but I think it is appropriate to programming languages as well:

A belief that some languages are intrinsically superior to others is widespread, but it has no basis in linguistic fact. Some languages are of course more useful or prestigious than others, at a particular period of history, but this is due to the preeminence of the speakers at that time, and not to any inherent linguistic characteristics.

--David Crystal (ed.). The Cambridge Encyclopedia of Language 2/e (1997). p.7

"Power" simply isn't attributable to one language over another. It would be silly to say "Chinese is a more powerful language than Korean." Likewise, it is silly to say "APL is a more powerful language than COBOL."

There have been several attempts to equate linguistic power with some objective measure. I believe these attempts fail:

It may be easier to get a job in the US if you speak American English than say Maori. Likewise, its no doubt easier to get a job programming Java or C, rather than LISP or J. But this economic advantage certainly doesn't reflect some kind of innate power of the language. Its about the power of speakers of the language.

"Hi" isn't better than "ni hao" or "shalom" because its shorter. Similarly, while a function may be expressed more succinctly in APL than COBOL, this too doesn't reflect some kind of innate power of the language.

My opinion is that discussions of "the power of one language over another" are veiled expressions of the speaker's feelings of superiority over some other group. In short, its prejudice and stereotyping. Of course, people who are prejudiced really, really believe their stereotypes quite strongly, and its unlikely you could persuade them to change their minds.

Title: What is a "powerful" language?


问:
Asynchronous Programming in Functional Languages
I'm mostly a C/C++ programmer, which means that the majority of my experience is with procedural and object-oriented paradigms.  However, as many C++ programmers are aware, C++ has shifted in emphasis over the years to a functional-esque style, culminating finally in the addition of lambdas and closures in C++0x.

Regardless, while I have considerable experience coding in a functional style using C++, I have very little experience with actual functional languages such as Lisp, Haskell, etc.

I've recently began studying these languages, because the idea of "no side-effects" in purely functional languages has always intrigued me, especially with regards to its applications to concurrency and distributed computing.

However, coming from a C++ background I'm confused as to how this "no side-effects" philsophy works with asynchronous programming.  By asynchronous programming I mean any framework/API/coding style which dispatches user-provided event handlers to handle events which occur asynchronously (outside the flow of the program.)  This includes asynchronous libraries such as Boost.ASIO, or even just plain old C signal handlers or Java GUI event handlers.

The one thing all of these have in common is that the nature of asynchronous programming seems to require the creation of side-effects (state), in order for the main flow of the program to become aware that an asynchronous event handler has been invoked.  Typically, in a framework like Boost.ASIO, an event handler changes the state of an object, so that the effect of the event is propagated beyond the life-time of the event handler function.  Really, what else can an event handler do?  It can't "return" a value to the call point, because there is no call point.  The event handler is not part of the main flow of the program, so the only way it can have any effect on the actual program is to change some state (or else longjmp to another execution point).

So it seems that asynchronous programming is all about asynchronously producing side-effects.  This seems completely at odds with the goals of functional programming.  How are these two paradigms reconciled (in practice) in functional languages?

答:
This is a fascinating question. The most interesting take on it is, in my view, the approach adopted in Clojure and explained in this video:

http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey

Basically the "solution" proposed is as follows:

You write most of your code as classic "pure" functions with immutable data structures and no side effects

Side effects are isolated via the use of managed references which control change subject to software transactional memory rules (i.e. all your updates to mutable state take place within a proper isolated transaction)

If you take this view of the world, you can see asynchronous "events" as triggers for a transactional update of mutable state where the update is itself a pure function.

I've probably not expressed the idea as clearly as others have done, but I hope this gives the general idea - basically it's using a concurrent STM system to provide the "bridge" between pure functional programming and asynchronous event handling.


问:
Is learning C# as a first language a mistake?
I know there are similar questions on here, which I've read, but I recently read this post by Joel Spolsky:

How can I teach a bright person, with no programming experience, how to program?

And it got me thinking about my way of learning and whether it might actually be harmful in the long run.

I've dabbled with various languages but C# is my first serious one, I've read "Head First C#" and created a few projects. But after reading the post above I've found it a bit disheartening that I may be going about it all wrong, obviously I respect Joel's opinion which is what has thrown me a bit.

I've started reading "Code" as recommended in the reading list and I'm finding it pretty hard going, although enjoyable. I feel like it's taken the shine off of my "noobish hacking about" in Visual Studio.

So now I'm unsure as to what path I should take? Should I take a step back and follow Joel's advice and start reading?

I guess my main aim is just to become a good programmer, like everyone else, but I don't want to be going into bad practice by learning a .NET language when someone who's opinion I respect thinks that it is harmful.

Thoughts?

答:
To me, that stuff in that other article smacked a bit of being elitist drivel.  Yes, I frequently recommend SICP to serious developers who really want to get better, but only to those who want to go beyond the "norm" and learn the deep magic. Indeed, for years SICP was the standard MIT freshman programming text; but, a lot of solid working programmers never had the opportunity to attend that fine but expensive and highly selective institution.

So what do I recommend, in answer to your question?  Start with what you have and learn how to think like a programmer, rather than just learning some specific language.

If you happen to have a C# implementation available, well, I can tell you that it's a perfectly fine language for a working stiff like me—as are Java, JavaScript, Python, Ruby, Scala, Scheme, and the many other languages I have learned over the years.  In the end, I try to select the right languages and tools for the specific job at hand, and that means switching languages like hats.

There is nothing wrong with using fun ways to learn, such as approaching Ruby via Why's Poignant Guide and Shoes (like I recommended in another recent post).  There are arcane and mystical paths, such as banging your head against The Little Schemer and The Seasoned Schemer on your way to SICP.  Many modern thinkers would have you skip all that older academic and "enterprisey" stuff and dive directly into JavaScript, JQuery, and HTML5 instead. There are many ways to get started so don't waste too much more time.  Just pick one and get coding!

Realistically, I believe few working professionals these days would send you backwards to learn Assembler or C/C++ first.  Frankly, if they did, I do not believe they would be doing you much of a service.

So, to embellish a little on "start with what you have," I have three more bits of advice:

Pick one programming language that seems cool to you and one learning approach that seems to make sense and give them your all.  Become literate in your chosen language; read as much good code as you can manage!

Get your hands on your keyboard right away and start coding as you learn.  Do all the elementary exercises in your programming books by yourself and practice all the tutorials you can find with your fingers happily clicking away to make them really work.  You'll be surprised by how many skills you will gain while fixing errors in demos that are supposed to be working code but are not!

Spend most of your effort on learning how good programmers think their way through problems.  Learn how to analyze and decompose complex problems and systems, breaking them down until you really understand them.  Then learn to synthesize and design automated solutions, building them up so that they make some task easier for some human beings on this planet.

I started with FORTRAN IV and QBASIC and if those didn't ruin me, C# will not hurt you, either!  Good luck and make sure you're having fun while you're learning!


答:
Developers with a range of experience from 2 to 6 years ...  How do I find something positive in moving over that will convince the other developers?

It is bizarre that a critical strategic platform decision such as this one is left to the whims of junior developers.   Your senior guy needs to man up to pick the right platform for the company.   In another 5 years C# very well could be on the strong decline as Win32/64 drops in importance in light of OS X and iOS uptake (don't believe this? Check the numbers and revenue graphs of AAPL).  Ask your developers why they want to develop for a platform that will be dead in 10 years.  Do they want to be like IBM in the 80s?

For this reason Java is the best way to go because it allows migration to the new platform (bthe desired Linux and OS X) in a cross-platform way, without other middleware such as Mono (emulation layers).  C# and Java are near identical languages syntactically.  .NET is just a bunch of library calls.  Reference: http://www.25hoursaday.com/CsharpVsJava.html

Title: Should we choose Java over C# for a new project?

Body:
We have a team of .NET developers (C#) with a range of experience from 2 to 6 years. Over the last few years we have been developing Silverlight, ASP.NET MVC, and WPF applications. However, there is a new two year project which means we will develop a HTML5 application on Linux.

The company I work for would like all developers across their offices to use the same programming language which is Java. Although there is talk of using Mono but using the same language and sharing modules, services, etc. already created in Java is the main reason for moving to Java.

Some of the developers here are upset. How do I find something positive in moving over that will convince the other developers?

There will be a training budget, but the thought of learning to work with Java libraries and a new platform (Linux) will be scaring a lot of the guys.

What should I do?


问:
Why does a computer science degree matter to a professional programmer?
I have a degree in computer science.  It has been great for opening doors, getting a job.  As far as helping me in the professional field of C# .NET programming (the most popular platform and language in the area I work if not the entire united states on hands down the most popular OS in the world) its hardly useful.  Why do you think it helps you as a programmer in your professional career (outside spouting off to prims algorithm to impress some interviewer)?

In today's world adaptation, a quick mind, strong communication, OO and fundamental design skills enable a developer to write software that a customer will accept.  These skills are only skimmed over in the cs program.  In my mind, reading a 500 page C# book by Wrox offers far more useable a skillset than 4 years of the comp sci math blaster courses.  Many disagree.  So, why does a computer science degree matter?

答:
Absolutely correct, computer science degree does not matter much; which is why your only choice should be to get an engineering degree instead.

In interviewing candidates with various backgrounds, the one trait which stands out for those candidates who did not have any degree is this:  lack of technical communication skills and lack of discipline.   These are fundamental traits learned when getting any science degree (I'd say even more so with an engineering degree).

With most things being equal (and a single round of interviews often comes up with "about equal" candidates), I would hire the person with engineering degree first, the computer science degree second, and the no-degree third.  However, there are ways to make things very unequal in the comparison, so that anyone can beat out even those with a pedigree degree - but that's a separate question isn't it?


问:
How can I be most productive in Visual Studio when limited to small screen space?
I'm a student, and I do a lot of code on a small (12.5", 1366x768) laptop screen that I carry from class to class. Most programming environments are designed with the idea that someone has large screen size available, because most programmers do in fact have access to large screens. However, large screens are difficult to carry to class all day, and my previous laptop (15", 1920x1200) often got left in the dorm just because it was so friggin heavy.

I'm pretty much locked in to Visual Studio at this point; no program I've ever used is as productive for the kind of code I work with (after installing Whole Tomato's Visual Assist and Jared Par's VsVim, of course :) )

(I've seen other questions about small screens but they all pretty much go with "leave Visual Studio" -- which is hard given some of the kinds of development I've been doing....

答:
All that stuff on the View menu? Set them to collapse. Do this by clicking the push-pin/thumb tack and let the windows collapse back to the sidelines. This gives you a lot more screen space for the important stuff, and if you need it, mouse over the tab and it slides out. The visual cue that the tab will auto-expand/collapse, or stay out all the time is the push-pin (circled in red on samples): vertical, they stay out all the time; horizontal, they come out when you need them.

Sample will all stuff expanded:

Same sample will all stuff collapsed:

Property Tab expanded:


答:
Discussions about programming languages are - IMHO - like discussions about mail clients in some Linux newsgroups: they tend to be a flame war. I can remember times when VB6 was popular. There were people even arguing that it isn't a programming language at all, while others created stunning applications with it.

I think programming languages differ already in the concept as the creators had different things in mind when they created/designed the language. So a language that fits one purpose - and under that circumstance is powerful - might not fit another. Naming the language powerful or not is then purely subjective. That said, I do not think that there is a metric that can be applied.

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>


答:
Plenty of space! Right click on the toolbar area and uncheck the toolbars, put all the side and bottom panels on autohide or just have one side panel and setup tabs by dragging windows into the panel you want to use. Learn shortcut keys. Auto-hide your Windows taskbar.

Also Google for fonts like Dina that are both small and readable.

Title: How can I be most productive in Visual Studio when limited to small screen space?

Body:
I'm a student, and I do a lot of code on a small (12.5", 1366x768) laptop screen that I carry from class to class. Most programming environments are designed with the idea that someone has large screen size available, because most programmers do in fact have access to large screens. However, large screens are difficult to carry to class all day, and my previous laptop (15", 1920x1200) often got left in the dorm just because it was so friggin heavy.

I'm pretty much locked in to Visual Studio at this point; no program I've ever used is as productive for the kind of code I work with (after installing Whole Tomato's Visual Assist and Jared Par's VsVim, of course :) )

(I've seen other questions about small screens but they all pretty much go with "leave Visual Studio" -- which is hard given some of the kinds of development I've been doing....


答:
Learn the shortcuts to various commands and use the full screen mode (View -> Full Screen).

You can also use the "Command Window" to access other menu items (even if they don't have a shortcut), you can find it in the View menu -> Other windows -> Command Window


问:
function pointers are so complex to me
I found this code sample in this answer by Armen Tsirunyan.

```<code>class MyClass
{
   public:
   typedef void (*funcPtr)(int, int);
   MyClass(funcPtr whatToCall)
   {
     callme = whatToCall;
   }
   void myClass::callMain()
   {
       callSomeApi(callme, <some arguments>);  //callme function pointer is passed as argument
   }
private:
   funcPtr callme;
};

void f(int a, int b) {blah blah blah};

int main()
{
   MyClass myObject(f);
   myObject.callMain(); //will call the api function with f passed as argument
}
</code>```

I would like to know the advantages to use such a function pointer as a class member. If there are more, I should be overwhelmed to their uses and calls. Do you have some tips to help me memorise its usage?

答:
The alternative to have a class store a function pointer for a callback is having a class store an instance of a callback class. You can do that like this:

```<code>class MyCallbackClass
{
 public:
 virtual void CallbackFunction(int param1, int param2)=0;
};
</code>```

Now, instead of: funcPtr callme; Use MyCallbackClass *callme;

Call it with callme->CallbackFunction(param1, param2);

Create the callback with:

```<code>class SomeCallback : public MyCallbackClass
{
 public:
 SomeCallBack() { ; }
 virtual int CallbackFunction(int p1, int p2)
 {
  // callback code goes here
 }
};
</code>```

Then initialize 'callme' to a new SomeCallBack();

This is much more the "C++ way" than function pointers. It tends to be much more elegant in complex cases -- especially where more than one callback is needed. But it tends to be ugly in simpler cases, especially because you have to create an instance of the callback class, which is pure ugly if the callback class doesn't need any member variables. If it does need member variables, that's actually a plus and then the callback class approach really shines.

Title: function pointers are so complex to me

Body:
The alternative to have a class store a function pointer for a callback is having a class store an instance of a callback class. You can do that like this:

class MyCallbackClass
{
 public:
 virtual void CallbackFunction(int param1, int param2)=0;
};

Now, instead of: funcPtr callme; Use MyCallbackClass *callme;

Call it with callme->CallbackFunction(param1, param2);

Create the callback with:

class SomeCallback : public MyCallbackClass
{
 public:
 SomeCallBack() { ; }
 virtual int CallbackFunction(int p1, int p2)
 {
  // callback code goes here
 }
};

Then initialize 'callme' to a new SomeCallBack();

This is much more the "C++ way" than function pointers. It tends to be much more elegant in complex cases -- especially where more than one callback is needed. But it tends to be ugly in simpler cases, especially because you have to create an instance of the callback class, which is pure ugly if the callback class doesn't need any member variables. If it does need member variables, that's actually a plus and then the callback class approach really shines.


问:
API design pitfalls in C
What are some flaws that drive you nuts in C APIs (including standard libraries, third party libraries, and headers inside of a project) ?  The goal is to identify API design pitfalls in C, so people writing new C libraries can learn from mistakes of the past.

Explain why the flaw is bad (preferably with an example), and try to suggest an improvement.  Although your solution might not be practical in real life (it's too late to fix strncpy), it should give a heads up for future library-writers.

Although the focus of this question is C APIs, problems that affect your ability to use them in other languages are welcome.

Please give one flaw per answer, so democracy can sort the answers.

答:
Functions with inconsistent and often cumbersome string returning conventions.

For example, getcwd asks for a user-supplied buffer and its size.  This means an application either has to set an arbitrary limit on the current directory length, or do something like this (from CCAN):

```<code> /* *This* is why people hate C. */
len = 32;
cwd = talloc_array(ctx, char, len);
while (!getcwd(cwd, len)) {
    if (errno != ERANGE) {
        talloc_free(cwd);
        return NULL;
    }
    cwd = talloc_realloc(ctx, cwd, char, len *= 2);
}
</code>```

My solution: return a malloced string.  It's simple, robust, and no less efficient.  Excepting embedded platforms and older systems, malloc is actually quite fast.

Title: API design pitfalls in C

Body:
Functions with inconsistent and often cumbersome string returning conventions.

For example, getcwd asks for a user-supplied buffer and its size.  This means an application either has to set an arbitrary limit on the current directory length, or do something like this (from CCAN):

 /* *This* is why people hate C. */
len = 32;
cwd = talloc_array(ctx, char, len);
while (!getcwd(cwd, len)) {
    if (errno != ERANGE) {
        talloc_free(cwd);
        return NULL;
    }
    cwd = talloc_realloc(ctx, cwd, char, len *= 2);
}

My solution: return a malloced string.  It's simple, robust, and no less efficient.  Excepting embedded platforms and older systems, malloc is actually quite fast.


问:
Functional testing must be done by external party to avoid bias?
Our developers demand that someone external to the development team completes the functional testing. Their argument is that they are biased and cannot test their own code as they are too close to it. Our last round of testing is with the client in the form of UAT.

To be clear by 'functional testing' I mean testing the code against the specs, eg. when you click on 'submit' the index page should load. By UAT I mean the client comes in and runs through use cases on the release candidate.

While I understand this argument of bias, is it reasonable for the developers to demand someone else complete their functional testing or is this just a way to avoid doing their job?

答:
I think you absolutely have to do both. Programmers have to do functional testing because functional testing is always part of programming. It would be extremely inefficient for a programmer to release code to someone else if he hadn't already made sure it actually functioned. (Sometimes you have no choice, such as when the programmer can't replicate a problem. This almost always makes things much slower.)

However, the complaint is legitimate. Programmers naturally do things the way they programmed the computer to expect because that's how they expected humans to do it. As a result, functional issues that anyone but the programmer would hit are missed by the programmers. I can't tell you how many times someone complained that my code was broken and didn't do what they expected, and my reaction was "Why would anyone do that?" Yet to many non-programmers, it was the most natural way to request the specified function.

Programmers must always do functional testing when it is possible for them to do so because that is the most efficient way to catch non-functional code and non-functional code is common. However, functionality also must always be tested by someone more like the expected user to ensure the code functions as the user expects and to ensure the programmers correctly understood the specification.

OwnerDisplayName: bobbyz


问:
How far should I take email address validation when the cost of bad emails is high?
When it's more important to prevent typos than to cover 100% of all possible email addresses, what syntactic email validations do you do?

Imagine this:

You're with the local gas & electric company.  10% of new
  installations are cancelled because the customer is not home and it
  costs your company $50 a pop.  You start taking email addresses with
  the new install orders so that you can send reminder emails the day
  before the appointment.  You bring that number to 0% when you have a
  deliverable email.  The only problem is that 15% of all the emails
  you take bounce back because of some typo.  Email addresses are
  recorded by call center agents who talk to the customer over the
  phone.

In this case, it's important to collect a valid email address.  It's also not all that bad if someone cannot successfully use an email address like:

```<code>"Big Momma D.'s #1 CA$H Maker, BOY!!!"@naturalhistory.museum
</code>```

My guess is that Big Momma D. can't use this email anywhere and either doesn't really use email, or has more conventional email address to use.

This is related to this more general question:
How far should I take e-mail address validation?

Let's throw a few more assumptions on here:

This is in the US, so it's unlike people will have email addresses like 漢字@gmail.com (good luck communicating that to a call center agent in Austin, Texas)

Validation emails are not suitable, since the customer is only in contact with us by phone

答:
One possible solution: Have them send you an email from their regular email address instead. Give them an email address that's as easy as possible to type. You can reserve a domain just for this. If your company is "MyCorp", you can register "MyCorpEmail.com". Tell them their appointment code is '243' and have them email '243@MyCorpEmail.com" (You can vary the domain, the appointment code can be a word, you get the idea.)

Then, when you get the email, you will have captured their email address with no chance of a typo. Just carefully select the email code on your side to make it as easy to type and spell as possible. You can even ask them to send them the email while you're on the phone, if possible.


答:
The way for you to "smell test" this request is determine how much of their own testing the developers have done.  Did they do unit tests?  Did they document them?  Can they show how the work was tested against the initial requirements?  What evidence is there that the work they have done is "ready" for formal review?

This will help you understand if they're just trying to throw it over the wall or if they've given it all the scrutiny they can and want a second set of eyes.

Title: Functional testing must be done by external party to avoid bias?

Body:
Our developers demand that someone external to the development team completes the functional testing. Their argument is that they are biased and cannot test their own code as they are too close to it. Our last round of testing is with the client in the form of UAT.

To be clear by 'functional testing' I mean testing the code against the specs, eg. when you click on 'submit' the index page should load. By UAT I mean the client comes in and runs through use cases on the release candidate.

While I understand this argument of bias, is it reasonable for the developers to demand someone else complete their functional testing or is this just a way to avoid doing their job?


问:
Are Intel compilers really better than the Microsoft ones?
Years ago, I was surprised when I discovered that Intel sells Visual Studio compatible compilers. I tried it in particular for C/C++ as well as fantastic diagnostic tools. But the code was simply not that computationally intensive to notice the difference. The only impression was: did Intel really do it for me just now, wow, amazing tools with nanoseconds resolution, unbelievable. But the trial ended and the team never seriously considered a purchase.

From your experience, if license cost does not matter, which vendor is the winner?

It is not a broad or vague question or attemt to spark a holy war. This sort of question is about two very visible tools. Nobody likes when tools have any mysteries or surprises. And choices between best and best are always the pain. I also understand the grass is always greener argument. I want to hear all "what ifs" stories.

What if Intel just locally optimizes it for the chip stepping of the month, and not every hardware target will actually work as well as Microsoft compiled? What if AMD hardware is the target and everything will slow down for no reason? Or on the other hand, what if Intel's hardware has so many unnoticable opportunities, that Microsoft compiler writers are too slow to adopt and never implement it in the compiler? What if both are the same exactly, actually a single codebase just wrapped into two different boxes and licensed to both vendors by some third-party shop?

And so on. But someone knows some answers.

答:
I've only encountered three advantages:

It has support for features of newer Intel CPUs much sooner than other compilers do.

It's a great additional compiler to issue warnings and catch problems that other compilers miss. GCC catches some things ICC doesn't, and vice versa. Visual studio catches some things ICC doesn't, and vice versa.

It does a much better job of auto-parallelizing loops (distributing them over multiple threads automatically) than any other compiler. Not very much code benefits from this, but when you have code that does, it can make a heck of a difference.


答:
Functions with inconsistent or illogical return values. Two good examples:

1) Some windows functions that return a HANDLE use NULL/0 for an error (CreateThread), some use INVALID_HANDLE_VALUE/-1 for an error (CreateFile).

2) The POSIX 'time' function returns '(time_t)-1' on error, which is really illogical since 'time_t' can be either a signed or unsigned type.

Title: API design pitfalls in C

Body:
What are some flaws that drive you nuts in C APIs (including standard libraries, third party libraries, and headers inside of a project) ?  The goal is to identify API design pitfalls in C, so people writing new C libraries can learn from mistakes of the past.

Explain why the flaw is bad (preferably with an example), and try to suggest an improvement.  Although your solution might not be practical in real life (it's too late to fix strncpy), it should give a heads up for future library-writers.

Although the focus of this question is C APIs, problems that affect your ability to use them in other languages are welcome.

Please give one flaw per answer, so democracy can sort the answers.


答:
Functions or parameters with non-descriptive or affirmatively confusing names. For example:

1) CreateFile, in the Windows API, doesn't actually create a file, it creates a file handle. It can create a file, just like 'open' can, if asked to through a parameter. This parameter has values called 'CREATE_ALWAYS' and 'CREATE_NEW' whose names don't even hint at their semantics. (Does 'CREATE_ALWAYS' mean it fails if the file exists? Or does it create a new file on top of it? Does 'CREATE_NEW' means it creates a new file always and fails if the file already exists? Or does it create a new file on top of it?)

2) pthread_cond_wait in the POSIX pthreads API, which despite its name, is an unconditional wait.

Title: API design pitfalls in C


问:
What is an algorithmic programming language?
"... You need to understand the core language: is it algorithmic, functional, object-oriented? ..." - Effective Java, Joshua Bloch, 2ndEd. 2008. Foreword, p xiii

Functional: Lisp, OO: Java, but what is ( would Bloch mean by ) an algorithmic programming language?

答: Perhaps "procedural" is what's intended. Languages like C and Pascal, in which procedures are the main tool for structuring a program, are often called "procedural programming languages." You can think of a procedure as an implementation of an algorithm, so "algorithmic" would seem like a reasonable synonym for "procedural".</p>


答: I assume the author want to speak about imperative programming language. A (quite complete) map of the different programming paradigms and their relationship that a language may support is available here. An important note is that a language may support (more or less well) several paradigms.

Title: What is an algorithmic programming language?

Body:
"... You need to understand the core language: is it algorithmic, functional, object-oriented? ..." - Effective Java, Joshua Bloch, 2ndEd. 2008. Foreword, p xiii

Functional: Lisp, OO: Java, but what is ( would Bloch mean by ) an algorithmic programming language?


问:
What are pros and cons of using temporary "references"?
In C and C++ (and I guess other languages that allow taking a "reference" to an array element or something similar), when you have an array like type, accessing individual elements of such an array can be done "directly" or via a temporary reference or pointer.

Example:

```<code>// Like this:
for(int i=0; i<n; ++i) {
   theArray[i].frobnicate();
   theArray[i].shrub();
   if(i % 2) {
      theArray[i].modulize();
   }
}

// Or like this:
for(int i=0; i<n; ++i) {
   TheType& elem = theArray[i];
   elem.frobnicate();
   elem.shrub();
   if(i % 2) {
      elem.modulize();
   }
}
</code>```

Obviously if the loop body becomes too complex some refactoring should be used and the whole access moved to a separate function/method that would naturally operate on a single element of the array, but for cases where there are few acesses that are only used in one loop, it may be more convenient to keep them directly in the loop.

We have been debating which form we should prefer in our team and opinions are mixed, therefore I'm interested in whether there exist some guidelines, especially wrt. C++.

Edit: This is purely about style if you will. Performance is irrelevant, as our C++ compiler actually should generate exactly the same code in both versions.

答:
Each approach has advantages.

The temporary reference approach has the advantage that you get to name the reference. This can provide additional information to help make the code more self-explanatory. It also eliminates having multiple instances of the same expression to access the variable.

The no-reference approach is one-line shorter. And if you only access the member once or twice, the benefit of eliminating multiple instances is much less.

I've written coding practices documents. If you feel you must have a policy on this, I would suggest noting the advantages of each and recommending the no-reference approach where the code is simple and the reference approach where either the expression would be repeated many times or having the reference named adds to code readability.

You don't have to have a rule for everything, especially where there's no clear major advantage of either approach and no specific problem you're trying to avoid.


问:
Philosophy behind Undefined Behavior
C\C++ specifications leave out a large number of behaviors open for compilers to implement in their own way. There are a number of questions that always keep getting asked here about the same and we have some excellent posts about it:

https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-a-c-programmer-should-know-abo

https://stackoverflow.com/questions/4105120/what-is-undefined-behavior

https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points

My question is not about what undefined behavior is, or is it really bad. I do know the perils and most of the relevant undefined behavior quotes from the standard, so please refrain from posting answers about how bad it is. This question is about the philosophy behind leaving out so many behaviors open for compiler implementation.

I read an excellent blog post that states that performance is the main reason. I was wondering if performance is the only criteria for allowing it, or are there any other factors which influence the decision to leaving things open for compiler implementation?

If you have any examples to cite about how a particular undefined behavior provides sufficient room for compiler to optimize, please list them. If you know of any other factors other than performance, please back your answer with sufficient detail.

If you do not understand the question or do not have sufficient evidences/sources to back your answer, please do not post broadly speculating answers.

答:
I'll give you an example where there's pretty much no sensible choice other than undefined behavior. In principle, any pointer could point to the memory containing any variable, with the small exception of local variables that the compiler can know have never had their address taken. However, to get acceptable performance on a modern CPU, a compiler must copy variable values into registers. Operating entirely out of memory is a non-starter.

This basically gives you two choices:

1) Flush everything out of registers before any access through a pointer, just in case the pointer points to that particular variable's memory. Then load everything needed back into register, just in case the values were changed through the pointer.

2) Have a set of rules for when a pointer is allowed to alias a variable and when the compiler is permitted to assume that a pointer does not alias a variable.

C opts for option 2, because 1 would be terrible for performance. But then, what happens if a pointer aliases a variable in a way the C rules prohibit? Since the effect depends on whether the compiler did in fact store the variable in a register, there's no way for the C standard to definitively guarantee specific results.

OwnerDisplayName: Als

Title: Philosophy behind Undefined Behavior


问:
Group messaging of computers over internet
I want to be able to send messages between computers on the internet network but with minimal functionality

requirement are- 1)computers can join/leave the group (I expect the group size to be a maximum of 5-10) 2)any message generated by any computer will be sent to every other node (this is the main requirement and I have short messages which need to be sent in shortest possible time: suggest network layer protocol to be used here), message wont be resent or ack (except leave)..but I still want to maintain high reliability, can I maintain it without receiving acks?

one problem would be to communicate on the internet I will need some sort of NAT support? how can this be managed without a stun server?

Should I use a p2p library? as I think most of the features they offer wont be needed by me could anyone suggest some here?

I'm working in C++.

答: Why not just use TCP? The server can be a simple relay server or an off-the-shelf IRC server. Do you have some kind of critical latency requirement? Or high throughput requirement? If not, I would just pull the server off the shelf.</p>


问:
What happens when a project switches to a different license?
I've been reading a bit about software licenses, and I'm having trouble getting my head around the idea of what happens when one wants to change the license.  I've read a couple of questions here on the topic and it clarifies things some, but there are still a couple of areas that are unclear to me.

One example:  Suppose I have a project hosted on github with no license specified.  If someone contributes a patch to my code base and I merge it in, does that patch still belong to them?  If so, would I need their permission to change the license on my project?

Another example:  Suppose I have my software under some permissive open source license.  I understand that I am allowed to change the license on my software at will (barring conflicts with contributors), but does that effect existing copies of the software out there?  If I decide to close source my project, do existing copies of the source with packaged OS license remain open source and distributable according to the previous license?

I like the idea of working together with others on projects in a flexible manner, and unless a project actually starts to pick up it seems like unnecessary overhead to go about deciding on an appropriate license.  It would be nice to be more aware of the potential conflicts that could crop up, though.

答:
If you merge a patch from someone, the patch still belongs to them. When you distribute the project, every recipient gets a license to that patch from its author.

Whether you need permission to change the license depends on the original license. For example, if the original license was BSD with no advertising clause, you can switch to GPL because the BSD license permits it. (Weirdly, everyone who gets copy of your project still gets a BSD license to whatever protectable expression is left from that contribution from its original author.) But if the original license was GPL, your license to use the patch is GPL and you can't change it because the GPL does not permit you to add or remove restrictions.

License changes have no effect on existing licenses. Most FOSS licenses are irrevocable, so once you have given me a particular license to a particular piece of code, I have it forever.

It must be that way, otherwise one of your project contributors whose changes are now deep in your code could revoke your license to redistribute your own project. That wouldn't be any fun.

I am not a lawyer. This is not legal advice.


问:
What is the purpose of the "non-endorsement clause" in the New BSD license?
Note: This question is not about the "obnoxious BSD advertising clause".  The New BSD license does not contain that clause, and is compatible with the GPL.

I'm trying to pick between the New BSD license and the MIT license for my own projects.  They are essentially identical, except the BSD license contains the following clause:

Neither the name of the <organization> nor the
  names of its contributors may be used to endorse or promote products
  derived from this software without specific prior written permission.

Why would anyone want to use this clause?  What's wrong with gaining some notoriety if someone makes a well-known piece of software using your code?  Also, wouldn't dictating what users can and cannot do with your given name fall outside the domain of intellectual property?

答: If I add backdoors and vulnerabilities to Linux and distribute the result, the GPL allows me to do it. But we definitely don't want me calling it "Linux" and describing it as "The operating system designed by Linus Torvalds". Linus has a legitimate interest in being able to distinguish the official release, whose quality he controls, from everything else, whose quality he has no control over.</p>


问:
CPOL License. Can I use it on my commercial application without distributing source code?
I'm considering using a project from http://www.codeproject.com that uses the CPOL license. Section 5e says:

"You may distribute the Executable Files and Source Code only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy of the Executable Files or Source Code You distribute and ensure that anyone receiving such Executable Files and Source Code agrees that the terms of this License apply to such Executable Files and/or Source Code. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute the Executable Files or Source Code with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License."

Is not clear to me if I should include their source code with my executable or not. Or even worse, if I should make my own source code available such as with GPL license.

The reason why is not clear to me is because I'm not sure if by compiling their source code together with mine I'm "distributing" either their "Source Code" or "Executable Files"?

答:
Legally, compiling is like stapling. If you staple a copy of a DVD of your wedding to a copy of a DVD of The Phantom Menace, it is legally both your wedding and The Phantom Menace. If you deliver the two DVD's stapled together, you are distributing The Phantom Menace.

Compiling cannot produce a derivative work because a compiler is not creative. Legally, only a creative process can produce a work (with a few exceptions created specifically by statute, none relevant here).

However, if your source code contains protectable expression from the other work, then your source code is a derivative work. When you compile it, it's still a derivative work.  I have read the license twice, and I see no place that it requires you to distribute the source code of derivative works like the GPL does.

Oddly, and for absolutely no reason (it's not legally necessary) the license requires you to get your users to agree to the terms of the license. That's awkward.


答:
If you release software without specifying a license, you are potentially placing any users of your software in a very difficult position.  In some legal jurisdictions, your users would have no clear legal right to use your software in any way.  Don't do this!

If you incorporate someone else's patch into your codebase (with their explicit or implied permission), they retain any copyright on their patches ... unless they have explicitly transferred copyright to you.  This can present problems if you then want to change the licensing terms of the codebase.  I can think of three ways to deal with this:

Make your licensing "GPL x.y or later" (or similar) using the wording recommended for the relevant license.

Make formal assignment of copyright to you (or your project organisation) a precondition for accepting / incorporating patches from other people.

When you want to change the license, attempt to identify and contact all copyright owners to get their permission.  If you can't get their permission, remove their code from the codebase.

If I decide to close source my project, do existing copies of the source with packaged OS license remain open source and distributable according to the previous license?

Yes.  That's what granting an "irrevocable" right means.

In theory you could craft a license that allows you to unilaterally alter the license terms, but it would not be a legitimate OSS license ... and nobody in their right mind would use your software.

Title: What happens when a project switches to a different license?

Body:
I've been reading a bit about software licenses, and I'm having trouble getting my head around the idea of what happens when one wants to change the license.  I've read a couple of questions here on the topic and it clarifies things some, but there are still a couple of areas that are unclear to me.

One example:  Suppose I have a project hosted on github with no license specified.  If someone contributes a patch to my code base and I merge it in, does that patch still belong to them?  If so, would I need their permission to change the license on my project?

Another example:  Suppose I have my software under some permissive open source license.  I understand that I am allowed to change the license on my software at will (barring conflicts with contributors), but does that effect existing copies of the software out there?  If I decide to close source my project, do existing copies of the source with packaged OS license remain open source and distributable according to the previous license?

I like the idea of working together with others on projects in a flexible manner, and unless a project actually starts to pick up it seems like unnecessary overhead to go about deciding on an appropriate license.  It would be nice to be more aware of the potential conflicts that could crop up, though.


问:
I need a true random number generator web service
Random.org provides 200k free random bits (only 6250 32-bit integers!) from the analog world (cf.) per IP per day.

Does anyone know of an alternative web service that provides more on-demand  random bits per day?

(paying is OK as long as the price is "within expectations" of 1000×1024bits per usd cent) (random.org's paid service charges 100× this price)

答:
What you are asking for is Holy water, and you are rejecting the suggestion that you use regular water. The only reason for preferring Holy water over water is religious. There are simple, randomly-seeded PRNGs that cannot be distinguished from true physical randomness by any known process. And these systems are non-deterministic.

A real-world computer has several sources of true physical randomness. For example, a modern x86 CPU has a 'TSC' which measures the instruction cycle count (and thus, indirectly, the time to a resolution of a billionth of a second or so).

You can capture the TSC when a network packet arrives. The low bits of the TSC will depend on the precise offset between the crystal oscillator that times the network interface and the crystal oscillator that runs the CPU. This is dependent on microscopic zone temperature variations in the two quartz crystals that are believed to be truly random.

Similarly, you can capture the TSC when data arrives from the hard drive. The low bits are dependent on turbulent airflow shearing between the hard drive surface and the case. This is also believed to be truly random.

Well-known algorithms, such as the one the Linux kernel uses (developed by Theodore Ts'o based on the work of M. Matsumoto and Y. Kurita) use the avalanche effect to convert a few unpredictable bits into a much larger number. The only differences between the outputs of these algorithms (assuming they are properly seeded by TSC data) and the output of true physical randomness is religious -- no known method can distinguish these outputs. There is no test that one will pass and the other will fail.

I have developed random number generators for online casino use that have achieved independent certification. These methods are the ones used in the real world.


问:
Why isn't SSL/TLS built into modern Operating Systems?
A lot of the basic network protocols that make up the infrastructure of the Internet are built in to most major Operating Systems.  For example, TCP, UDP, and DNS are all built into Linux, UNIX and Windows, and are made available to the programmer through low-level system APIs.

But when it comes to SSL or TLS, one has to turn to a third-party library such as OpenSSL or Mozilla NSS.

SSL is a relatively old protocol, and it's basically an industry standard as ubiquitous as TCP/IP, so why isn't it built into most Operating Systems?

答:
There are obvious benefits to building TCP into the operating system. TCP requires precision timing and rapid response to network packets even when no application data is involved. If you tried to implement TCP in user space on top of a generic IP API, it would be much worse. There are no similar advantages to integrating SSL in the kernel.

On the other hand, there are a few disadvantages. For example, SSL requires manipulating key rings and lists of certificates and the like. Doing that through a kernel or OS API would be inelegant. So even if it came with the operating system, it would just be a library (just like it is in Windows). Those libraries are already available anyway, so it's ultimately just a change in packaging.


问:
Is learning C# as a first language a mistake?
I know there are similar questions on here, which I've read, but I recently read this post by Joel Spolsky:

How can I teach a bright person, with no programming experience, how to program?

And it got me thinking about my way of learning and whether it might actually be harmful in the long run.

I've dabbled with various languages but C# is my first serious one, I've read "Head First C#" and created a few projects. But after reading the post above I've found it a bit disheartening that I may be going about it all wrong, obviously I respect Joel's opinion which is what has thrown me a bit.

I've started reading "Code" as recommended in the reading list and I'm finding it pretty hard going, although enjoyable. I feel like it's taken the shine off of my "noobish hacking about" in Visual Studio.

So now I'm unsure as to what path I should take? Should I take a step back and follow Joel's advice and start reading?

I guess my main aim is just to become a good programmer, like everyone else, but I don't want to be going into bad practice by learning a .NET language when someone who's opinion I respect thinks that it is harmful.

Thoughts?

答:
As much as I advise you to learn many languages (as do the others suggest), make sure you know a (couple of) language(s) you learn very well.

The risk of knowing many languages is that you might never learn a language completely causing frustration when actually wanting to solve a problem.

Knowing the for-loop construction is many languages is fun but useless if you don't know how to handle errors in any of them.


答:
Try 4 simple steps:

Use Hide Main Menu extension.

Remove all toolbars. Use short-cuts instead. I find myself that I actually never use the toolbars.

Set Auto-Hide for all panels except the Source Code window.

Use scroll wheel to zoom the text.


问:
How do I safely write code in my own 'words' and not plagiarize?
I understand plagiarism and paraphrasing fairly well when it comes to writing a research paper, but those equivalent areas in programming seem foreign to me. I've looked up the topics online, and surprisingly there is not as much material on the subject as one would have expected.

When writing code and having to implement something I've never implemented before, I'll go online to look for an example. I try to read through the documentation beforehand, but sometimes I find it challenging to follow. So if that fails, I will search for the topic online and be presented with dozens of examples (whether they be on someone's personal blog or a Q&A site like SO). Now I'm usually presented with 5-10 lines of code. I have and will NEVER copy-and-paste that into my own code, but I still worry about copying it down verbatim. I find it hard to reword a certain piece of code, especially when there are only so many ways to do so. I make sure to rename variables, change formatting, etc. - but is this enough?

I've always wanted to understand this topic, but now that I'm working with a new language and in a corporate environment I think that it is especially pertinent. If anyone could explain or link to a good explanation elsewhere, I would greatly appreciate that!

tl;dr
I don't understand how much you have to change and reword 5-10 snippets of code found online to avoid plagiarism. What if there is very little that you can change?

答:
If you're not coding in an academic environment, why would you worry about plagiarism? In a professional environment, it only matters if you plagiarize other employees in your company. Plagiarism is about who gets credit. In any event, the solution to plagiarism is simple -- anything you take, give credit to the original author. If it was from a web page, include the URL. This benefits you, because if you have any questions, you may be able to find the original source again.

If your question is really about copyright infringement, remember that copyright doesn't cover functional aspects. It only covers creative choices where there are very large number of equally-useful choices. If you can't easily change the code without breaking the functionality, then it's not something copyright covers (under the merger or scènes à faire rule).

OwnerDisplayName: Anonymous


问:
Need to make a stock inventory application
I need to make an application for my dad to keep track of stock trading inventory. He trades shares for himself and for his clients and would like to keep the records, things like buy/sell price of shares, profits, loss, date etc etc for his shares and his client shares and would like various kind of reports/views.

He uses windows. I want to provide a local html page where he will enter new information and this should go to a local database and from his html page, he can choose reports etc and the reports will be displayed on the webpage etc..

I am thinking of using struts (and windows,tomcat) and mysql to make this application. I know some stuff from college days, but would look into the tutorials to setup things and program.

Does this selection of technology looks good enough or something more easier and equally good exist?

update:

This is what I have settled for: Used mysql/windows, navicat lite and populated database/tables, and wrote some procedures taking some inputs. Like one procedure takes date and stock name as input and gives you quantity you have of that stock by that date and profit/loss so far, effective buy price of each share of that stock. This is for individual basis usage..and it looks like this will suffice for now -- very very simple, but I could custom create tables,custom create queries/procedures..Dad gets "contract notes" from his broker containing his daily transactions and I could get these notes online, compile these of last 2-3 years into one table and so the thing is in working state..very primitive, but works for his requirements for now.
and yes, made 2 accounts (one read-only priviledge account using which he will run his queries,procedures etc) and other root, which he will use when populating his tables say once or twice in 15 days.

答: I would recommend to use Play Framework with Java and MySQL for this. It's a typical database oriented application, so you should design the database schema carefulle before you start coding. Play Framework is a Java web framework with a short development cycle, just save your source code and update your web page - inpired by Ruby on Rails. </p>


问:
What's the difference between working at a software company and a company whose focus is in another field?
Recently, I was approached by a local ad agency with a job opportunity. They are bringing all web/interactive development in-house and adding to their development team.

I'm growing sick of my cushy, yet boring corporate job, and am intrigued by the position.

Having only worked for software shops where the primary business was making software, I worry that they may not put emphasis on quality software practices, since development is not the focus of their business.

Could anyone with experience at both compare/contrast working at a software company with working at a company that just happens to have an in-house software development team or department?

答:
There's already some great answers here, but I'd just like to reference a link to the transcript of the 2nd part of a talk that Joel Spolsky gave at Yale University:

Joel Spolsky - Talk At Yale Part 2 of 3

There he talks about the difference between "in-house" programmers and programmers that work in software/technology companies.

His three main points are:

When you're an in-house programmer, you never get to do things the
right way. You always have to do things the expedient way.

As an in-house programmer, once some software is “good enough,” you
stop working on it.  When you develop software "products," you get to
make them beautiful.

When you’re a programmer at a software company, the work you’re doing
is directly related to the way the company makes money.  That means,
for one thing, that management cares about you.

Personally, I've worked at both software companies and non-software companies throughout my career, and although there are always exceptions to every rule, I do agree with Joel's points as the vast majority of companies seem to be in accordance with them.


问:
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?

答:
I would say counting them is a mistake. There is no way you can grind something like that down to a number. However, if a particular developer's code seems to have more problems than similar code written by others, and this is a consistent pattern, then I would say that developer is probably not as good, all other things being equal. It's a fact to be put into the mix.

In any event, I've been in this business for decades, and I can't say I've ever seen a programmer who had an unusually high or unusually low bug rate. I've seen programmers who were faster or slower, programmers who could get jobs done or who ran into trouble. I've seen programmers who naturally write very easy to understand code, very fast code, or very confusing code. But I've never seen a programmer with an atypically high or low bug rate. Maybe I just haven't been paying close enough attention.