答:
Well I tend to make comments in several general areas and each type might be handled differently.

Required changes. These are the kinds of changes where I point out that the code doesn't meet the functional requirements or doesn't work and must be fixed before being pushed to production. I tend to be very straightforward in these comments. The requirements says..., this does not do that. Or this will fail if the value sent in is null (especially when you know that case will occur based on the data that will get sent in).

Then there are the "this works but here is a better way to accomplish that" comments. You have to be more gentle in these and do more of a sales pitch. I might say that I would do this instead because it is likely to be better performing (I generally review SQL code where performance is very important). I might add some details about why it is a better choice just like I would do in answering a question on Stack Overflow. I might point out that it isn't required to change this for this particular code, but to consider the change in future coding. Basically with these types of comments I am educating people with less experience on what might work better.

Then there are the "this works but we do things this way" comments. These will probably also be required changes. These would include comments about company standards or the architecture we expect them to use. I would reference the standard or architecture document and tell them to fix to the standard. The comment would be straightforward but neutral, it is missing thus and so or the variable names don't conform to our naming standard or simliar things. For instance, our architecture for SSIS packages requires the package to use our metadata database to store particular information about the package and requires particular logging. The package would work without these things but they are required for company reasons (we need to report of the success rate of imports for instance or analyze the types of errors we receive.)

The one thing you don't want to do in code review comments is personally attack someone. It can also help if you find something they did well and point out that was good. Sometimes I learn something new from a code review and if I did I tell the person that.

Title: What's the best way to comment in a code review?

Body:
My team just started using crucible/fisheye for initiating code reviews whenever one of us checks something in. There are only 3 of us, and we're each encouraged to review the code and leave comments where we see fit.

My question is, how do I best leave a comment on a line of code I see a problem with? I want to get my point across without seeming abrasive.

I don't want to seem like I'm on a high horse and say "I've been doing it this way...
and I also don't want to seem like I'm trying to be authoritative and say something like "This should be done this way..." but I still need to get the point across that what they're doing is not very good.

To Clarify:
This is a really good resource for what I should be looking to comment on: Is a code review subjective or objective (quantifiable)?, but I'm looking for how to comment on it.


问:
What's the best way to comment in a code review?
My team just started using crucible/fisheye for initiating code reviews whenever one of us checks something in. There are only 3 of us, and we're each encouraged to review the code and leave comments where we see fit.

My question is, how do I best leave a comment on a line of code I see a problem with? I want to get my point across without seeming abrasive.

I don't want to seem like I'm on a high horse and say "I've been doing it this way...
and I also don't want to seem like I'm trying to be authoritative and say something like "This should be done this way..." but I still need to get the point across that what they're doing is not very good.

To Clarify:
This is a really good resource for what I should be looking to comment on: Is a code review subjective or objective (quantifiable)?, but I'm looking for how to comment on it.

答:
It depends on what sort of problem has been noticed

missing copywrite notice - a common and boring issue just a brief comment stating the issue and move on

places where I might do it differently - usually tend to ask questions here rather than make statements, sometimes the answers will justify the original solution other times not and then I can address those more explictly

places where there is a clear defect e.g. Equals override that can stackoverflow - reach for the red pen - mark it as a defect and be very explicit as why it is broken - also check other similar areas to check there has not been a systematic problem.

ContentLicense: CC BY-SA 3.0


问:
How to build a good service layer in ASP.NET?
I have looked through some questions, technologies for building a good service layer but I have some questions regarding this that I need help with.

First some information of what I have for requirements. We currently have a number of web applications that talk to each other in a spiderweb looking way (all talking to each other in a confusing way via webservices and database data).

We want to change this so that all applications go through a service layer where we can work more with cache and encapsulate common functionality and more.

We want this layer to also have a Web API so that 3rd party clients can consume information from the service.

The problem I see is that if we build the service layer with say MVC4 Web API don't we need to communicate between the application using the webAPI meaning we have to construct URLs  and consume JSON/Xml. That does not sound too effective. I assume a better method would be working with entities and WCF to communicate between the application but then we might loose the Web API magic?

So the question is if there is a way to consume a service layer as both a Web API (JSON/XML) and as a more backend service layer with entities. If we are forced to use 2 different service layers we might have to duplicate some functionality and other bad things.

Hope the question is clear enough and please ask if you need any more information.

答:
For a set of applications that are hosted on intranet and possibly in one LAN, the best can be a TCP connection for services.

In that sense, I shall suggest, creating a service application that expose a set of endpoints and service interfaces that can work on TCP. These can be consumed by the home-grown or trusted applications.

The service application whould have another set of endpoints and service interfaces that are exposed for consuming over web (web API).

So the service application can be hosted using WCF and endpoints/interfaces shoukd be added in accordance to the need.

OwnerDisplayName: Swippen

OwnerDisplayName: Kangkan


问:
Why the recent shift to removing/omitting semicolons from Javascript?
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?

答:
I recently wrote a parser/analyzer for JavaScript, where I had to painstakingly implement ASI, and I also have my copy of Crockford's JavaScript: The Good Parts on my bookshelf, which advocates always using semicolons.  The intention was good, but it doesn't always help in practice.

Obviously, the people writing frameworks like jQuery, zepto, etc. are JavaScript syntax masters and thus they know the difference between:

```<code>return
{
    status: true
};
</code>```

and

```<code>return {
    status: true
};
</code>```

JavaScript, while powerful, is also a beginner's language and good luck explaining this to someone who is just learning what a for loop is.  Like introducing most people to a new skill, there are some more complex things you don't want to explain right away, so instead you choose to instill a "cargo cult" belief in certain things just to get them off the ground.  So, you have two choices when teaching a beginner how to write JavaScript:

Tell them "follow this one rule and don't ask why", telling them to put a always semicolon at the end of every line.  Unfortunately, this doesn't help in the example in the above, or any other example where ASI gets in the way.  And Mr. or Ms. beginner programmer gets befuddled when the code above fails.

Tell them "follow these two rules and don't ask why", telling them not to bother with semicolons at the end of every line, and to instead always a) Follow return with a {, and b) When a line starts with a (, prepend it with a ;.

Choosing option 2 is a better set of "cargo cult" rules to follow (will result in very few ASI-related bugs), and even if you do get a deep understanding of the topic, you have fewer unneeded characters on the screen.

Body:
I recently wrote a parser/analyzer for JavaScript, where I had to painstakingly implement ASI, and I also have my copy of Crockford's JavaScript: The Good Parts on my bookshelf, which advocates always using semicolons.  The intention was good, but it doesn't always help in practice.

Obviously, the people writing frameworks like jQuery, zepto, etc. are JavaScript syntax masters and thus they know the difference between:

return
{
    status: true
};

and

return {
    status: true
};

JavaScript, while powerful, is also a beginner's language and good luck explaining this to someone who is just learning what a for loop is.  Like introducing most people to a new skill, there are some more complex things you don't want to explain right away, so instead you choose to instill a "cargo cult" belief in certain things just to get them off the ground.  So, you have two choices when teaching a beginner how to write JavaScript:

Tell them "follow this one rule and don't ask why", telling them to put a always semicolon at the end of every line.  Unfortunately, this doesn't help in the example in the above, or any other example where ASI gets in the way.  And Mr. or Ms. beginner programmer gets befuddled when the code above fails.

Tell them "follow these two rules and don't ask why", telling them not to bother with semicolons at the end of every line, and to instead always a) Follow return with a {, and b) When a line starts with a (, prepend it with a ;.

Choosing option 2 is a better set of "cargo cult" rules to follow (will result in very few ASI-related bugs), and even if you do get a deep understanding of the topic, you have fewer unneeded characters on the screen.


问:
Syntax logic suggestions
This syntax will be used inside HTML attributes. Here are a few examples of what I have so far:

```<code><input name="a" conditions="!b, c" />
<input name="b" />
<input name="c" />
</code>```

This will make input "a" do something if b is not checked and c is checked (b and c  are assumed to be checkboxes if they don't have a :value defined)

```<code><input name="a" conditions="!b:foo|bar, c:foo" />
<input name="b" />
<input name="c" />
</code>```

This will make input "a" do something if bdoesn't have foo or bar values, and if c has the foo value.

```<code><input name="a" conditions="!b:EMPTY" />
<input name="b" />
</code>```

Makes input "a" do something if b has a value assigned.

So, essentially , acts as logical AND, : as equals (=), ! as  NOT, and | as OR. The | (OR) is only needed between values (at least I think so), and AND is not needed between values for obvious reasons :)

EMPTY means empty value, like <input value="" />

Do you have any suggestions on improving this syntax, like making it more human friendly? For example I think the "EMPTY" keyword is not really appropriate and should be replaced with a character, but I don't know which one to choose.

答:
Symbols as you use are compact, but they are not friendly. If you are aiming this meta language at developers, then I think it is reasonably simple, as it is based upon punctuation familiar to programmers.

But that is not your aim. You appear to be targeting this language at end users or designers, in which case your syntax is not simple at all. They have no background to imply that ! = not, | = OR.

I would think hard about your target market, and try to find a language that they know (CSS perhaps?) and base your metalanguage around the idioms used in a language they are familiar with, or on basic English and Math (or, and, not, =).

While I cannot be sure that this is appropriate for your end users (that is your call, not mine) I would think that something like this would be a better fit for non-programmers. These are re-writes of the exact examples you used.

b = FALSE, c = TRUE

NOT b = foo OR bar, c = foo (alternately: b = NOT foo, b = NOT bar, c = foo if you don't want to support NOT on the left side of the expression)

b = NOT BLANK

You may choose to identify your reserved words differently than CAPS as I used ($or, $blank, $true), but the aim is to be expressive, not compact.

Title: Syntax logic suggestions


问:
Model View Presenter for WebForms and Winforms
I have a windows forms project using the Model View Presenter pattern and would like to build a web forms project on top of the same MVP structure.

The windows forms project knows nothing of ASP.Net Membership and just communicates via the presenter to the model and then to the business layer to do user log on/validation.  In the web forms project I have created custom classes that inherit from the built in membership and role provider classes so that I can use the existing user and roles tables as well as integrate nicely with the ASP.Net login controls.  However, currently I have had to reference the business layer directly in the custom membership class to validate users, so if I follow MVP, the membership code shouldn't be in the view with references to business layer, it should be in the model but that means referencing System.Web.Security in the model.

Is there a way to still use ASP.Net membership with MVP where the webforms and winforms projects are built on top of the same MVP structure?  I think I need to pass in the dependency on membership to the presenter and then to the model but can't quite see a clean way to do this.

One of the commonly mentioned benefits of MVP is that it allows for building different UI's on top of the same presenters, models, etc.  However, in practice, does this really work well or is it best to implement MVP separately per UI technology?

Also in relation to the web forms project, is Session state something that the view can just deal with or does this need wrapping with a custom class and interface and passing to the presenter to maintain?

答:
I was thinking of something like this.

Where "Webforms User Stuff" would depend on System.Web.Security and "Generic User Stuff" would have your flavor of access control.  Don't directly use ASP.NET membership but use composition.


问:
Do you spend your working hours on learning?
Do you spend your working hours learning new stuff, reading tech blogs, books on programming etc.? What's your opinion on it? Can an employer have benefits allowing developers to spend about 1-1.5 hrs a day on learning. Will it be repaid in future (with better productivity etc.)?</p>

答:
For me, programming is learning. Every time I write a method I can learn something:

Is this the best way to do this?

What is the memory/CPU usage?

What are the trade-offs?

What are the potential problems that could make this method fail? (deadlock, dropped connection, etc.)

Does this method need to be part of a library so I can reuse it later?

How can I explain this system in non-technical terms so that anyone can understand it?

How will I remember and organize everything I just learned?

Every time I go on Programmers.SE or Stack Overflow I learn something.

I think that being a programmer is all about learning. And, everything that we learn can be used to make us better programmer and help make the projects that we work on succeed.


问:
How to deal with tautology in comments?
Sometimes I find myself in situations when the part of code that I am writing is (or seems to be) so self-evident that its name would be basically repeated as a comment:

```<code>class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

(C# example, but please refer to the question as language-agnostic).

A comment like that is useless; what am I doing wrong? Is it the choice of the name that is wrong? How could I comment parts like this better? Should I just skip the comment for things like this?

答:
///  blocks are used for generating documentation for IntelliSense and API documentation.

Thus, if this is a public-facing API, you should always include at least a  comment, even if the purpose of the function should be self-evident to readers.

However, this is the exception to the rule; in general, just remember to DRY (Don't Repeat Yourself).

Title: How to deal with tautology in comments?

Body:
/// <summary> blocks are used for generating documentation for IntelliSense and API documentation.

Thus, if this is a public-facing API, you should always include at least a <summary> comment, even if the purpose of the function should be self-evident to readers.

However, this is the exception to the rule; in general, just remember to DRY (Don't Repeat Yourself).


问:
Why rails use yaml to config database instead of plain ruby code?
Most of configuration files in ruby such as Gemfile, gemspec, are just ruby code itself. Why database configuration file in rails is the exception?</p>

答:
My guess:

For configuration of a common module across environments it is the most concise way of doing so.  To do it in Ruby adds more complexity to the file.

You would have to ask the original designer though to get the real answer.


答:
I want to get my point across without seeming
  abrasive.

Don't confuse terseness with being abrasive.  When something is a problem, document it in a way that whoever is going to fix it can understand.  Stick to the facts and don't write an essay.  To wit:

This will cause the frobnitz to malfunction when fooble is within 5 grimbles of the snorgatz factor.

The established convention for doing this is to call fazzatz() with a freshly-initialized Squidge.  Make this into a method so it always happens the same way and isn't duplicated.

I also don't want to seem like I'm trying to be authoritative
  and say something like "This should be done this way..." but
  I still need to get the point across that what they're doing is
  not very good.

The purpose of reviewing code is to put a second, usually-more-experienced, pair of eyes on it to ferret out problems.  If you're in the position of passing judgement on others' work and there's a valid reason to say something isn't good, you'd be neglecting your responsibility as a reviewer if you didn't.

There will be disagreements, and those are opportunities for the reviewer and reviewee to defend their positions.  If you're otherwise peers and you reach an impasse, find someone senior to break the tie.


问:
creative & complex vs simple and readable
Which is a better option?

It's not always that when you have something creative your code is going to look ugly.

But at times it does go a bit ugly.

e.g.

```<code>if ( (object1(0)==object2(0) &&
     (object1(1)==object2(1) &&
     (object1(2)==object2(2) &&
     (object1(3)==object2(3) )
    retval = true;
else
    retval = false;
</code>```

is simple and readable

```<code>bool retValue = (object1(0)==object2(0)) &&
                (object1(1)==object2(1)) &&
                (object1(2)==object2(2)) &&
                (object1(3)==object2(3));
</code>```

but having something like this will make some newbies scratch their heads.

So what do I go for? including simple code everywhere might sometime hamper my performance.

What I could think of was commenting wherever necessary but at times you get too curious to know what is actually happening.

答:
including simple code everywhere might sometime hamper my performance.

Don't prematurely optimize. Readable code is likely maintainable code. It is easier to optimize maintainable code, than to maintain unreadable (but fast) code.

That being said, both of your examples are less than readable. iterating through (as in @Useless's) answer, might help.


答:
From my experience:

Always have the author of the code with you while reviewing his
code. Preferably the code is projected on the whiteboard and both of
you can clearly see the code very well.

Have a friendly conversation. Appreciate the good part of the
    coding. Tell him that "this is the best I have seen" if you see some
    good parts in the code.

Ask him to review your code and accept and agree to the valid
    points and correct him. Give respect for his comments in your code
    and he will automatically give respect to your code review comments.

Deal with at the developer level unless it is very important or
    more time is needed to correct the code review problems. Don't escalate to
    managers for simple if condition missing issues.

Look with the perspective of "Learning from other code" instead
    of pointing mistakes in the code.

During the code review sessions, quote the past mistakes that you
    have made and how code reviews helped you and avoided big production
    issues because another set of eyes helped you.

Be humble. More appreciation and less comments to him :) You will
    learn a lot during code review and he will also gladly accept your
    comments.


问:
Can we set up svn server on a local computer without any network access?
I want to set up an SVN repository on my computer without any network access. I am working on a code without any collaborator, so I don't want it to be publicly available.

I read this post, but it suggests using online SVN repository services that give free repositories. In that case, my code will be publicly available (as is included in the terms of free plans).

So I was wondering if I can set up a local server on my Windows XP machine that only I access even when I don't have any internet connection?

答:
The easiest way to set up a local server is to use svnserve:

Subversion includes Svnserve - a lightweight stand-alone server which uses a custom protocol over an ordinary TCP/IP connection. It is ideal for smaller installations, or where a full blown Apache server cannot be used.

You don't actually need a subversion server though, if all you want to do is access the repository locally, since you can access a subversion repository via a file URL, as described in this answer:

You can access the repository using file:// protocol so you will only need Tortoise SVN installed and nothing else. See this question in FAQ: Is it possible to use TortoiseSVN without a server?

You can even have the repository in the usb device so that you can take the source with you and work on in from other computers.

If you are using TortoiseSVN, then you can find instructions at Creating The Repository With TortoiseSVN:

Open the windows explorer

Create a new folder and name it e.g. SVNRepository

Right click on the newly created folder and select TortoiseSVN → Create Repository here....

Immediately above on this page also describes how to create a repository from the command line.

Having said that, I would recommend that you have a look at Mercurial or Git as an alternative to svn though. If you are familiar with TortoiseSvn then you will find TortoiseHg and TortoiseGit an easy transition, plus it gives you the flexibility to work in a distributed way later if you need to. For instance in the past I've used memory sticks to transfer hg repositories between machines without network access, and when you work this way you get a free backup into the bargain.


答:
Lets try an answer that recommends generic solutions rather than specifics.

Firstly yes, you can use Subversion on a standalone computer - you can install the server locally or you can work with file://

But unless there is a very good reason why you have to use subversion I would suggest that this is not the best solution to the problem of local version control - not least because it fails one of the things that I regard as essential i.e. ensuring that you source code is in at least two places (yes, even for personal stuff). I would therefore suggest use of a Distributed Version Control System (DVCS).

One of the benefits of DVCS is that, once the tools are installed, repositories are self contained within a folder and you can sync content between different folder containing the "same" repo so long as you have file level access. You also have the option to talk to "server" versions of those repos (that are either privately hosted or that are available as a service). This makes life a lot easier running everything locally.

There are other advantages to DVCS too.

As I already noted, I don't think you really have a proper VCS solution 'til your code is on at least two machines (specifically two distinct hard disks and ideally in more than one location - although cloning and pushing to say USB stick or "cloud" storage (skydrive, dropbox, et al) is another way that should work as well).

In terms of which DVCS - I would look at Mercurial (Hg) and Git and also at Veracity. I use Mercurial because its still nicer on windows...

If you terms of hosted services I do actually agree that there is an awful lot to commend github - but there are also a lot of nice things about bitbucket and Fogbugz/Kiln... and the same is probably true of a lot of other services which I haven't listed (e.g http://beanstalkapp.com/ which was mentioned in passing to me on twitter earlier today)

Title: Can we set up svn server on a local computer without any network access?

Body:
I want to set up an SVN repository on my computer without any network access. I am working on a code without any collaborator, so I don't want it to be publicly available.

I read this post, but it suggests using online SVN repository services that give free repositories. In that case, my code will be publicly available (as is included in the terms of free plans).

So I was wondering if I can set up a local server on my Windows XP machine that only I access even when I don't have any internet connection?


答:
Simplest (and fastest) server, which you can use for work with local repository, embedded into every svn-client. This is server for accessing any repository and any amount of repositories, existing on local filesystem, using protocol file:///. It doesn't provide any authorization or authentication methods, grant only full unlimited access to repository under control, but, from other side, it allows to use and gives all features of VCS-system per se.

In order to use this server, you have in any empty directory in any location call CLI-command svnadmin with the corresponding subcommand and parameters (I can't recall, are there administrative programs in the CLI-client bundle or not and can't check it - I haven't installed CLI svn-client, only TortoiseSVN, which have these programs in installer in version  1.7) - I hope, you'll be able to find it.

svnadmin help show us all available subcommands, we are now interested in subcommand create.

svnadmin help create provide all needed for us details

```<code>create: usage: svnadmin create REPOS_PATH

Create a new, empty repository at REPOS_PATH.

Valid options:
...
</code>```

At starting point for first repo we can ignore all fine-tune options and remember only main form svnadmin create REPOS_PATH, there REPOS_PATH is absolute or relative path to empty directory, planned for repo. Because most time ordinary Windows-people for cross-platform application may people may be confused, which notation (forward- or backslashes) to use in path (metoo), the safest way is cd to location, from which our dir is visible without long path - parent of future repo-directory or the directory itself.
For planned for repo z:\Main before svnadmin create

```<code>Z:
cd \Main
</code>```

and, at last,

```<code>svnadmin create .
</code>```

As result we get created empty repository in directory, which shown in Windows Explorer with special icon as content-indicator

Now, every time when this repository is needed, we use usual SVN-commands, there URL-part or parameters seems as file:///Z:/Main

```<code>c:\>svn ls file:///Z:/Main
branches/
tags/
trunk/
</code>```

(I added standard repository tree in repo).

Let's dissect this strange URL:

file:///, as for any URL, means access-protocol, in our case protocol is special, and have three, not two slashes

Z:/Main is full path to repo with drive and path inside drive, there all Windows-backslashes replaced by "classic" forward-slashes

From any other point this repository haven't any differences from "Big Brothers" with special Subversion-servers

Body:
Simplest (and fastest) server, which you can use for work with local repository, embedded into every svn-client. This is server for accessing any repository and any amount of repositories, existing on local filesystem, using protocol file:///. It doesn't provide any authorization or authentication methods, grant only full unlimited access to repository under control, but, from other side, it allows to use and gives all features of VCS-system per se.

In order to use this server, you have in any empty directory in any location call CLI-command svnadmin with the corresponding subcommand and parameters (I can't recall, are there administrative programs in the CLI-client bundle or not and can't check it - I haven't installed CLI svn-client, only TortoiseSVN, which have these programs in installer in version  1.7) - I hope, you'll be able to find it.

svnadmin help show us all available subcommands, we are now interested in subcommand create.

svnadmin help create provide all needed for us details

create: usage: svnadmin create REPOS_PATH

Create a new, empty repository at REPOS_PATH.

Valid options:
...

At starting point for first repo we can ignore all fine-tune options and remember only main form svnadmin create REPOS_PATH, there REPOS_PATH is absolute or relative path to empty directory, planned for repo. Because most time ordinary Windows-people for cross-platform application may people may be confused, which notation (forward- or backslashes) to use in path (metoo), the safest way is cd to location, from which our dir is visible without long path - parent of future repo-directory or the directory itself.
For planned for repo z:\Main before svnadmin create

Z:
cd \Main

and, at last,

svnadmin create .

As result we get created empty repository in directory, which shown in Windows Explorer with special icon as content-indicator

Now, every time when this repository is needed, we use usual SVN-commands, there URL-part or parameters seems as file:///Z:/Main

c:\>svn ls file:///Z:/Main
branches/
tags/
trunk/

(I added standard repository tree in repo).

Let's dissect this strange URL:

file:///, as for any URL, means access-protocol, in our case protocol is special, and have three, not two slashes

Z:/Main is full path to repo with drive and path inside drive, there all Windows-backslashes replaced by "classic" forward-slashes

From any other point this repository haven't any differences from "Big Brothers" with special Subversion-servers


答:
There are quite a few SVN hosting companies that offer a free account for one or two developers and don't require that your code be public. Check the linked chart for $0 fee, OSS Required = NO. I count nine providers that meet those criteria right now.

While you can certainly host your own repository very easily, there are some benefits that come with using a provider:

You can access your code from anywhere with no extra setup.

Keeping your code off-site protects you from hard disk crashes, fires, etc.

Low administrative overhead.


答:
I think that both your examples are simple and readable. In general, I follow the Occam's razor or KISS principle: do not use a concept
that is more difficult to understand unless you have some real gain from it.

In other words, the problem you are trying to solve is probably complex enough,
do not make your solution even more complex. I would add that sometimes a simple solution requires a deeper analysis and much more creativity than a complex one.

I think these principles are particularly important if

You are working in a team: other programmers are going to have to read your code. They all know you are a good programmer already, no need to show off, just make it simple and readable.

You are developing something you have to deliver in time and according to some quality requirement: do not add extra complexity that you will have to manage yourself sooner or later. Customers won't read your source code.

On the other hand, if you are coding for your own fun and you want to try
out new stuff, then do what you like better.

Just my 2 cents.

Title: creative & complex vs simple and readable

Body:
Which is a better option?

It's not always that when you have something creative your code is going to look ugly.

But at times it does go a bit ugly.

e.g.

```<code>if ( (object1(0)==object2(0) &&
     (object1(1)==object2(1) &&
     (object1(2)==object2(2) &&
     (object1(3)==object2(3) )
    retval = true;
else
    retval = false;
</code>```

is simple and readable

```<code>bool retValue = (object1(0)==object2(0)) &&
                (object1(1)==object2(1)) &&
                (object1(2)==object2(2)) &&
                (object1(3)==object2(3));
</code>```

but having something like this will make some newbies scratch their heads.

So what do I go for? including simple code everywhere might sometime hamper my performance.

What I could think of was commenting wherever necessary but at times you get too curious to know what is actually happening.


问:
Bug reopen vs. new
A bug was opened, fixed, verified and closed. A month later, it showed up again in a subsequent version after several iterations without any regression.

Provided the bug characteristics are the same, would you reopen the existing bug ID or open a new one with a link to the closed bug?

答:
I agree with the previous posters' suggestion to open a new bug since it may not end up being the same root cause.

My further recommendation would be to ensure you're always adding unit and integration tests that cover the bug so that in future versions you catch the problem right away before it goes out to your clients.  Nothing looks worse to a client then seeing the same bug come back.

Title: Bug reopen vs. new


问:
What makes C so popular in the age of OOP?
I code a lot in both C and C++, but did not expect C to be the second most popular language, slightly behind Java.

TIOBE Programming Community Index

I'm curious as to why, in this age of OOP, C is still so popular? Note that 4 out of the top 5 popular programming languages are "modern", object-oriented capable languages.

Now, I agree that you can use OOP in C to some extent, but it's sort of painful and inelegant (well at least compared to C++ I guess). So, what makes C so popular?  Is it efficiency; being low-level; the vast majority of libraries that already exist or something else?

答: I'm surprised that no one has mentioned Worse Is Better yet. It's over 20 years old at this point, but still eminently worth reading. While at times slightly tongue-in-cheek, it does a very good job of outlining how and why the expedient often wins over the ideal, using C (pitted against LISP) as one of its central examples.</p>


答:
In most projects I work on, there isn't a significant amount of time to write detailed comments on every single class member.

That doesn't mean there isn't time for comments; on the contrary, there's plenty of time for tautological comments that puke back a rephrased version of whatever's being commented. They work great as a starting point.

Especially given Visual Studio's usage of comments accompanying IntelliSense, it's a good idea to start with a short bit of information about the field:

```<code>class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

And then as you continue to code, when you can't remember whether UpdateLocation was the location that the update took place, or the location that the update is being sent to, you'll have to revisit the code. It is at this point that you should add that additional information:

```<code>class Example
{
    /// <summary>
    /// The Uri location where the update took place.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

If ever another programmer asks you about details on a field, update the comments with that information:

What sort of update should Example.UpdateLocation be used to store?

```<code>class Example
{
    /// <summary>
    /// The Uri location where the Foo update took place.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

Just like a program has bugs, good comments have bugs that need to be iteratively worked out. The purpose of comments is to assist in understanding code when you revisit it six months later and can't remember anything about how the program works.

And just like programming, your comments have to start somewhere. Tautological comments are the Hello World! of comments, as you practice writing and updating documentation, your starting documentation will become more and more resilient.

Title: How to deal with tautology in comments?

Body:
Sometimes I find myself in situations when the part of code that I am writing is (or seems to be) so self-evident that its name would be basically repeated as a comment:

```<code>class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

(C# example, but please refer to the question as language-agnostic).

A comment like that is useless; what am I doing wrong? Is it the choice of the name that is wrong? How could I comment parts like this better? Should I just skip the comment for things like this?

Body:
In most projects I work on, there isn't a significant amount of time to write detailed comments on every single class member.

That doesn't mean there isn't time for comments; on the contrary, there's plenty of time for tautological comments that puke back a rephrased version of whatever's being commented. They work great as a starting point.

Especially given Visual Studio's usage of comments accompanying IntelliSense, it's a good idea to start with a short bit of information about the field:

class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

And then as you continue to code, when you can't remember whether UpdateLocation was the location that the update took place, or the location that the update is being sent to, you'll have to revisit the code. It is at this point that you should add that additional information:

class Example
{
    /// <summary>
    /// The Uri location where the update took place.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

If ever another programmer asks you about details on a field, update the comments with that information:

What sort of update should Example.UpdateLocation be used to store?

class Example
{
    /// <summary>
    /// The Uri location where the Foo update took place.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

Just like a program has bugs, good comments have bugs that need to be iteratively worked out. The purpose of comments is to assist in understanding code when you revisit it six months later and can't remember anything about how the program works.

And just like programming, your comments have to start somewhere. Tautological comments are the Hello World! of comments, as you practice writing and updating documentation, your starting documentation will become more and more resilient.


答:
Comments should be used to do one of the following.

Information for document generators to grab. This can't be understated, this is extremely important.

Warnings to why a piece of code is the way it is, and what other considerations. I've dealt with code written in 2 programming languages. One key part of this was to have a common structure between the two languages. A comment at both locations informing the user that if they change this number, they also need to change another is extremely helpful.

Write notes to explain why a particularly weird looking piece of code is the way it is. If you had to think about how to get a piece of code to work in a particular way, and the solution isn't evident from the beginning, it's probably worth an explanation as to what you were trying to do.

Labeling inputs/outputs, if they aren't clear. It's always good to know what your inputs are expected to be, and what format they are in.

Comments should not be used to do the following:

Explain things that are extremely obvious. I once saw legacy code like this: page=0; // Sets the page to 0. I think any competent individual could figure that out.

Title: How to deal with tautology in comments?


问:
How do I prevent useless content load on the page in responsive design?
In responsive design, elements are hidden in the page with @media queries and display: none in CSS.

Ok.

In my design however browsers that have less than 800px in width should avoid loading some content at all.

When accessed with on a device with more than 800px of screen, the page loads fully. In mobile devices or even on desktop with less than 800px of width some content is hidden.

I want to make the page load faster for low-resolution devices and avoid loading chunks of content that the user will never see. How can I go about this?

答:
I thought long and hard about this all morning.  This is a very interesting question.

I think the solution that Christian purposed, which is also the defacto-standard, is an inelegant solution that works against progressive enhancement.  While it could be said that it is progressive because if the user does not have the site Javascript enabled, they will simply see a slim version of the website without the extra goodies loaded on view.

However, I don't like this approach.  I have Javascript mostly disabled in my browser, and I run my windows at 1024 - 1280px most of the time, and a site designed for a base of 800px with Javascript on-loads will look pretty bare to me.

That said, I think I may have come up with a solution.

I think the best way to go about responsive design might be by using a tracking image and server-side intervention.

In your style sheets, you could have:

```<code>@media (screen and max-device-width(800px) {
    #sometag {
        background-image: url('track-800.gif');
    }
}

@media (screen and max-device-width(496px) {
    #sometag {
        background-image: url('track-496.gif');
    }
}
</code>```

Now, provided that image is served on a cookie-enabled domain, the web browser will pass the session id back to the server, enabling sessions on that request. If you have these images served by a php-script, you can now track and store the size of the device the user is using.

Given this information now stored in a session variable, you can disable areas of the page (on subsequent page loads) that will never display for the users device resolution.

Disclaimer

This method would require utilizing max-device-width() media queries, rather than max-width() queries. The difference is the application size would be based on the size of the users display, rather than the size of the window.

Body:
I thought long and hard about this all morning.  This is a very interesting question.

I think the solution that Christian purposed, which is also the defacto-standard, is an inelegant solution that works against progressive enhancement.  While it could be said that it is progressive because if the user does not have the site Javascript enabled, they will simply see a slim version of the website without the extra goodies loaded on view.

However, I don't like this approach.  I have Javascript mostly disabled in my browser, and I run my windows at 1024 - 1280px most of the time, and a site designed for a base of 800px with Javascript on-loads will look pretty bare to me.

That said, I think I may have come up with a solution.

I think the best way to go about responsive design might be by using a tracking image and server-side intervention.

In your style sheets, you could have:

@media (screen and max-device-width(800px) {
    #sometag {
        background-image: url('track-800.gif');
    }
}

@media (screen and max-device-width(496px) {
    #sometag {
        background-image: url('track-496.gif');
    }
}

Now, provided that image is served on a cookie-enabled domain, the web browser will pass the session id back to the server, enabling sessions on that request. If you have these images served by a php-script, you can now track and store the size of the device the user is using.

Given this information now stored in a session variable, you can disable areas of the page (on subsequent page loads) that will never display for the users device resolution.

Disclaimer

This method would require utilizing max-device-width() media queries, rather than max-width() queries. The difference is the application size would be based on the size of the users display, rather than the size of the window.


答:
A comment like that is useless; what am I doing wrong?

It only seems useless if you already know what UpdateLocation does. Is "update" here a verb or a noun adjunct? That is, is this something that updates the location, or is it the location of the update? One might infer the latter from the fact that UpdateLocation is apparently a property, but the larger point is that sometimes it doesn't hurt to explicitly state something that seems obvious.

Title: How to deal with tautology in comments?


问:
while(true) and loop-breaking - anti-pattern?
Consider the following code:

public void doSomething(int input)
{
   while(true)
   {
      TransformInSomeWay(input);

      if(ProcessingComplete(input))
         break;

      DoSomethingElseTo(input);
   }
}
```

<p>Assume that this process involves a finite but input-dependent number of steps; the loop is designed to terminate on its own as a result of the algorithm, and is not designed to run indefinitely (until cancelled by an outside event). Because the test to see if the loop should end is in the middle of a logical set of steps, the while loop itself currently doesn't check anything meaningful; the check is instead performed at the "proper" place within the conceptual algorithm.</p>

<p>I was told that this is bad code, because it is more bug-prone due to the ending condition not being checked by the loop structure. It's more difficult to figure out how you'd exit the loop, and could invite bugs as the breaking condition might be bypassed or omitted accidentally given future changes.</p>

<p>Now, the code could be structured as follows:</p>

<pre class="lang-java prettyprint-override"><code>public void doSomething(int input)
{
   TransformInSomeWay(input);

   while(!ProcessingComplete(input))
   {
      DoSomethingElseTo(input);
      TransformInSomeWay(input);
   }
}
</code>```

However, this duplicates a call to a method in code, violating DRY; if TransformInSomeWay were later replaced with some other method, both calls would have to be found and changed (and the fact that there are two may be less obvious in a more complex piece of code).

You could also write it like:

public void doSomething(int input)
{
   var complete = false;
   while(!complete)
   {
      TransformInSomeWay(input);

      complete = ProcessingComplete(input);

      if(!complete)
      {
         DoSomethingElseTo(input);
      }
   }
}
```

... but you now have a variable whose only purpose is to shift the condition-checking to the loop structure, and also has to be checked multiple times to provide the same behavior as the original logic.

For my part, I say that given the algorithm this code implements in the real world, the original code is the most readable. If you were going through it yourself, this is the way you'd think about it, and so it would be intuitive to people familiar with the algorithm.

So, which is "better"? is it better to give the responsibility of condition checking to the while loop by structuring the logic around the loop? Or is it better to structure the logic in a "natural" way as indicated by requirements or a conceptual description of the algorithm, even though that may mean bypassing the loop's built-in capabilities?

答:
Your alternatives are not as bad as you may think. Good code should:

Clearly indicate with good variable names / comments under what conditions the loop should be terminated. (The breaking condition should not be hidden)

Clearly indicate what is the order of doing operations. This is where putting the optional 3rd operation ( DoSomethingElseTo(input) ) inside the if is a good idea.

That said, it is easy to let perfectionist, brass-polishing instincts consume a lot of time. I would just tweak the if as mentioned above; comment the code and move on.

ContentLicense: CC BY-SA 4.0


答: It's only a meaningful problem if the loop body is non-trivial. If the body is so small, then analyzing it like this is trivial, and not a problem at all.</p>

Title: while(true) and loop-breaking - anti-pattern?

Body:
Consider the following code:

public void doSomething(int input)
{
   while(true)
   {
      TransformInSomeWay(input);

      if(ProcessingComplete(input))
         break;

      DoSomethingElseTo(input);
   }
}
```

<p>Assume that this process involves a finite but input-dependent number of steps; the loop is designed to terminate on its own as a result of the algorithm, and is not designed to run indefinitely (until cancelled by an outside event). Because the test to see if the loop should end is in the middle of a logical set of steps, the while loop itself currently doesn't check anything meaningful; the check is instead performed at the "proper" place within the conceptual algorithm.</p>

<p>I was told that this is bad code, because it is more bug-prone due to the ending condition not being checked by the loop structure. It's more difficult to figure out how you'd exit the loop, and could invite bugs as the breaking condition might be bypassed or omitted accidentally given future changes.</p>

<p>Now, the code could be structured as follows:</p>

<pre class="lang-java prettyprint-override"><code>public void doSomething(int input)
{
   TransformInSomeWay(input);

   while(!ProcessingComplete(input))
   {
      DoSomethingElseTo(input);
      TransformInSomeWay(input);
   }
}
</code>```

However, this duplicates a call to a method in code, violating DRY; if TransformInSomeWay were later replaced with some other method, both calls would have to be found and changed (and the fact that there are two may be less obvious in a more complex piece of code).

You could also write it like:

public void doSomething(int input)
{
   var complete = false;
   while(!complete)
   {
      TransformInSomeWay(input);

      complete = ProcessingComplete(input);

      if(!complete)
      {
         DoSomethingElseTo(input);
      }
   }
}
```

... but you now have a variable whose only purpose is to shift the condition-checking to the loop structure, and also has to be checked multiple times to provide the same behavior as the original logic.

For my part, I say that given the algorithm this code implements in the real world, the original code is the most readable. If you were going through it yourself, this is the way you'd think about it, and so it would be intuitive to people familiar with the algorithm.

So, which is "better"? is it better to give the responsibility of condition checking to the while loop by structuring the logic around the loop? Or is it better to structure the logic in a "natural" way as indicated by requirements or a conceptual description of the algorithm, even though that may mean bypassing the loop's built-in capabilities?


问:
DI/IoC in Java for a .NET'er used to Castle.Windsor
Is there a Java DI container that works in a similar way to the most excellent Castle.Windsor container on the .NET side?

The Java containers I've had a look at all seem to rely on annotations (Guice) within my services, which I don't dig all that much - I'd like to go POJO all the way if possible. Spring on the other hand can do without the annotations, but it requires a lot of XML. XML configuration != maintainability.

One of the really nice things about Castle.Windsor is the wiring you're able to set up in code with Installers, auto wiring based on naming conventions and whatnot.

Ideally the container should also support lifecycle management and configuration; i.e. registering components as transient, singleton, pooled etc.

Another bonus would be support for interceptors.

Any tips would be greatly appreciated.

答: Try Spring's Javaconfig- it can be used in several ways, I prefer to not put annotations in the classes I'm using and just writing a context class with the @Config and @Bean annotations. It does autowiring (although I prefer not using it).


答:
I suppose my reason is the lamest: I program in too many different languages at the same time (Java, Javascript, PHP) - that require ';' so rather than train my fingers and eyes that the ';' is not needed for javascript, I just always add the ';'

The other reason is documentation: by adding the ';' I am explicitly stating to myself where I expect the statement to end. Then again I use { } all the time too.

The whole byte count argument I find irritating and pointless:

for common libraries like jquery: use the google CDN and the library will probably be in the browser cache already

version your own libraries and set them to be cached forever.

gzip and minimize if really, really necessary.

But really how many sites have as their biggest speed bottleneck the download speed of their javascript? If you work for a top 100 site like twitter, google, yahoo, etc. maybe. The rest of us should just worry about the code quality not semicolon religious wars.

Title: Why the recent shift to removing/omitting semicolons from Javascript?

Body:
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?


问:
What are the advantages of using bitwise operations?
Following reading the latest CodeProject newsletter, I came across this article on bitwise operations.  It makes for interesting reading, and I can certainly see the benefit of checking if an integer is even or odd, but testing if the n-th bit is set?  What can possibly be the advantages of this?</p>

答:
Tricks that combine bitwise logical operations, bitwise shift operations and arithmetic operations can be understood by people who have studied the construction of a binary adder using logic gates (and, or, not). Outside that circle, it is very difficult to understand without a detailed comment.

It is useful when programming SIMD units, especially if the CPU's architecture intentionally left out some SIMD instructions because they could be emulated by a few others.

For example, the architecture may not define any instructions for taking the negative values of a group of 16 bytes, but that can be emulated by bitwise negating and then adding 1. Likewise, subtraction can be omitted too, because it can be emulated by taking the negative of the second operand. The availability of the "alternate route" is the reason for omitting certain instructions.

Likewise, the SIMD may only support parallel 8-bit addition, without implementing addition for wider elements such as 16-bit, 32-bit or 64-bit. To emulate them, one needs to extract the sign bit from the 8-bit calculation result, then perform the carry operation on the next element.

ContentLicense: CC BY-SA 2.5


答:
I cite two points from another answer, because they capture exactly the reasons why I still use C from time to time (it is not my main language of choice, though):

C is simple. It lacks the expressivity of sophisticated OOP or functional languages, but its simplicity means it can be picked up quickly.

C is mature. The last standard that introduced big changes is C99, and it is mostly backwards-compatible with previous standards. Unlike newer languages (say, Python), you don't have to worry about breaking changes any time soon.

I think this is very true. I learnt C during the early nighties: it was simple, few keywords and constructs, most of the job done by libraries. Then I did not use C for a few years. Around 2002 I needed a fast implementation of an algorithm, I installed a C compiler and implemented it. I know the language, I know what it is good for, what it is not good for (I would never implement a web application in C!), and it is just there when I need it. No surprises.

With C++ I had a different experience. I learnt it around 1995 and it meant a big paradigm switch from imperative to OOP. Great! I used it for several projects until 1999. For a few years I did not use C++ and when I picked it up again (2008) I found lots of new features already in the language, and even more planned (meanwhile introduced in C++11). I got the feeling I have to learn the language again.

As a developer, I prefer mature, stable languages. I like to learn a language once, to understand its design principles, what it is good for, and to use it when I think it is the right tool for the job.
I also like to learn different languages and to pick the language that suites my need (C, C++, Java, Scala, Haskell, and so on). What I do not like is to have to learn the same language again and again because it gets developed further and further, and never reaches maturity.

IMHO, a programming language should have a clear, coherent, and stable design. I like the approach of designers like Niklaus Wirth: every time he felt the need for a different language, he designed a new one (Pascal, Modula-2, Modula-3, Oberon). I do not like languages that undergo important changes every 5-10 years: they are like moving targets and I never feel it is worthwhile investing my time to learn them in depth, because the version I am learning now will probably be obsolete in a few years anyway.

In this sense C is IMO a winner: it is good for certain applications and less appropriate for others, but it has the advantage that it is simple and relatively stable.

Title: What makes C so popular in the age of OOP?

Body:
I code a lot in both C and C++, but did not expect C to be the second most popular language, slightly behind Java.

TIOBE Programming Community Index

I'm curious as to why, in this age of OOP, C is still so popular? Note that 4 out of the top 5 popular programming languages are "modern", object-oriented capable languages.

Now, I agree that you can use OOP in C to some extent, but it's sort of painful and inelegant (well at least compared to C++ I guess). So, what makes C so popular?  Is it efficiency; being low-level; the vast majority of libraries that already exist or something else?


问:
Current iOS version/device statistics?
The answer to this SO question has become stale: iOS version/device statistics - where can I find?
because time currency wasn't part of that question, and iOS version updates have been release since this question was asked.

Is there a web site or other publicly available source which keeps a current or frequently updated list of the percentages of iOS devices and OS versions in use, perhaps by continual monitoring of app analytics or web site logs or other means?

And what device or OS information are iOS app analytics currently allowed to report, if any?  (...assuming an appropriate privacy policy and adhering to such, of course.)

答:
This developer has posted the iOS version stats his app sees (updated weekly). Currently (as of August 13, 2012) about 73% of devices use IOS 5.X.

Update for iOS 6:  Here some newer stats on iOS 6 Adoption two weeks after its release.

Title: Current iOS version/device statistics?


问:
What is the "Find-Fix-Verify" pattern?
What is the "Find-Fix-Verify" pattern, as related to the process of doing editing/spellchecking/debugging, etc.?

Where is this pattern best described?

What are some advantages and disadvantages of this pattern?

答:
It seems to be a workflow pattern for crowdsourcing, first described in this paper and used with some success by Zappos to improve the spelling and grammar of product reviews on their site.

I guess the "pattern" is a simple division of labor:

Have some people identify problems

Have other people fix the problems identified by the first group

Have a third group check that the fixes were done correctly

Makes sense (the find/fix division probably improves overall speed, and the verify step is always needed for crowdsourcing), but not really all that impressive an idea...

Title: What is the "Find-Fix-Verify" pattern?


答:
Subversion does not require a server. It uses a centralized repository, but this repository can be accessed through the 'file' access method, which means, you merely need access to the filesystem that the repository is stored on. The easiest way to set this up would be to create a folder somewhere on your hdd, point TortoiseSVN (or a similar tool) at it, and 'create repository here'. From there, you can do whatever you need to get your code into the repository.

However, in the long run, you're probably better off using a distributed SCM, the best candidates being git (more powerful, steep learning curve, works best on *nix) and mercurial (slightly less powerful, easy to learn, works equally well on windows and *nix). With these, your working copy contains the entire repository, and you can make as many clones (remote or local) as you wish. You can start out locally, and if you decide to host the repository externally, you simply clone your existing local repository to the external location, and you can synchronize in both directions at any time. Better yet, because each of your clones contains the entire project history, the SCM doubles as a backup system. With subversion, if your server dies and you haven't backed it up, your history is gone - with git, you just clone your working copy to a new server and that's it.

http://hginit.com/ has an excellent tutorial on getting started with mercurial.


问:
When should JavaScript generate HTML?
I try to generate as little HTML from JavaScript as possible. Instead, I prefer to manipulate existing markup whenever I can and only generate HTML when I need to dynamically insert an element that isn't a good candidate for using Ajax. This, I believe, makes it far easier to maintain the code and quickly make changes to it because the markup is easier to read and trace. My rule of thumb is: HTML is for document structure, CSS is for presentation, JavaScript is for behavior.

However, I've seen a lot of JS code that generates mounds of HTML, including entire forms and content-heavy modal dialogs. In general, which method is considered best practice? In what circumstances should JavaScript be used to generate HTML and when should it not?

答:
The advantage of generating HTML on the client, is you offload the rendering work to each client, that sits generally idle waiting for the response. Freeing more server resources to deliver only JSON data and static content(HTML, JS and CSS).

We do a web app that generate exclusively HTML with Javascript. 87% of server hits are JSON data, the static content is generally loaded once, then from the browser cache.

But you can't use it - at least not easily - if you need SEO.
Or if you target a population that have Javascript disabled, but I'm not sure this one is still relevant with Youtube, Twitter, Facebook, Gmail,... naturally forcing people to enable it.

Title: When should JavaScript generate HTML?


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

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

答:
Being a good software engineer is 3% talent, 97% not being distracted by the internet.

— Unknown, appropriated

LastEditorDisplayName: Roger Pate


答: Auto-compiled documentation aside, code should document itself, so that comments should only document where the code is not enough to document itself.</p>

Title: How to deal with tautology in comments?


问:
Why the recent shift to removing/omitting semicolons from Javascript?
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?

答:
It makes method chaining easier and commit diffs cleaner

So let's say I'm jQuerying about and I have

```<code>$('some fancy selector')
  .addClass()
  .attr();
</code>```

If I want to add stuff and keep my line-based commit diff small, I have to add it above attr. So it's one thought longer than just "add at the end". And who wants to think? =)

```<code>$('some fancy selector')
  .addClass()
  // new method calls must go here
  .attr();
</code>```

But, when I drop the semi-colons, I can just append and call it a day

```<code>  $('some fancy selector')
    .addClass()
    .attr()
+   .animate()
+   .click()
</code>```

Also, if I decide to pop off the last method, I don't have to reassign the semi-colon and pollute my commit again.

```<code>  $('some fancy selector')
    .addClass()
    .attr()
    .animate()
-   .click()
</code>```

Versus the uggo

```<code>  $('some fancy selector')
    .addClass()
    .attr()
+   .animate();
-   .animate()
-   .click();
</code>```

Body:
It makes method chaining easier and commit diffs cleaner

So let's say I'm jQuerying about and I have

$('some fancy selector')
  .addClass()
  .attr();

If I want to add stuff and keep my line-based commit diff small, I have to add it above attr. So it's one thought longer than just "add at the end". And who wants to think? =)

$('some fancy selector')
  .addClass()
  // new method calls must go here
  .attr();

But, when I drop the semi-colons, I can just append and call it a day

  $('some fancy selector')
    .addClass()
    .attr()
+   .animate()
+   .click()

Also, if I decide to pop off the last method, I don't have to reassign the semi-colon and pollute my commit again.

  $('some fancy selector')
    .addClass()
    .attr()
    .animate()
-   .click()

Versus the uggo

  $('some fancy selector')
    .addClass()
    .attr()
+   .animate();
-   .animate()
-   .click();


问:
Why do computer architecture textbooks prefer MIPS architecture?
I have read a lot of computer architecture textbooks, and I wonder why most of them (if not all) used MIPS as the architecture to teach. Why MIPS and not Intel or AMD or something else? What makes the architecture suitable for teaching?</p>

答:
Intel and AMD have a large share of the Desktop market. Other processor families are much more common in devices outside that fairly small area of influence. MIPS is also a RISC architecture which are generally thought of as being easier to learn. You learn a small number of commands that can be combined orthogonally a multitude of ways similar to UNIX style piping.

Computer Architecture books that are educational rather than specificational are generally geared toward concepts rather than specific implementation details and thus tend to be more likely to use RISC over CISC simply because there's less to teach in order to understand the instruction set.

I do expect a convergence with ARM though as it is an extremely widely used architecture that is also RISC so I'd think it will show up in architecture books soon enough.


问:
Introducing functional programming constructs in non-functional programming languages
This question has been going through my mind quite a lot lately and since I haven't found a convincing answer to it I would like to know if other users
of this site have thought about it as well.

In the recent years, even though OOP is still the most popular programming paradigm, functional programming is getting a lot of attention. I have only
used OOP languages for my work (C++ and Java) but I am trying to learn some
FP in my free time because I find it very interesting.

So, I started learning Haskell three years ago and Scala last summer. I plan to
learn some SML and Caml as well, and to brush up my (little) knowledge of Scheme. Well, a lot of plans (too ambitious?) but I hope I will find the time
to learn at least the basics of FP during the next few years.
What is important for me is how functional programming works and how / whether
I can use it for some real projects. I have already developed small tools in Haskell.

In spite of my strong interest for FP, I find it difficult to understand why
functional programming constructs are being added to languages like C#, Java, C++, and so on. As a developer interested in FP, I find it more natural to
use, say, Scala or Haskell, instead of waiting for the next FP feature
to be added to my favourite non-FP language.
In other words, why would I want to have only some FP in my originally
non-FP language instead of looking for a language that has a better support
for FP?

For example, why should I be interested to have lambdas in Java if I can switch
to Scala where I have much more FP concepts and access all the Java libraries
anyway?
Similarly: why do some FP in C# instead of using F# (to my knowledge,
C# and F# can work together)?

Java was designed to be OO. Fine. I can do OOP in Java (and I would like to keep using Java in that way). Scala was designed to support OOP + FP. Fine: I can use a mix of OOP and FP in Scala. Haskell was designed for FP: I can do FP in Haskell. If I need to tune the performance of a particular module, I can
interface Haskell with some external routines in C.

But why would I want to do OOP with just some basic FP in Java?

So, my main point is: why are non-functional programming languages being extended with some functional concept?
Shouldn't it be more comfortable (interesting, exciting, productive) to
program in a language that has been designed from the very beginning to
be functional or multi-paradigm? Don't different programming paradigms
integrate better in a language that was designed for it than in a language
in which one paradigm was only added later?

The first explanation I could think of is that, since FP is a new concept
(it isn't new at all, but it is new for many developers), it needs to be
introduced gradually. However, I remember my switch from imperative to OOP:
when I started to program in C++ (coming from Pascal and C) I really had to
rethink the way in which I was coding, and to do it pretty fast.
It was not gradual. So, this does not seem to be a good explanation to me.

Or can it be that many non-FP programmers are not really interested in
understanding and using functional programming, but they find it practically
convenient to adopt certain FP-idioms in their non-FP language?

IMPORTANT NOTE

Just in case (because I have seen several language wars on this site):
I mentioned the languages I know better, this question is in no way
meant to start comparisons between different programming
languages to decide which is better / worse.

Also, I am not interested in a comparison of OOP versus FP (pros and cons).
The point I am interested in is to understand why FP is being introduced
one bit at a time into existing languages that were not designed for it
even though there exist languages that were / are specifically designed
to support FP.

答:
Notwithstanding any specific ideas on the part of language designers, it bears mentioning that authors and stewards of programming languages are, in the end, pushing a product.  So, I might ask why I'd want a camera-phone when my plain phone is a better phone and my camera a better camera, but that isn't going to stop manufacturers of both devices from trying to broaden their product's offering to attract new customers.

Once you look at it from that perspective, then notions of preserving the integrity of the original language become a matter of degrees and tradeoffs.  If I'm the author of OOP language AwesomeCode and I see people starting to get interested in new functional language FCode, do I tell my users "sorry, but this is an OOP language only" and risk them going to C# instead to get at its lambas, or do I cave and grudgingly include some of FCode's functionality?


答:
The MIPS architecture is derived from an architecture specifically designed at Stanford for educational use and for research into CPU ISAs and architectural implementations.  Early academic RISC architecture were designed such that they could be implemented (included layout) by small teams of graduate or upper-division students (not the cast of thousands involved in current Intel CPUs.)  Thus MIPS may have basic features more compatible with textbook pedagogical explanations, and less legacy-derived "stuff" that isn't, compared with other commercial architectures.

MIPS may also have more available open source implementations very similar to it than other RISC or currently popular architectures.

Title: Why do computer architecture textbooks prefer MIPS architecture?

Body: I have read a lot of computer architecture textbooks, and I wonder why most of them (if not all) used MIPS as the architecture to teach. Why MIPS and not Intel or AMD or something else? What makes the architecture suitable for teaching?</p>


问:
How is JavaScript insecure, and what are the main methods used to deal with that?
I just read about Caja, which is a "sanitized" version of JavaScript. But I'm wondering - what is the big problem with JavaScript(it seems so widely used )? Just how dangerous is it?</p>

答:
The changes it makes vs. regular javascript are pretty well described here.

From that reference:

Caja takes JavaScript (technically, ECMAScript 5 strict mode code),
  HTML, and CSS input and rewrites it into a safe subset of HTML and
  CSS, plus a single JavaScript function with no free variables. That
  means the only way such a function can modify an object is if it is
  given a reference to the object by the host page. Instead of giving
  direct references to DOM objects, the host page typically gives
  references to wrappers that sanitize HTML, proxy URLs, and prevent
  redirecting the page; this allows Caja to prevent certain phishing
  attacks, prevent cross-site scripting attacks, and prevent downloading
  malware. Also, since all rewritten programs run in the same frame, the
  host page can allow one program to export an object reference to
  another program; then inter-frame communication is simply method
  invocation.

And, Google's site on Caja.


问:
How to deal with tautology in comments?
Sometimes I find myself in situations when the part of code that I am writing is (or seems to be) so self-evident that its name would be basically repeated as a comment:

```<code>class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

(C# example, but please refer to the question as language-agnostic).

A comment like that is useless; what am I doing wrong? Is it the choice of the name that is wrong? How could I comment parts like this better? Should I just skip the comment for things like this?

答:
Here's a question I like to ask myself when thinking about whether to add a comment into a section of code: What can I convey that would help the next person understand the overall intent of the code better, so that they can update, fix, or extend it faster and more reliably?

Sometimes the correct answer to this question is that there is nothing much you can add at that point in the code, because you have already selected names and conventions that make the intent about as obvious as it can be. That means you've written solid self-documenting code, and that inserting a comment there would likely detract more than it would help. (Note that redundant comments can actually damage code reliability over time by slowing falling out of sync with the real code over time and thus making it harder to decipher the real intent.

However, in almost any program and in any programming language, you are going to encounter points where certain critical concepts and decisions made by the original programmer -- by you -- will no longer be apparent in the code. This is pretty much unavoidable because a good programmer always programs for the future -- that is, not just to make the program work once, but to make all of its many future fixes and versions and extensions and modifications and ports and who knows what to also work correctly. That latter set of goals is a lot harder, and requires a lot more thinking to do well. It is also very hard to express well in most computer languages, which are more focused on functionality -- that is, on saying what does this version of the program need to do, right now, in order to make it satisfactory.

Here's a simple example of what I mean. In most languages, a quick in-line search of a small data structure will have enough complexity that someone looking at it for the first time likely will not recognized immediately what it is. That's an opportunity for a good comment, because you can add something about the intent of your code that a later reader will likely appreciate immediately as helpful for deciphering the details.

Conversely, in languages such as the logic-based language Prolog, expressing the search of a small list can be so incredibly trivial and succinct that any comment you might add would just be noise. So, good commenting is necessarily context dependent. That includes factors such as the strengths of the language you are using and the overall program context.

The bottom line is this: Think to the future. Ask yourself what is important and obvious to you about how the program should be understood and modified in the future.[1]

For those parts of your code that are truly self documenting, comments just add noise and increase the coherency problem for future versions. So don't add them there.

But for those parts of your code where you made a critical decision from several options, or where the code itself is complex enough that its purpose is obscure, please, add your special knowledge in the form of a comment. A good comment in such a case is one that lets some future programmer know what must be kept the same -- that is the concept of an invariant assertion, incidentally -- and what is OK to change.

[1] This goes beyond the issue of comments, but it's worth bringing up: If you find that you have a very crisp idea of how your code could change in the future, you should likely think beyond just making a comment and embed those parameters within the code itself, since that will almost always be a more reliable way to ensure the reliability of future versions of your code than trying to use comments to steer some unknown future person in the right direction. At the same time you also want to avoid overgeneralizing, since humans are notoriously bad at predicting the future, and that includes the future of program changes. So, try to define and capture reasonable and well-proven dimensions of future at all levels of program design, but don't let it get you distracted into an exercise in excessive generalization that is unlikely to pay of in the long term.

Title: How to deal with tautology in comments?


答:
Purely functional programming styles have serious problems with input/output. That's why most functional languages are not pure and Haskell which is has...intimidating I/O techniques. Anything that requires a destructive update like Graphics for instance is harder to do that in functional languages.

Functional constructs are being added to mainstream languages for three main reasons:

Pattern Matching: Functional languages typically have extremely compact syntax for dealing with pattern matching. Python has shades of this with its for statements. This winds up very useful in things like Data Mining.

Generic Programming/Metaprogramming: These both improve code adaptability tremendously by allowing a program to either be more flexible or to modify itself as it goes along. This can be hugely important in AI.

State Control: Functional Programming has no variables whatsoever, it has symbols instead. Every "variable" has a single unchanging value. That means we don't get any kind of ambiguity in terms of what something is. A magic A is a magic A while in imperative languages it could be a Magic A or B or C or D or whatever. There is no chance at all for an undetermined state in Functional Programming because there aren't any states in that sense. What is done instead is the idea of isolation of I/O. You get back what you put in, not some random weirdness and due to isolation there is no way that I/O can corrupt your internal program (ideally). This whole mess comes in hand in particular with Concurrency as you don't need locks or barriers.

I'd argue that Object Oriented Programming is still fully applicable with Functional Programming. OO Programming is a useful way of organizing and structuring code while Functional Programming is a useful way of ordering and structuring computation. OCAML is a prime example here. OO Programming has even been combined with logic programming in the form of Prolog++. So OO Programming can certainly benefit from other styles just as much as they can benefit from it.

Title: Introducing functional programming constructs in non-functional programming languages

Body:
This question has been going through my mind quite a lot lately and since I haven't found a convincing answer to it I would like to know if other users
of this site have thought about it as well.

In the recent years, even though OOP is still the most popular programming paradigm, functional programming is getting a lot of attention. I have only
used OOP languages for my work (C++ and Java) but I am trying to learn some
FP in my free time because I find it very interesting.

So, I started learning Haskell three years ago and Scala last summer. I plan to
learn some SML and Caml as well, and to brush up my (little) knowledge of Scheme. Well, a lot of plans (too ambitious?) but I hope I will find the time
to learn at least the basics of FP during the next few years.
What is important for me is how functional programming works and how / whether
I can use it for some real projects. I have already developed small tools in Haskell.

In spite of my strong interest for FP, I find it difficult to understand why
functional programming constructs are being added to languages like C#, Java, C++, and so on. As a developer interested in FP, I find it more natural to
use, say, Scala or Haskell, instead of waiting for the next FP feature
to be added to my favourite non-FP language.
In other words, why would I want to have only some FP in my originally
non-FP language instead of looking for a language that has a better support
for FP?

For example, why should I be interested to have lambdas in Java if I can switch
to Scala where I have much more FP concepts and access all the Java libraries
anyway?
Similarly: why do some FP in C# instead of using F# (to my knowledge,
C# and F# can work together)?

Java was designed to be OO. Fine. I can do OOP in Java (and I would like to keep using Java in that way). Scala was designed to support OOP + FP. Fine: I can use a mix of OOP and FP in Scala. Haskell was designed for FP: I can do FP in Haskell. If I need to tune the performance of a particular module, I can
interface Haskell with some external routines in C.

But why would I want to do OOP with just some basic FP in Java?

So, my main point is: why are non-functional programming languages being extended with some functional concept?
Shouldn't it be more comfortable (interesting, exciting, productive) to
program in a language that has been designed from the very beginning to
be functional or multi-paradigm? Don't different programming paradigms
integrate better in a language that was designed for it than in a language
in which one paradigm was only added later?

The first explanation I could think of is that, since FP is a new concept
(it isn't new at all, but it is new for many developers), it needs to be
introduced gradually. However, I remember my switch from imperative to OOP:
when I started to program in C++ (coming from Pascal and C) I really had to
rethink the way in which I was coding, and to do it pretty fast.
It was not gradual. So, this does not seem to be a good explanation to me.

Or can it be that many non-FP programmers are not really interested in
understanding and using functional programming, but they find it practically
convenient to adopt certain FP-idioms in their non-FP language?

IMPORTANT NOTE

Just in case (because I have seen several language wars on this site):
I mentioned the languages I know better, this question is in no way
meant to start comparisons between different programming
languages to decide which is better / worse.

Also, I am not interested in a comparison of OOP versus FP (pros and cons).
The point I am interested in is to understand why FP is being introduced
one bit at a time into existing languages that were not designed for it
even though there exist languages that were / are specifically designed
to support FP.


问:
PHP to SharePoint roadmap
I'm a PHP developer with familiarity with Rails and a focus on MVC development. My company is moving more and more to SharePoint and I feel I need to learn to build application within the SharePoint system.

I have some brief introduction to C# but that's about it. I've used some SharePoint Designer and the web interface but not that heavily (most of my "development" so far for SharePoint has been html/css/javascript page manipulation in SPDesigner).

What, and in what order should I be learning to eventually develop applications for SharePoint? Also, any good resources for each step?

答:
SharePoint is so big and complex that you really need to have a specific requirement in mind.

You will find that SharePoint gets in the way a bit if you are used to simple web apps which do only what you write them to do and can be upgraded with a simple file copy. However, there are ways to make it closer to modern web development.

For the last year or so I have been building web parts that look a lot like asp.net mvc controllers. The tools I use are on github - http://github.com/tqc/RazorEngine.

You can do a lot of stuff client side, which is the same regardless of platform. There are even libraries that let you use jquery to read from SharePoint lists, though I generally prefer custom web services myself. I'd stay away from designer for this though - it works well to start with, but eventually becomes Unmaintainable.

OwnerDisplayName: Daryl Gubler

Title: PHP to SharePoint roadmap


答: "Location" is kind of obvious, but "Update" could be a bit vague.  If you can't write a better name, then can you offer more detail in the comment?  Update of what?  Why do we need this?  What are some assumptions (is null allowable)?</p>

Title: How to deal with tautology in comments?


问:
Which of these looks cleaner?
I have wrote a small method in a program to do one thing my method looks like this:

```<code>public static void removeExpiredAssignments(Module module){
    module.removeExpiredAssignments();
}
</code>```

So the method is called like:

```<code>removeExpiredAssignments(module);
</code>```

When the desired operation could be done by saying:

```<code>module.removeExpiredAssignments();
</code>```

Which is easy to understand from the code point of view?

答: It depends what you're trying to do. Calling the method on the module directly implies that the module is required and directly effected by the action. Calling the method that takes in a module implies that the module may or may not be needed in order to carry out the action, and that it may or may not directly effect the state of the module.</p>

Title: Which of these looks cleaner?


答:
Erik's answer is correct for the "why" this is done.

I'd like to add that when selecting a language, pick the one that naturally supports the paradigm.  For example, wanting to do FP and picking C++ and wrangling in some strange libraries is inferior in every way to just picking a FP language to start with.  Pick the tool that best meets the need.  If you really want FP features, use an FP language, don't use the weak half-functional implementation of it with leaky abstractions in another language.

This kind of thing annoys me when people try to wrangle everything into The One True Language, which is the wrong idea.  Use different tools for different jobs, don't try to make the ultimate Swiss army knife which doesn't really do any job well.


问:
Why would a programmer want to separate implementation from interface?
The bridge design pattern separates implementation from the interface of a program.

Why is this advantageous?

答:
It allows you to change the implementation independently of the interface.  This helps deal with changing requirements.

The classic example is replacing the storage implementation under an interface with something bigger, better, faster, smaller, or otherwise different without having to change the rest of the system.


答:
In addition to Daniel's answer, separating interface from implementation through concepts like polymorphism allows you to create several implementations of the same interface that do similar things in different ways.

For example, lots of languages have a concept of a stream somewhere in the standard library.  A stream is something that holds data for serial access. It has two basic operations: Read (load the next X number of bytes from the stream) and Write (add X number of bytes of data to the stream), and sometimes a third, Seek (reset the "current position" of the stream to a new location).

That's a simple enough concept, but think of all the things you could do with it.  The most obvious one is to interact with files on disc.  A file stream would let you read data from a file or write to it.  But what if you wanted to send data over a network connection instead?

If you relied on implementations directly, you'd have to write out two completely different routines to save the same data to a file or to send it over the network.  But if you have a stream interface, you can create two different implementations of it (FileStream and NetworkStream) that encapsulate the specific details of sending the data where it needs to go, and then you only need to write the code that deals with saving a file once.  Suddenly your SaveToFile and SendOverNetwork routines are a lot simpler: they just set up a stream of the appropriate type and pass it to the SaveData routine, which accepts a stream interface--it doesn't need to care what type, as long as it can perform the Write operation--and saves the data to the stream.

That also means that if your data format changes, you don't have to change it in multiple different places.  If you centralize your data saving code in one routine that takes a stream, then that's the only place that it needs to be updated, so you can't accidentally introduce a bug by only changing one place when you needed to change both.  So separating interfaces from implementations and using polymorphism makes for code that's simpler to read and understand, and that's less likely to have bugs.

Title: Why would a programmer want to separate implementation from interface?

Body:
The bridge design pattern separates implementation from the interface of a program.

Why is this advantageous?


答: This ties in with Jeremy's answer, but I'd say it's a question of whose responsibility it is to execute the method. Is the module where the knowledge of how to perform this belongs? If so, it should be the module that executes the method on itself. If the knowledge of how to do this belongs elsewhere, the method should be on that other object/class and take the module as its argument.

Title: Which of these looks cleaner?

Body:
I have wrote a small method in a program to do one thing my method looks like this:

```<code>public static void removeExpiredAssignments(Module module){
    module.removeExpiredAssignments();
}
</code>```

So the method is called like:

```<code>removeExpiredAssignments(module);
</code>```

When the desired operation could be done by saying:

```<code>module.removeExpiredAssignments();
</code>```

Which is easy to understand from the code point of view?


问:
I Want To Program!
I am highly interested in learning how to program but I am unsure whether I want to lean towards web developing or software programming. Or does computer programming cover both in a nut shell? Where should or how should I start?</p>

答:
Web development and traditional client application development (which is what I assume you mean by "software programming") are very different things.

When writing a web app, you take input from a client and produce HTML as output, to be rendered in the client's browser.  Web programming is basically stateless.  This means that because the browser does not maintain an open connection with your server, you can't assume anything about past interactions when a new request comes in.  Everything you create has to be based on the data that the browser sends you and the data you have stored in the database.  (It's possible to save some data in memory on the server so you don't always need to read the database for everything if you've got the same user making a bunch of requests in a short amount of time, but since the Web connection is stateless and doesn't remain open, you have no way of knowing when they're finished, so you have to make sure all data gets stored in the database.)

On the other hand, when writing a traditional app, you generally directly control not only the data but also the code that draws what the user sees.  And knowing when the program is in use and when it's being shut down is an inherent part of the program, so you can rely a lot more heavily on in-memory data, and only worry about saving data when it's appropriate to do so within the context of your program.  Also, a traditional app is run directly on a user's computer and is only used by one person at a time, whereas a webserver can have to service hundreds or even thousands of connections from different people all at once.

To give a simple example, let's say you have a game where a character can walk around on a map.  In a traditional program, your code draws the scene, the user uses the keyboard or mouse to tell the character to move to another position, and your program draws the movement to the screen.  It's probably animated, because that's not hard to do if you know a few things about sprites.

Doing that on a web app would be very different.  The user has a webpage open in their browser that displays the map and the character.  They select a new position to move to by clicking on it.  Your page has code in it that tells the browser to send a request to execute that move to your server over HTTP.  Your server receives it.  First it has to validate it, (you have to make sure it's a legal move; since the move command is just a Web request, it's very easy for someone to try to cheat by just sending the server whatever they want, whether or not it actually makes sense according to the rules,) by looking up the character's current position in the database and making sure it's possible to execute that move.  Then (assuming it's valid) it calculates the effects of the move on the game, saves the changes to the database, and creates a new webpage containing the updated game map to send back to the user's browser.

This is a bit of an over-generalization (on both sides) but that's the general idea of the difference between Web programming and traditional app programming.  Which one you should lean more towards depends on what it is you're interested in creating.  That's really the first question you should answer.  If you just say "I want to program something," then you've got no starting point.  But if you say "I want to write a XYZ" then you have an actual goal, and you can start to learn how it's done.

One bit of advice, and this is another generalization, but it's a useful one.  When you get down to it, programming really only consists of two basic tasks: breaking down a problem into a set of smaller sub-problems, and expressing small problems in formal logic so that a computer can understand them.  If you can learn to do those two things really well, the rest is just specific techniques and gaining the experience to know which one to use where.

Title: I Want To Program!