答:
I don't have an answer for you myself, but the problem rung a bell - I remember some random guys discussing it on a podcast once.

Spolsky: I noticed one of the
  questions you asked on the blog was
  how should you handle maintenance
  recurring tasks in general?

Atwood: Yes.

Spolsky: Is that a fair
  characterization?  Every website has
  some tasks that you don't want to
  execute at the time a web page is
  loading, but you want to execute with
  some recurrence of some sort.

Atwood: Ya, background tasks sort of
  thing.

Spolsky: Ya, so what did you figure
  out?

Atwood: Well, I originally asked on
  Twitter, because I just wanted
  something light weight.  I really
  didn't want to like write a windows
  service.  I felt like that was out of
  band code. Plus the code that actually
  does the work is a web page in fact,
  because to me that is a logical unit
  of work on a website is a web page.
  So, it really is like we are calling
  back into the web site, it's just like
  another request in the website, so I
  viewed it as something that should
  stay inline, and the little approach
  that we came up that was recommended
  to me on Twitter was to essentially to
  add something to the application cache
  with a fixed expiration, then you have
  a call back so when that expires it
  calls a certain function which does
  the work then you add it back in to
  the cache with the same expiration.
  So, it's a little bit, maybe "ghetto"
  is the right word.

Title: Servicing background tasks on a large site

Body:
We're dealing with an interesting problem on StackOverflow.

We've got a whole bunch of little "needs to be done soon-ish" tasks.  An example is updating "Related Questions" lists.  What we've done in the past is to piggy-back those tasks onto some users' page loads.

This was never ideal, but it wasn't really noticeable.  Now that SO has passed the 1,000,000 question mark, those unlucky users are starting to feel it.

The natural solution is to actually push these tasks into the background.  There are two broad ways of doing this I'm considering.

1. In IIS as a custom Thread-Pool/Work-Queue

Basically, we spin up a few (non-ThreadPool, so as to not interfere with IIS) threads and have them services some collections we're shoving Funcs into.

The big pro here is simplicity.  We don't have to worry about marshaling anything, nor do we have to make sure some external service is up and responding.

We also get access to all of our common code.

The con is, well, that we shouldn't use background threads.  The objections I know of are all centered around starving IIS (if you use ThreadPool) and the threads dieing randomly (due to AppPool recycling).

We've got existing infrastructure to make the random thread death a non-issue (its possible to detect a task has been abandoned, basically), and limiting the number of threads (and using non-ThreadPool threads) isn't difficult either.

Am I missing any other objections to in IIS process thread-pooling/work-queues?

Moved to StackOverflow, as it wasn't really addressed here.

2. As a Service

Either some third-party solution, or a custom one.

Basically, we'd marshal a task across the process boundary to some service and just forget about it.  Presumably we're linking some code in, or restricted to raw SQL + a connection string.

The pro is that its the "right way" to do this.

The cons are that we're either very restricted in what we can do, or we're going to have to work out some system for keeping this service in sync with our code base.  We'll also need to hook all of our monitoring and error logging up somehow, which we get for free with the "In IIS" option.

Are there any other benefits or problems with the service approach?

In a nutshell, are there unforseen and insurmountable problems that make approach #1 unworkable and if so are there any good third-party services we should look into for approach #2?


问:
Do we need "obvious" Method Documentation information?
I know we have questions about comments in general but I'm specifically wondering about Java Doc style method documentation here.

I've been pruning unnecessary comments as I refactor and I've noticed our code has painfully obvious descriptions of methods.

```<code>/**
* @name save
* @desc Validates and saves submitted daily plant production information.
*/
</code>```

Most of the "documented" functions are just method names used by convention in our MVC framework (CakePHP). It's inherently obvious that the save method in the Production Controller performs the necessary actions to save Production Information.

We don't actually use Java Doc and I question the value of these descriptions even if they were included in Java Doc style documentation. The only reason I haven't touched these because they're method documentation that's supposed to be valuable. The method documentation also hasn't been used consistently, about half of our Controller/model methods are documented.

Is there any reason to keep these obvious "Java Doc" comments or should I prune them in favor of "self documenting code" and only make Java Doc comments for less obvious methods?

答:
"Obvious" is "obviously" subjective.

I certainly wouldn't go removing "obvious" code comments just for the sake of it, or tidying things up (in your opinion).

It might be worth a dev team meeting to discuss the level comments need to be at from now on.

Going on a delete mission for the sake of it is liable to just annoy people.

ContentLicense: CC BY-SA 3.0


问:
should I throw exception from constructor?
I know I can throw exception from constructor in PHP but should I do it? For example, if a parameter's value is not as I expected it.

Or should I defer throwing an exception till a method is invoked. What are advantages and disadvantages in both cases?

答: If your constructor is invoked with bad parameter(s) then you should (must?) throw an exception. If you do not then you could get a bad object which will not behave as expected.</p>

OwnerDisplayName: WordsWorth

OwnerDisplayName: Peter Kiss


答:
Why would you postpone throwing the exception?

If you know that the object can't properly instantiate with the given parameters, then you should definitely throw an exception.

Otherwise, somebody might test your object for null, which it won't be, and could assume everything went as expected.

There are a lot of things that can be done to your object without calling a method on it: it could be added to a list, it could be compared, it could be sent as a parameter, etc etc etc. All of these are things that should not have happened, considering it is not a valid object.

Title: should I throw exception from constructor?

Body:
I know I can throw exception from constructor in PHP but should I do it? For example, if a parameter's value is not as I expected it.

Or should I defer throwing an exception till a method is invoked. What are advantages and disadvantages in both cases?

OwnerDisplayName: Andrei G


问:
Can thesaurus items have more than one USE relation?
I want to model a Thesaurus using the ANSI/NISO standard relation description like "broader term", "narrow term", etc. (see this Wikipedia article for details). Is it valid for a Thesaurus item in this description standard to have more than one "use" relationship?</p>

答:
No.

USE is for mapping entry vocabulary to authorized terms. It's an equivalency relationship. Therefore 1:1.  Use for is just the opposite; it defines a specific term to be used instead of (often) multiple common terms.  e.g. you might have ('vermilion: USE 'red), or you could have ('red: USE-FOR 'pink, 'vermilion, 'rose).


问:
Should I require users to register to use my app?
So I'm very close to releasing an app I've been working on, and the server I integrate with allows me to register users.  So I was wondering if I should require users to register with the app before they use it.  The app wouldn't "need" the registration for any of the features (although I have some ideas about future updates where the user's data could be saved to their account in the cloud), but it would still be nice to have a list of registered users.

One reason I think I should require users to register is because when the app launches for the first time, the user must accept my privacy policy and terms of use; so if I made a registration screen, it might be an easier and more straightforward, rather than bombarding the user with the thick legal language.

But I'm afraid requiring the user to register will cost me some users.  I once downloaded an app, and it wanted me to register, but I was lazy never did.  Is that a legitimate fear with requiring registration?

Thanks!

Edit:
To clearify, if I was to require registration, what info should I collect: name, email, password?  other?  And we wouldn't be spamming them with emails at all.  We also have a very strong privacy policy and would store all data securely.

答:
All of these answers are great, but they're preoccupied with policies and technicalities.

Yes, absolutely! you should require users to register. Why? First off, you want those email addresses. Without those emails, someone can use your app, forget about it, and you have no way of contacting them again if you added a new feature that would entice them to come back. It would be a serious mistake if you did not get their email addresses.

You say it would detract potential people. Yes, you would. But you'd mostly detract people who are probably not your core users.. just people who casually want to see what it's about, not people who are really motivated and interested in what you have to offer. Trust me, if someone really really wants what you offer, they'll register. Most sites require registration these days: stack exchange, quora, gmail, faceboook, pinterest. It's common practice - don't worry

If you worry about it being a hassle, implement Facebook Connect at the very least.


答:
Absolutely!!

You should throw the exception if the parameters for constructing the object is not valid or not as per the contract. It is not a good idea to go ahead with the flow knowing that the object is constructed with bad data which can cause many  issues if you allow the caller to go ahead.

It is always better to "FAIL FAST AND FAIL EARLY"


问:
How to decide : Phone App or Web App
From your real life experience & executed work.

How to choose between starting a project as a Phone App or a Web App ?

From what I've read, it is a matter of : the need vs time & $ cash to solve it.

I am not sure for the long term & with a limited budget what path to take.

My main concerns and comparisons :

Phone App

locked in on a given platform

specific to each device

specific dev skills needed for each device

cost of programming

cost of distributing

limited distribution channel

Web App

open platform

multiple devices friendlier

overlapping dev skills

cost of programming

no distribution cost

no distribution channel

What are your Pros / Cons

答:
From a money perspective, a web app is way easier to monetize. Monetizing mobile apps still is in its early stages, and you either have to rely on something like iAds or AdWhirl (which don't pay as much as web advertising), or strike a deal to do some sort of special sponsorship ,which requires more convincing as most companies are not used to doing this..

I would recommend starting with a web app, making that as popular as it can be. Then make a mobile app to increase mindshare, and branding, which in turns increases the popularity of the web app. The mobile app is a slave to the web app, as it's hard for a mobile app to be financially successful alone. Even mobile apps like Foursquare have not solved the question on how to make money.

ContentLicense: CC BY-SA 2.5

Title: How to decide : Phone App or Web App


答:
This is a very timely question to me, as in the legacy code I am working with, most of the Javadoc falls into this category. It is usually autogenerated, with either no useful information added by hand, or the info being out of date (or copied unmodified from another method's Javadoc).

The most annoying is the autogenerated Javadoc for trivial getters and setters on POD classes (we have lots of these). When I see a class having 50 or more fields, containing not much more than getters and setters for these fields, and the useless Javadoc taking up more than half of the screen real estate, I often end up removing it completely.

Javadoc for nontrivial methods is a different case. If it contains any useful info and/or it is for a public method, I prefer to keep it (and improve if possible).

Title: Do we need "obvious" Method Documentation information?

Body:
I know we have questions about comments in general but I'm specifically wondering about Java Doc style method documentation here.

I've been pruning unnecessary comments as I refactor and I've noticed our code has painfully obvious descriptions of methods.

```<code>/**
* @name save
* @desc Validates and saves submitted daily plant production information.
*/
</code>```

Most of the "documented" functions are just method names used by convention in our MVC framework (CakePHP). It's inherently obvious that the save method in the Production Controller performs the necessary actions to save Production Information.

We don't actually use Java Doc and I question the value of these descriptions even if they were included in Java Doc style documentation. The only reason I haven't touched these because they're method documentation that's supposed to be valuable. The method documentation also hasn't been used consistently, about half of our Controller/model methods are documented.

Is there any reason to keep these obvious "Java Doc" comments or should I prune them in favor of "self documenting code" and only make Java Doc comments for less obvious methods?


问:
Pronunciation in programming?
How do you correctly or erroneously pronounce programming terms?  Any that you find need strict correction or history into the early CS culture?

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

regex = "rej ex" not "regg ex"?

sql = "s q l" not "sequel" (already answered, just i.e.)

Unixen

| = pipe not vertical bar?

bin = bin as in pin , not as in binary?

lib = lib as in library , not as in liberate?

etc = "ett see" , not "e t c" (as in /etc and not "&c")

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答:
char = "tchar"

! = punto esclamativo (in Italian)

# = "sharp" or I strangely say 'S' (like 'ess') if it's a C preprocessor statement O_O

#! = shebang

* = asterisco (italian again)

regex = "rej ex"?

sql = "s q l" or "sequel"

Unixen

| = pipe?

bin = bin as in pin

lib = lib as in liberty?

etc = "etch"

Annoyance

/ = slash (and it's correct, this -> \ is the backslash

LaTeX = "latek"

Title: Pronunciation in programming?


问:
Coding Guideline : Methods shouldn't contain more than 7 statements?
I was looking through the AvSol Coding Guidelines for C# and I agree with nearly everything but I'm really curious to see what other think of one specific rule.

AV1500

Methods should not exceed 7 statements  A method that requires more
  than 7 statements is doing too much, or has too many responsibilities.
  It also requires the human mind to analyze the exact statements to
  understand what the code is doing. Break it down in multiple small and
  focused methods with self-explaining names.

Do most of you follow this rule? Even if there's little to be saved from creating a new method (Your code is still DRY) aside from greatly increasing readability?  And is your number still as low as 7?    I would tend more toward 10.

I'm not saying I violate this rule all over the place--on the contrary, my methods are 95% small and focused but saying you should never violate this rule really blew me away.

I really just want to know what everyone thinks of NEVER violating this rule (It's a '1' on the coding standard--meaning NEVER do this).  But I think you'd have trouble finding a codebase that doesn't.

答:
The question is conflating "rules" with "guidelines". Rules are meant to be obeyed - guidelines are advice that are meant to cause you to consider what you are doing and if it really could be done in a better way.

I'd say, on average, most programming is probably improved by following guidelines but there will always be cases where following the guidelines dogmatically will cause more problems than they were intended to resolve. That's why they are not presented as rules, but guidelines.

A previous answerer has shown that the writers of the guidelines never intended them to be applied dogmatically and included statements to that effect in their document.


答:
I use this rule.

If the code itself is self documenting, then there is no need for these obvious comments. But during code review if the code reviewer feels it is difficult to understand the code in the first review, that means that the code needs some comments. I would go and add these comments.

Also if the code is impacted by internal features like thread safety / caching , it is better to add comments to the code indicating that

/* This code is not thread safe */ etc


问:
why do some job posts say "high pressure environment"?
Why would there be any pressure if everyone knows what they are doing and the projects are accurately estimated? If there's pressure, or even high pressure, then it implies what they are currently doing is not working, why would any good programmer want to join a team like that? Are these kind of job posting failed at trying to show off or are they really just being honest? Or is there really some good reasons for having pressure?</p>

答:
Example high pressure job: High frequency algorithmic trading. A software engineer friend of mine is working for a trading shop. Huge stress, huge pressure. All deadlines are "right now". Everything is shipped to production on the day it's written. Even a few minute delay could cost the company millions. Not many people can handle an environment like this. If you can do it, expect a 50-100% higher salary than industry standard at your level + end-of-year bonus based on % of your algos' profits. It's super high-risk, high-pressure, high reward. It has nothing to do with unrealistic deadlines or lacking management, and everything to do with your ability to handle the pressure. (And traders swearing at your face as their P&L goes down the crapper that day.)

Other examples:

Jobs where producing the kind of software with high-requirements for dependendability:

medical software,

embedded software.

Jobs where deliverables (and failures) would have:

a direct and large impact on people,

a direct and large impact on the company's image.

Alternatively, it's not necessarily just code for "we're under-resourced and have unrealistically aggressive deadlines", but also possibly code for "your responsibility makes you an expendable liability if anything goes awry".


问:
Is it possible to combine programming languages?
I've been programming for a while, I've written some rudimentary programs, and I want to keep learning. I've reached that point where you just don't know what to learn next, and I'd like to ask a question for my own curiosity.

The question, in a nutshell, is if you can combine multiple programming languages into 1 result? For example, can this code be possible?

```<code><html>
cout << "Hello world!";
</html>
</code>```

or

```<code>import java.util.Scanner;
cout << "Insert a number from 1 to 10";
Scanner n = new Scanner(System.in);
System.out.println("The value you entered was" +n.newLine());
</code>```

This feels like a silly question but I can't possible know if it's possible or not, so that's why I'm asking it. In this question I notice he is using Python code in html code, if my above example is not possible, what did he do?

答:
Language is a tool. Before choosing a tool (moreover, making some weird hummer-PC-spectroscope combination) one should ask himself - what exactly is it that I want to do??
Once the answer is given, you will find out that such kind of languages mixture is seldom necessary. </p>


答:
Someone's obvious can turn out to be other person's mystery.

It depends on the context to know what is valuable or not :

An obvious thing may not be a good thing in some case: for example,
* If the comment right a narration translation to code as is than there is really no value reading it.

However, sometimes you may answer

why is this method useful?

or better even -

"Don't supply NULL value - there is No ASSERT here" -

this would be obvious to someone who has written a code, but avoids great pit falls to someone reading first time.

The most common things that doesn't get commented because the developer things it is obvious - is the name and meaning of variables (or even methods sometimes) and almost always we find the peer developer snatching hair way too often.


答:
I learned most of my programming lingo from my roommate in college who was also a CS major. Only thing he did "wrong" was intentionally pronounce "sql" as "ess coo ell":

regex: regg exx

lib: as in liberation (from Windows)

bin: as in clothesbin

etc: et cetera (from the Latin and so on)

|: pipe

#!: the "bang line"

#: hatch mark

Title: Pronunciation in programming?

Body:
How do you correctly or erroneously pronounce programming terms?  Any that you find need strict correction or history into the early CS culture?

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

regex = "rej ex" not "regg ex"?

sql = "s q l" not "sequel" (already answered, just i.e.)

Unixen

| = pipe not vertical bar?

bin = bin as in pin , not as in binary?

lib = lib as in library , not as in liberate?

etc = "ett see" , not "e t c" (as in /etc and not "&c")

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"


问:
Is continuous creation and deletion of tables a sign of an architectural flaw?
Recently I had a discussion with a developer who mentioned that during program development, they routinely create and delete tables and columns on a regular basis while working on new features and justified things by saying that this is normal when using an agile development process.

As most of my background is in a waterfall development environment, I wonder if this is actually considered proper under agile development, or if this might be a sign of an underlying problem, either with the program architecture or with their following of the agile process.

答:
There isn't as much focus on design up front when working under Agile, so I don't see this as being a huge problem, certainly for the first release.

It is hard to comment on a system that has 700 tables I haven't seen, it may well need all of them, but it could also be the case that the database hasn't been managed well enough.

Even under agile, for a big system, it is quite common to still have someone/team in charge of the schema.


答:
If your database can be easily versioned and migrated and you've got the tests to prove that changing things did not break things then you've probably got a pretty agile process going.

In light of the comments -- generally to the effect of these are a bunch of cowboys justifying themselves as agile -- run screaming. Fast. And post all that you can to thedailywtf.com so we can all enjoy your horror.

Title: Is continuous creation and deletion of tables a sign of an architectural flaw?

Body:
Recently I had a discussion with a developer who mentioned that during program development, they routinely create and delete tables and columns on a regular basis while working on new features and justified things by saying that this is normal when using an agile development process.

As most of my background is in a waterfall development environment, I wonder if this is actually considered proper under agile development, or if this might be a sign of an underlying problem, either with the program architecture or with their following of the agile process.


答:
This might be best answered in two parts:

General Case - If the project is going to be worked on by more than one person and the method documentation is going to be published in such a way that it can be read separate from the code itself (i.e. a website with Javadoc published), the method documentation should be in place and accurate since someone might go to the Javadoc first. When you are working on a project where there is an API involved this becomes even more important as you should not have to read the API's source code to determine if you can or cannot do something.

Specific Case - For the specific case you are provided, I'd likely clean them up and leave them in place if only so you can use the search capability of your IDE to find a method. In the example you provide above, unless all of the save methods in the program start by doing the validation, it really should be mentioned in the comment. If the validation is in another function that is being called by the save method then it could likely be stripped from the comment.


答:
While it is not unusual to create and drop tables as a design evolves, some cleanup might be in order to make sure your database is really using all those tables.

Yes, Agile is all about refactoring, but if they are now saying the system is too big to refactor, they have stopped doing Agile and are now just Cowboy programming.  The development team won't like being called that, but that is what they are doing.  Riding the range shooting anything that moves.

A DBA will help, just make sure you get a DBA that understands development as well as Agile development.  Your development team needs to be reined in, not thrown in jail.


答:
It's becoming more-and-more apparent to me every day that "agile" is becoming a synonym for poorly thought-out, chaotic, hurried and seat-of-your-pants. And none of those things are compatible with an Agile approach as I understand it.

Having an effective and repeatable Agile process is not easy, and I don't believe that it inherently reduces the total amount of work to be done even though it may very well lead to better products.

If they've said that they don't have time to "refactor" the database then they probably also don't have time to set up versioning and migration for the database. They probably haven't taken the time to create a suite of functional tests for it. All of those things are what I think of when I think of a solid Agile process that's headed for success.

In the end, Agile is just a word. What you are doing day-to-day determines if you'll be successful or not.


问:
How does using #define for loop and condition bounds in C increase security?
My program uses the following define statements:

```<code>#define LOWEST_PATIENT_ID 10000
#define HIGHEST_PATIENT_ID 99999
#define LOWEST_CRITICAL_STATUS 1
#define HIGHEST_CRITICAL_STATUS 100
</code>```

used in this type of code:

```<code>do{
   scanf("%d", &c_status);
   }while((c_status<LOWEST_CRITICAL_STATUS)
           ||(c_status>HIGHEST_CRITICAL_STATUS));
</code>```

I'm unclear about how this is more secure. or is it the typedef statement that is secure?

答:
It doesn't.

#define statements in C aren't really useful for security. The use you put them to here is a means of improving readbility (and whether it does that is debateable) and of having what are, in effect, global variables in the file without having to worry about scoping.


答:
If this project is to have any longevity, you should keep the obvious documentation.  It's obvious to you that a function called save "validates and saves", but I would have never guessed that save validates, since it's not called validateAndSave.  As others have said, it's hard to define what is obvious; perhaps obviousness comes from conventions, such as "every save function validates."  If someone comes from a different project with different conventions, you might end up with many similarly-named methods that fit into two categories.  Then we have "Ben's save methods validate and save, and Don's save methods log to an audit mechanism and save."

Unless the method does exactly what it said and absolutely nothing else (apart from setters and getters, I think this is relatively rare), you need the documentation.


问:
How close have we gotten to automating code writing?
And I don't mean Autocomplete or automatic code snippets as inserted by modern day editors, or polymorphic code. But what is the state-of-the-art in programs that can go through given inputs and types and information of the desired outputs and output a valid piece of code in a language of choice. I am aware of Genetic Programming, Gene Expression Programming but I don't know of any other efforts. Also googling doesn't turn up much.

Is anyone aware of any advancements on this front?

Edit: When i say "output a valid piece of code", I mean an AI or something similar working out the logic and the flow of control and implement it in an imperative language. Imperative language only, since that's the tough part. Nevertheless, if you know of any new languages being developed to support this kind of idea, please do mention, as maybe our current set of languages are not suitable for the kind of early AI we may first chance upon.

答:
How close have we gotten to automating code writing?

no where near anything that's worth talking about.

I also strongly put it that we will never get there either.


答: I think it would be worth mentioning Cython here. It's a superset of Python for writing C extensions and although it is really a unique language in itself, it pretty much allows you to use C code in Python code, if you conform to Cython's Python style syntax</p>

Title: Is it possible to combine programming languages?

Body:
I've been programming for a while, I've written some rudimentary programs, and I want to keep learning. I've reached that point where you just don't know what to learn next, and I'd like to ask a question for my own curiosity.

The question, in a nutshell, is if you can combine multiple programming languages into 1 result? For example, can this code be possible?

```<code><html>
cout << "Hello world!";
</html>
</code>```

or

```<code>import java.util.Scanner;
cout << "Insert a number from 1 to 10";
Scanner n = new Scanner(System.in);
System.out.println("The value you entered was" +n.newLine());
</code>```

This feels like a silly question but I can't possible know if it's possible or not, so that's why I'm asking it. In this question I notice he is using Python code in html code, if my above example is not possible, what did he do?


答:
The point of javadocs is to provide information that isn't immediately obvious from just reading the method signature. Otherwise, it's just a waste of space. I disagree with the people who say that you shouldn't remove useless comments just for the sake of removing: those comments waste developer time, since the developers won't know that they're useless until after they read them. Go ahead and delete.

But an even better idea is to edit it so that it does provide useful information.

Before:

```<code>/** Sets the monkeyName field.
 * @param name - the monkey's name.
 */
public void setMonkeyName(String name) {
</code>```

After:

```<code>/** Validates and stores the monkey's name per RFC 420, Monkey Enterprise Data Protocol.
 *
 * @throws IllegalArgumentException if the name fails validation
 */
</code>```

Body:
The point of javadocs is to provide information that isn't immediately obvious from just reading the method signature. Otherwise, it's just a waste of space. I disagree with the people who say that you shouldn't remove useless comments just for the sake of removing: those comments waste developer time, since the developers won't know that they're useless until after they read them. Go ahead and delete.

But an even better idea is to edit it so that it does provide useful information.

Before:

/** Sets the monkeyName field.
 * @param name - the monkey's name.
 */
public void setMonkeyName(String name) {

After:

/** Validates and stores the monkey's name per RFC 420, Monkey Enterprise Data Protocol.
 *
 * @throws IllegalArgumentException if the name fails validation
 */


问:
Add a unit test for each new bug
In my job all developers that resolve a bug have to add a new unit test that warns about this type of bugs (in the case it occours again). If a unit test is not possible (for example, a webpage design issue), then QA department has to create a test case to manually check it.

The idea behind this is that if a defect has not been detected before the product release is because there isn't an appropriate unit test to detect it. So the developer has to add it.

The question is: is this common in any software development methodology? This technique has a name? I would like to learn more about it, but I need some information to start with it.

答:
Absolutely!

If you can agree that unit tests are a good thing, then you will realise that if there is a bug then there is a missing unit test covering that code path.

So what should happen is, you write a unit test that shows the bug exists, fix the actual bug, then the unit test will pass.

If you have no unit tests at all, then this can be a good way of starting to introduce unit tests to a project.

Title: Add a unit test for each new bug


答:
This is quite common. We use this in our team. For Every production defect, the developer must add a note on the root cause of the problem , add a failing unit test and add a test impact analysis before the ticket can be pushed to dev state to check in the code.

The failing unit test must pass before we can push  the code to production.

I don't think this has a specific name except that general "regression testing". This is very useful and we have started seeing a rise in the quality of the product after we started following this process.

Title: Add a unit test for each new bug

Body:
In my job all developers that resolve a bug have to add a new unit test that warns about this type of bugs (in the case it occours again). If a unit test is not possible (for example, a webpage design issue), then QA department has to create a test case to manually check it.

The idea behind this is that if a defect has not been detected before the product release is because there isn't an appropriate unit test to detect it. So the developer has to add it.

The question is: is this common in any software development methodology? This technique has a name? I would like to learn more about it, but I need some information to start with it.


答: Agile is about coding, Databases aren't code. Changing a database should be treated like remodeling a house. People somehow got the belief that agile means act now plan later, which is completely untrue. Even under agile methods time needs to be given for planning, especially for something as important as database design.</p>


问:
Reflection and the LGPL
Simply, If I use reflection to add methods or functionality to a class defined in a LGPL'd library I'm linking to, does that count as a modification to the existing library and would my reflective code have to be released under the LGPL?</p>

答:
http://www.gnu.org/licenses/lgpl-3.0.en.html

I'd say that reflecting into the LGPL lib is a 'combined work' and so is subject to the limitations described in the licence:

A “Combined Work” is a work produced by combining or linking an
  Application with the Library. The particular version of the Library
  with which the Combined Work was made is also called the “Linked
  Version”.

The “Minimal Corresponding Source” for a Combined Work means the
  Corresponding Source for the Combined Work, excluding any source code
  for portions of the Combined Work that, considered in isolation, are
  based on the Application, and not on the Linked Version.

The “Corresponding Application Code” for a Combined Work means the
  object code and/or source code for the Application, including any data
  and utility programs needed for reproducing the Combined Work from the
  Application, but excluding the System Libraries of the Combined Work.

So, given these definitions (where your reflecting into the library is equivalent to linking with it and the code that does the reflection is the minimal corresponding source) you have to follow this section:

Combined Works.

You may convey a Combined Work under terms of your choice that, taken
  together, effectively do not restrict modification of the portions of
  the Library contained in the Combined Work and reverse engineering for
  debugging such modifications, if you also do each of the following:
   ...

d) Do one of the following:

0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.

1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.

so I'd say (Note: IANAL) you'd have to release the reflecting code part of your app under the LGPL too, though the section of your app that uses that code can still be proprietary.

Title: Reflection and the LGPL


问:
Should developers be expected to compile an internal library before the actual program?
Recently a senior developer that I work with made a case for requiring that developers get the latest version and compile as part of their project a major internal library. This stands in contrast the the counter argument that project teams should be working off a stable version that they get from an internal Maven repository; to which the developer argued that having the source code available on the developer machines saves time, as they can read the library's source code to determine if required functionality is available.

Does the senior developer have a valid argument? Or is requiring developers to read the library's source code run counter to the basic philosophy of encapsulation, and even having the library in the first place?

答:
I used to work for a large software company who was constantly "dogfooding" their own software with internal business systems.

They saw this as another level of testing.

That I agree with, for a company, is a good thing.

I think forcing you to download, and compile the latest version is a step too far, unless the compilation step is an important part of your companies offering of selling, or even outsourcing, a library.

ContentLicense: CC BY-SA 4.0


答:
Like most answers here on StackExchange, the reply should be 'it depends'. In agile development, requirements and specifications are discovered during implementation.

However, given agile development, when a relational model is properly normalized, adding new attributes to relations should rarely be a necessity , new entities should generally refer to older ones, given a proper model.

Most developers don't normalize their DB's because of time-constraints, laziness, incompetence or query complexity. Renormalizing requires transfer of existing data, modification of the DAO's, etc. etc. which generates a risk-factor.


答:
My last job was on a team like this.  When using an agile process requirements change.  Sometimes the changes mean a existing entity needs a new attribute resulting in a new column in an existing table or a whole new entity is required resulting a new table with relationships to existing tables.  These kinds of changes come with the territory and can't be ignore just because you don't want to touch the schema.  Success is determined by maintaining the integrity of your data when migrating from one database version to the next and proper unit testing.

Just try not to make unnecessary changes to your schema.  For example, if a feature requires a new table to be created, make sure you're happy with the definition of that table before you check it in and roll it out to your test environment.  Having to undo a change to your database schema after your data has been migrated can be painful.


答:
I ignore those kinds of jobs postings now.  What they mean is we want a slave who will work 80 hours a week and not get paid squat.  It is a sign that management is not bidding projects correctly or not managing projects correctly.

Well run teams run on time and without extra stresses, like managers that take on 100 new requirements and try to keep the date.  I haven't had a death march in years.  The closest thing was when I came back to a failing project as a consultant making exorbitant hourly rates and worked a long holiday weekend to bail out some major fail.

Title: why do some job posts say "high pressure environment"?

Body: Why would there be any pressure if everyone knows what they are doing and the projects are accurately estimated? If there's pressure, or even high pressure, then it implies what they are currently doing is not working, why would any good programmer want to join a team like that? Are these kind of job posting failed at trying to show off or are they really just being honest? Or is there really some good reasons for having pressure?</p>


答:
In general, often creating new tables and adding new columns is very normal in a process where programming and database administration are not strictly separated. A new feature might create new data that must go somewhere. Try too strictly to avoid that and you end up with an inner-platform model.

Well-written software hardly notices those new database objects, so nothing breaks just because of a new column in some table.

On the other hand, regularily droping columns or even tables is suspicious. A new feature never needs a table removed, so this could be a sign of people working completely planless.


答:
This senior developer's argument makes no sense to me.

They want to add overhead of constantly retrieving & compiling an internal library just so devs can occasionally read the source code?  That's going to waste a lot more time than having devs go look at the source code only when they need to check if a feature is available.

This is a particularly bad idea if the library and the clients are being developed by different development groups and the library is being actively developed.  The client developers won't have any insulation from instability in the library.

I don't see why source code can't be made available to the developers without forcing them to have it be part of their normal build.

Title: Should developers be expected to compile an internal library before the actual program?

Body:
Recently a senior developer that I work with made a case for requiring that developers get the latest version and compile as part of their project a major internal library. This stands in contrast the the counter argument that project teams should be working off a stable version that they get from an internal Maven repository; to which the developer argued that having the source code available on the developer machines saves time, as they can read the library's source code to determine if required functionality is available.

Does the senior developer have a valid argument? Or is requiring developers to read the library's source code run counter to the basic philosophy of encapsulation, and even having the library in the first place?


答:
I wouldn't buy the argument that having the ability to peruse the source locally is a benefit, but if the library is in active development (possibly to add support for your project's needs) then I don't think it's unreasonable to require developers to download updates frequently (possibly several times a day).  I think it makes better business sense to make a compiled (and unit-tested) binary available instead of requiring developers to compile from source, though.

Do you have the ability within your project to set up some kind of shared repository where the latest compiled version would be available?  Ideally you'd want a CI server that did the fetch-and-build on a schedule, but even if it's just a network resource that one of the team leads is responsible for updating periodically it might help.  Of course, this should be on the library team's plate, but obviously they're not interested, so you'll have to pick up their slack.


答: They can provide a degree of protection from buffer overflow-type attacks, since the range of the loop index is limited by a hard-coded value (presumably in a read-only area of memory) instead of being stored in a writable variable.</p>

Title: How does using #define for loop and condition bounds in C increase security?

Body:
My program uses the following define statements:

```<code>#define LOWEST_PATIENT_ID 10000
#define HIGHEST_PATIENT_ID 99999
#define LOWEST_CRITICAL_STATUS 1
#define HIGHEST_CRITICAL_STATUS 100
</code>```

used in this type of code:

```<code>do{
   scanf("%d", &c_status);
   }while((c_status<LOWEST_CRITICAL_STATUS)
           ||(c_status>HIGHEST_CRITICAL_STATUS));
</code>```

I'm unclear about how this is more secure. or is it the typedef statement that is secure?


问:
Should I invest time learning Coffeescript?
I am a freelancer and I earn my bread and butter by helping others write better java-script code. I have good experience with most of the JavaScript frameworks around. </p>

<p>I am wondering if it is worth for me to invest time in learning coffeescript. Who should learn it and who need not ? </p>

答:
I made the conversion from JavaScript to CoffeeScript about 6 months ago and I love it, there are so many places where the syntax just makes life a little easier.

For example you can de-structure  an object in an assignment so I just wrote some code like this

```<code>func = ({io: io, el: el} -> ...
</code>```

So you pass it an object and it breaks it apart into its parts, I really love coffeescript

OwnerDisplayName: Akshar Prabhu Desai

Body:
I made the conversion from JavaScript to CoffeeScript about 6 months ago and I love it, there are so many places where the syntax just makes life a little easier.

For example you can de-structure  an object in an assignment so I just wrote some code like this

func = ({io: io, el: el} -> ...

So you pass it an object and it breaks it apart into its parts, I really love coffeescript


答:
While having the source code available can be a benefit, if you have a CI build agent monitoring the repository, it makes WAY more sense to have that agent compile this library and copy it into dependent projects as an external, than to require the developers to run two different compilation steps when building their copy.

I'm currently working on a project that isn't hooked up to a build agent, that requires building a sub-application before building the main application. It's a serious pain in my posterior; to make a change to the sub-app, I must first build the entire project, then go to a sub-build folder, get the compiled product out of that and copy it to a different sub-folder, before building the entire project AGAIN to make sure the latest version of the sub-app is included in the build of the main app. This is NOT how it should be done; at the very least there should be an MSBuild script that will automate this process, and I would prefer that the build agent update the externals whenever new code is committed to the trunk.


答:
The technique is test-driven development. It's not really about being able to spot a similar bug next time, although the suite of repeatable tests is always helpful. The point is that you can demonstrate that you've isolated what is wrong with the code, proved that it is wrong, fixed it, proved that the fix is correct.

There's a quote that I can't quite recall or find, but roughly it is: "Every bug is a test not yet written."

Trying to sell it as a regression test is a lost battle, IMHO. Given how infrequently these things catch a repeated bug, most developers will just say, "Why bother, when I can simply fix it?"

Title: Add a unit test for each new bug


答:
The suggestion is

We can save time by client-side developers reading the library's source code to determine if required functionality is available

You could make an alternative suggestion

We can save time by someone documenting the library to indicate what functionality is available.


答: It means they never heard of Agile or Scrum or Kanban, and they don't care about burning out their developers.</p>


问:
When do you drop old technologies from your resume?
I have been reviewing several resumes we have for a new position.  I noticed that a few of them had many old programming language versions and old applications on their resume (e.g. SQL 4.2, VB5, Lotus 123, Novell).  This left their list of computer experience very long.  Do you keep it fresh?  Do you show your depth of experience even though you will never use that techology again?

When should you drop old technology on your resume?  By keeping old technology on your resume does that do any harm in getting hired?

答:
For a job-specific CV:
If you really want the job (and you should, if you're applying for it, unless you're the kind of developer who just applies for anything) then you should pare down the experience and skills to those that are directly relevant to the position. Old technologies may belong on there if they are relevant.

For a more general CV:
If it's the kind of CV that runs over two pages and covers your entire career, there's no reason to take anything off that you're proud of.


答: I'd say this is hardly different from creating a new class by extending a base class in an LGPL library.  You're just doing the introspection at run time instead of compile time.  Therefore, it's a derivative work, which doesn't require you to disclose your source code.</p>

Title: Reflection and the LGPL

Body: Simply, If I use reflection to add methods or functionality to a class defined in a LGPL'd library I'm linking to, does that count as a modification to the existing library and would my reflective code have to be released under the LGPL?</p>


答:
What the Sr Dev is suggesting makes little sense to me at best. It is nice to be able to browse sources, but there are better ways to do so.

What Artifact Repository are you using? You should be able to deploy a source jar for each version to live next to the compiled library. Most IDEs will then allow you to attach this to the compiled library for source browsing. Eclipse with the Maven Plugin will do this automatically.

If you need the very latest code, you can just deploy version snapshots.


答:
This should simply happen in your build script:

check whether a new version is available. skip 2 otherwise.

download and compile it and run whatever tools you have to generated an API reference from the source code locally. show a change log.

build your app

I don't see why or how this is a problem. Also when something is missing in the reference, you can add it to the sources and push the changes. Of course it might seem a little scary that the library can change right under your feet, but if the library maintainers do their job properly, this is a good thing.


问:
Would you allow your programmers to use Messenger and social networks like Facebook?
I had many bosses, each one had a different approach about allowing or not use of Windows Live Messenger, Facebook, and many other Internet sites.

Of course Internet is really needed to research about the best way to solve a specific task. Sometimes you could have a friend online, also a programmer, who knows better about something.

For some managers, internet access would slow down project progress, and on the other hand, allow people to interact and find out brand new solutions.

What would you do?

答:
My personal belief is people in all professions, but especially creative/problem solving professions need mental down time through out the day. Sure, you could stand behind your programmers cracking a whip and yelling, "More code!", and the project will probably get done on time and on budget, but you will get a mediocre product. They'll cut corners and write sloppy code just to get you off their back, and their minds won't be engaged enough to come up with elegant solutions.

Anytime I've had programmers working under me I've always encouraged them to take time off through out the day. Read a book, listen to music, play some basketball outside, or even spend some time on Face/Digg/Reddit/Whatever if that's what they like. All I care about is the final product. I don't care how they managed their time to achieve great results.


答:
State of the art in automating code writing? There is no "state of the art".  But there is a state of perpetual failure. There are no successful attempts so far. Most likely there will never be any successful implementation of this other than a few examples that are very limited in scope.

That may be a good thing since it would put us out of a job.

BTW to people reading.... Don't confuse algorithm creation with trivial CRUD generators like Ruby on Rails. CRUD generation is the execution of a predefined algorithm, not the creation of an algorithm to solve a problem.

Title: How close have we gotten to automating code writing?

Body:
And I don't mean Autocomplete or automatic code snippets as inserted by modern day editors, or polymorphic code. But what is the state-of-the-art in programs that can go through given inputs and types and information of the desired outputs and output a valid piece of code in a language of choice. I am aware of Genetic Programming, Gene Expression Programming but I don't know of any other efforts. Also googling doesn't turn up much.

Is anyone aware of any advancements on this front?

Edit: When i say "output a valid piece of code", I mean an AI or something similar working out the logic and the flow of control and implement it in an imperative language. Imperative language only, since that's the tough part. Nevertheless, if you know of any new languages being developed to support this kind of idea, please do mention, as maybe our current set of languages are not suitable for the kind of early AI we may first chance upon.


答:
This kind testing would better be done indeed. Thing is though, it should be done by testers, not by developers. In that sense, it's neither your nor library developer's job.

From what you describe it sounds like there are no testers in the project - if this is the case, that's a management problem, and quite a serious one.

...saves time as they can read the libraries source code to determine if required functionality is available

Quite lame reasoning. When most recent version library fails to compile with most recent version project, there could be multiple various reasons for that - just drilling into lib source code could be waste of time.

What if library is OK and build failure was caused by the bug in project code? Or, what if build failure was caused by temporary incompatible change that is supposed to be corrected a day or two later? What if a build failure indicates a complicated integration issue that will take a week or month to address? For an integration issue, would using a prior version library make a workaround or not?

Whatever the reason could be, doing preliminary analysis of the failure would mean wasting developer's time on a work that is supposed to be done by testers.

Another thing above reasoning misses is inevitable (and quite painful in my experience) productivity losses that follow when one has to break the flow by switching between development and QA activities.

When there are testers in the team, such things are really simple and can be handled much easier. What your "senior" developer cast at you is basically a draft testing requirement.

Upon every change made to the project or library, make sure that build is successful.

Steps to proceed from there are typical QA activities: clarify requirement details, design a formalized test scenario, negotiate on how to handle test failures.

From SQA perspective, this is quite a routine task of designing, setting up and maintaining a pretty simple regression testing procedure that could be highly automated - probably up to the point that only manual activity would be creating and maintaining tickets in issue tracker and verification of fixes.


问:
Why does the stack grow downward?
I'm assuming there's a history to it, but why does the stack grow downward?

It seems to me like buffer overflows would be a lot harder to exploit if the stack grew upward...

答:
program memory is traditionally set up as

```<code>code
constants
heap (growing up)
...
stack (growing down)
</code>```

heap and stack can be exchanged

but buffer overflows can still be exploited if the stack went the other way

taking the classic strcpy as an example

```<code>foo(char* in){
char[100] buff;
strcpy(buff,in);
}
</code>```

with stack memory as

```<code>ret foo
arg in
buff array
ret strcpy
buf pointer
in
</code>```

this would mean that when the copying is done the return address for strcpy is after the buffer (instead of foo's return address) and can be overwritten by whatever is in in

Title: Why does the stack grow downward?

Body:
program memory is traditionally set up as

code
constants
heap (growing up)
...
stack (growing down)

heap and stack can be exchanged

but buffer overflows can still be exploited if the stack went the other way

taking the classic strcpy as an example

foo(char* in){
char[100] buff;
strcpy(buff,in);
}

with stack memory as

ret foo
arg in
buff array
ret strcpy
buf pointer
in

this would mean that when the copying is done the return address for strcpy is after the buffer (instead of foo's return address) and can be overwritten by whatever is in in


答:
I believe it comes from the very early days of computing, when memory was very limited, and it was not wise to pre-allocate a large chunk of memory for exclusive use by the stack.  So, by allocating heap memory from address zero upwards, and stack memory from the end of the memory downwards, you could have both the heap and the stack share the same area of memory.

If you needed a bit more heap, you could be careful with your stack usage; if you needed more stack, you could try to free some heap memory. The result was, of course, mostly, spectacular crashes, as the stack would occasionally overwrite the heap and vice versa.

Back in those days there were no interwebz, so there was no issue of buffer overrun exploitations. (Or at least to the extent that the interwebz existed, it was all within high security facilities of the united states department of defense, so the possibility of malicious data did not need to be given much thought.)

After that, with most architectures it was all a matter of maintaining compatibility with previous versions of the same architecture. That's why upside-down stacks are still with us today.

Title: Why does the stack grow downward?

Body:
I'm assuming there's a history to it, but why does the stack grow downward?

It seems to me like buffer overflows would be a lot harder to exploit if the stack grew upward...


问:
Do we need "obvious" Method Documentation information?
I know we have questions about comments in general but I'm specifically wondering about Java Doc style method documentation here.

I've been pruning unnecessary comments as I refactor and I've noticed our code has painfully obvious descriptions of methods.

```<code>/**
* @name save
* @desc Validates and saves submitted daily plant production information.
*/
</code>```

Most of the "documented" functions are just method names used by convention in our MVC framework (CakePHP). It's inherently obvious that the save method in the Production Controller performs the necessary actions to save Production Information.

We don't actually use Java Doc and I question the value of these descriptions even if they were included in Java Doc style documentation. The only reason I haven't touched these because they're method documentation that's supposed to be valuable. The method documentation also hasn't been used consistently, about half of our Controller/model methods are documented.

Is there any reason to keep these obvious "Java Doc" comments or should I prune them in favor of "self documenting code" and only make Java Doc comments for less obvious methods?

答:
Redundant comments annoy the hell out of me too.

My advice would be to replace them with something better. Just deleting opens you up to missing something and deleting useful comments. If you are confident enough to recomment the method then you should understand it enough to prevent any pitfalls.

Is there any reason to keep these obvious "Java Doc" comments or
  should I prune them in favor of "self documenting code" and only make
  Java Doc comments for less obvious methods?

Your code should be self documenting and have comments. Since half your comments are not in Java Doc style I suggest you phase out Java Doc style comments. Consistency can be very useful with comments, there is no point implementing a style half the time.


问:
PDF help in the software manual
Just need a bit of advice here,  if we embed Adobe Reader as an activex control, as well as have a fallback PDF viewer (in case the user doesn't have Adobe Reader installed) would it be wiser to put screenshots in the manual using whatever the latest version of Adobe Reader is, or using the fallback reader?

I can see the drawbacks and benefits of both.  For one thing, the look and feel of the fallback reader is constant, whereas Adobe Reader changes, so we don't have to redo the manual as often.  But we expect that 90% of users will have Adobe Reader, so what they see in the manual won't even be what's in the program if we use the fallback reader for screenshots.

So what's the solution. Adobe, Fallback Reader or Both?

(For the record, the manual is a CHM, not a PDF)

答:
...what they see in the manual won't even be what's in the program if we use the fallback reader for screenshots

To me above reads as screen shots made that way would be useless (or almost useless). This makes a pretty strong case in favor of Adobe option.

Also it makes sense to smoke test how the manual looks in the fallback reader before releasing it. If testing shows that problem with particular screen shot breaks a large portion of manual when viewed that way, you may reconsider a general preference for that screen shot. Images hacked for fallback reader would need to be re-tested with Adobe.

Title: PDF help in the software manual


答:
There are several tools where you can do things without writing any code (MS Access, Filemaker). Some generate code in the background that can be altered. This works well with business apps and database front ends. The user hits a wall and eventually hires a programmer. The logic gets too complex. I've seen web apps that create a form that populates a table. This is great until you need a parent form with a child form handling multiple records. None of them offer this.

Trying to imagine how this works if I want to automate/code the altering of image, video or sound files. Like a database GUI someone could make them for these that generates code instead of just manipulating the file.

Spread sheets are handling everything from simple math to statistics fairly well. Record a Macro and a script is created.

Complexity ususally catches up. Eventually, you want to create something really new. Tough to build a code generator that creates code for something no one else thought of.


答:
Indexes, limits, bounds, etc., are always security-related with C code because of overflow exploit issues. Specifically, if you get the number wrong, you code is a candidate for exploitation.

Assigning the constant to a symbol does two things: it makes the number easier to verify in a review because it's immediately obvious what the number means, and more importantly, it ensures that every time you use the number in your code, you're using the SAME value.

Imagine, for example, where the number represents the length of the input field, and at some point you increase that length to accommodate larger names. If you've specified the value numerically in your code, you have to go track down every instance of that number and replace it, but only if the instance of that number represents your specific field (you can't just use search and replace to change every instance of 128 to 256 because the number could mean different things).

Furthermore, in some instances you may be using N+1 (e.g. to allow for termination), so you'd have to track down every instance of 128 and every instance of 129. And was there a reason to specify 130 as well? Oh, now it's difficult to remember. But don't miss any of them of you'll create a classic buffer overflow exploit.

If instead you just did #define FIRST_NAME_LENGTH 128 in one of your include files, and keyed all the corresponding values off that, then you can just change the number once and be done with it.

This is true even in instances where you only use the number once, because while you're CURRENTLY only using the number once, someone may need to extend the code in the future.

This is such an important issue that you should have been taught from day 1 to avoid "magic numbers" in your code. If the number "means" something, then you should make its meaning explicit.


答:
To answer your question, no, that isn't normal in an Agile process.

Where it may seem to stem from an Agile attitude is from Agile's short-iteration design/develop/test cycle, and Agile's emphasis on lightweight solutions that meet the known requirements, but are well-structured in order to be able to meet new requirements with minimal change. Given these two things, you might say that a developer, not knowing what might come down the line but knowing his change shouldn't impact the DB in a way that can't be undone, simply makes the necessary changes to the schema in the "lightest" way possible, and then at intervals several sets of "light" changes will be refactored into something more permanent and stable.

Having said that, I have not yet worked with a developer who subscribed to Agile theory and methodology, and also thought that routinely creating and deleting tables in the schema was necessary for any reason. Agile doesn't mean slap-dash or bolt-on. If you are given a story that requires the addition of a new field of data belonging to a particular record, you add the field to the table. If that change breaks something, you figure out why, and make other changes as may be necessary (I can think of very few things that would break by adding a column to a DB being queried; if it does break with this kind of change you have bigger problems). Refactoring is normally limited to code; changing the schema is usually a more involved process than changing code, and so when schema changes must occur they are usually made with more care, and at least some attention paid to knowledge of the future direction of the project. Having to re-structure some or all of the database indicates a fundamental failure of design; being Agile doesn't mean there isn't a "master plan" of basic architecture and design rules to follow while organically building the program and data structure.

Now, there are cases in Agile where what you "know" now will be contradicted by what you will learn later. Say you have a requirement that your system must have an Address for every Person. Since this is a 1:1 relationship and the data will be needed in the majority of cases, you simply add the Address fields to the Person table. A week later, you receive a requirement that a Person can have more than one Address. Now it's a 1:N relationship, and to properly model it you must undo your previous changes, splitting the fields out into a new Address table. This is not routine, especially among senior developers. An experienced developer will see that a Person has an Address, consider these as conceptually separate, and create a Person table and an Address table, linking Person to Address with a FK reference to an AddressID. A schema such as this is easier to change should the nature of the relationship change; without creating or deleting entire "wide" data tables, the relationship between Person and Address can be pretty easily modified from 1:1 to 1:N to N:N.


答:
The one place where it's okay for this to pop up is if you'll have a job where lives are on the line.

For example, if you're the sys admin for services that must be up in order to keep airplanes in the sky, you should expect it to be high pressure. Or, if you work on software that will be deployed for soldiers in a warzone, you can expect pressure.

If you see this, ask the interviewer if lives are on the line if you miss a deadline or alarm. If not, they're being dramatic.


问:
should I throw exception from constructor?
I know I can throw exception from constructor in PHP but should I do it? For example, if a parameter's value is not as I expected it.

Or should I defer throwing an exception till a method is invoked. What are advantages and disadvantages in both cases?

答:
I know I can throw exception from constructor in PHP but should I do it?

That is the only sane way to inform that the object construction failed.


答:
In this particular case, it's not about security so much as it is readability and maintainability.

LOWEST_CRITICAL_STATUS and HIGHEST_CRITICAL_STATUS convey more meaning than a literal 1 and 100 do.  Also, if the value of either symbol needs to change, you only need to change it in one place, as opposed to hunting for every occurrence of a 1 or 100 in your source code (understanding that there may be some occurrences of 1 or 100 that shouldn't change).


问:
Pronunciation in programming?
How do you correctly or erroneously pronounce programming terms?  Any that you find need strict correction or history into the early CS culture?

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

regex = "rej ex" not "regg ex"?

sql = "s q l" not "sequel" (already answered, just i.e.)

Unixen

| = pipe not vertical bar?

bin = bin as in pin , not as in binary?

lib = lib as in library , not as in liberate?

etc = "ett see" , not "e t c" (as in /etc and not "&c")

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答:
char =  character

!    =  exclamation

#    =  hash

*    =  Star

regex=  rej x

sql  =  S Q L

Title: Pronunciation in programming?


答: If they are making such changes frequently - particularly dropping tables and columns in live applications - that seems like a sign of inexperience.  It has nothing to do with whatever process they are claiming to follow.  'Agile' is not an excuse to not sit down and think about the data you need to store and how it relates before you start pounding out code.  If they find they are altering more than 10-20% of the initial structure, to me thats an indicator they're either not thinking things through or they dont have a lot of experience analyzing requirements and designing databases, and so they simply get too much of it wrong at the beginning.


问:
Could you describe "GNU General Public License (GPLv2)" in "for Dummies" terms?
I just want to make sure I'm using the right license for my open source API wrapper project for some social networks and also make sure I understand it. Could you just describe the basics of that license? What I can and can't do, etc? Does these things suit the GPLv2 license:

Open Source'ness

Ability to use it in your own project

But also give credit for it on ones website and keep copyright notices at the top of source files

Have control over it as in if you don't like how someone is using your code, you can report it somewhere after contacting the developer.

I would also like to make commercial versions and add ads to my project - so exceptions in the license would be noted.

Thank you all for your answers and comments. I've gone with the shorter and easier to understand New BSD License (BSD). Thanks anyway.

答:
Basically you're saying:

Please feel free to do whatever you want with this.

As long as you give me credit for my work.

And as long as you make the source code available to anyone you distribute whatever you build on top of my work to.

And as long as you extend these same rights to those who you distribute to.


问:
Is coupling with strings "looser" than with class methods?
I'm starting a school group project in Java, using Swing.  It's a straightforward GUI on Database desktop app.

The professor gave us the code from last year's project so we could see how he does things.  My initial impression is that the code is far more complicated than it ought to be, but I imagine programmers often think this when looking at code they didn't just write.

I'm hoping to find reasons why his system is good or bad.  (I asked the professor and he said I'd see later on why it's better, which doesn't satisfy me.)

Basically, to avoid any coupling between his persistable objects, models (business logic), and views, everything is done with strings.  The persistable objects that get stored in the database are hashtables of strings, and the models and views "subscribe" to each other, providing string keys for the "events" they subscribe to.

When an event is triggered, the view or model sends a string to all of its subscribers who decide what to do for that event.  For instance, in one of the views action listener methods (I believe this just sets the bicycleMakeField on the persistable object):

```<code>    else if(evt.getSource() == bicycleMakeField)
    {
        myRegistry.updateSubscribers("BicycleMake", bicycleMakeField.getText());
    }
</code>```

That call eventually gets to this method in the Vehicle model:

```<code>public void stateChangeRequest(String key, Object value) {

            ... bunch of else ifs ...

    else
    if (key.equals("BicycleMake") == true)
    {
                ... do stuff ...
</code>```

The professor says that this way of doing stuff is more extensible and maintainable than having the view simply call a method on a business logic object.  He says there is no coupling between the views and models because they don't know of each others' existence.

I think this is a worse kind of coupling, because the view and model have to use the same strings in order to work.  If you remove a view or model, or make a typo in a string, you get no compile errors.  It also makes the code a whole lot longer than I think it needs to be.

I want to discuss this with him, but he uses his industry experience to counter any argument that I, the inexperienced student, might make.  Is there some advantage to his approach that I'm missing?

To clarify, I want to compare the above approach, with having the view be obviously coupled to the model.  For instance, you could pass the vehicle model object to the view, and then to change the "make" of the vehicle, do this:

```<code>vehicle.make = bicycleMakeField.getText();
</code>```

This would reduce 15 lines of code that are currently ONLY used to set the make of the vehicle in one place, to a single readable line of code.  (And since this kind of operation is done hundreds of times throughout the app, I think it would be a big win for readability as well as safety.)

Update

My team leader and I restructured the framework the way we wanted to do it using static typing, informed the professor, and ended up giving him a demo.  He's generous enough to let us use our framework as long as we don't ask him for help, and if we can keep the rest of our team up to speed -- which seems fair to us.

答:
Actually, those classes are still tightly coupled.  Except now they're tightly coupled in a such a way that the compiler can't tell you when things are broken!

If someone changes "BicycleMake" to "BicyclesMake" then no one is going to find out that things are broken until runtime.

Runtime errors are way more costly to fix than compile time errors - this is just all kinds of evil.


答:
Some hardware has the heap starting at high memory, growing down, while the stack starts at low memory growing up.

HP's PA-RISC hardware, among others, does this: http://www.embeddedrelated.com/usenet/embedded/show/68749-1.php

The venerable Multics Operating System ran on hardware that had (one of possibly many) stacks growing up: see http://www.acsac.org/2002/papers/classic-multics.pdf, end of section 2.3.2:

Third, stacks on the Multics processors grew in the positive
  direction, rather than the negative direction. This meant that if you
  actually accomplished a buffer overflow, you would be overwriting
  unused stack frames, rather than your own return pointer, making
  exploitation much more difficult.

That's a rather interesting statement. Did buffer overflows become such a huge problem only because of the "customary" procedure-call-stack-frame arrangement?  Also, how much of Multics' reputation as Totally Invulnerable was just a fluke of hardware design?

Title: Why does the stack grow downward?


答:
While it sounds like your team is indeed simply cowboy coding, there really should be nothing wrong with refactoring code OR databases.  It's not lost work--it's adapting to a newly learned reality.

I'd suggest what the team needs is a sandbox to try out changes, do some testing, bounce them off the users, and decide whether they make sense.  At that point, integrating the changes that make sense--with adequate regression testing--into your schema should be fine.


问:
Communications regarding maintainability of code
I'm in search of good language or metaphors to discuss the maintainability of code with non-technical folks (PMs, business sponsors &c).

In particular, I've recently created a few one-off, get-it-done-tonight, gets-the-job-done pieces of code. Everyone, including the internal sponsor, knew that we were saving a couple hours based on the premise that the code would be used once, for the immediate need, and not again.

Then the inevitable: "Hey, remember that thing we did? Let's do it again, but with these minor changes." Of course, the minor changes aren't so minor, all the more so because the code was written as a big ol' procedural nastiness hinging on assumptions about the environment. [Yes, yes, I know, avoid the problem in the first place. Don't write bad code. Write everything as if it will be maintained by someone else, or me years from now. That's a different question, though. This is after it's happened.]

So what are some good metaphors for the internal sponsor (non-technical) to quickly explain why the code isn't maintenance or minor-change friendly?  The walls on a movie set: There's no garage there, it's just a door. -or- The doors are welded shut on this car.

How do you describe this continuum?

I want to find some terms for our group that will help talk about how much effort goes in up front and how that will improve maintainability: illustrating the trade-offs in "Do you want this tonight or do you want it maintainable?"

(In writing this up, I realize this might be the same as defining 'maintainable' for non-technical stakeholders. Seems like explaining loose coupling to non-technical types may not be the best way out of this. If you've successfully done that, how?)

Edited for answer:
For now I will continue to use building construction metaphors. This will turn into the size and strength of the foundation: "Yes we can build that building on this, but we will need to rework the foundation to be larger and cover the right area."

答: I would talk in terms of "technical debt" for this, especially if talking to stakeholders like customers or managers that have an ear for concerns of finance.  Making bad decisions or generating sloppy work is like taking out loans that have interest rates.</p>


答:
I disagree with your statement that "Imperative language... that's the tough part".  That's the easy part, although it is considerably easier in some languages than others.  Figuring out what the users really want, and organizing all that information is the hard part.  The "Imperative language" part looks hard because that is when all the real work gets done.  That's when the detailed questions about requirements appear, and when all the answers have to be organized into an executable system definition.

There is no programming without programming.  Someone has to translate imprecise human wants into a precise specification of a computation.  That specification can be in assembly language, or Java, or LISP, some diagrammatic system, or a language yet to be invented.  But until computers are capable of deep communication with humans, someone is going to have to talk to the users and precisely define the system.


问:
Implementing RSA into an Android Messaging App
I am implementing RSA encryption on a Android App so that I can send SMS message securely, each phone will have its own public and private key generated by the App.

But am stuck deciding the best way to store the keys, my options are:

Create a keystore and hold the public and private key in the keystore.

Save the public and private key to separate files.

Use sharedpreferences to store keys.

I was also thinking of encrypting the private key with blowfish if just stored in a file.

Can anyone help explain to me which is the most secure option?

答:
So here's the thing, all of the three approaches you mentioned are inherently insecure for one main reason: If/when your app gets reverse-engineered, the private key will be compromised. This is the nature of storing keys/sensitive information in apps and there's nothing you can do about that. This of course also means that if you hash the private key to a file, well now that your app is compromised reverse-hashing it will be trivial.

Now that we got that out the way, here's what you can do (in the Android context). Store the private key in SharePreferences (private mode) and use it as needed. SharedPreferences in private mode sort of translates to a separate memory space where the data cannot be accessed by the user or other apps.

Again, I need to point out that this isn't a secure way of getting this done because devices could be rooted, app reverse engineered, etc. This scheme works when you have a way to recover from a breach.

For example, if each user of your app (somehow) had a separate private key, and you find out that user X's key was compromised, well it would be a simple matter of updating X's private key from the server and you're on your way.


问:
Is it bad practice for a decorator to break the decoration chain?
I'm currently using decorators to apply various modifications to a template prior to rendering it.

I'm unsure about my cache decorator, though, because it is currently able to break the chain of decorators and return a cached object as opposed to the original decorated object.

```<code>class Cache : Decorator
{
    public String Render()
    {
        if(templateCache.IsCached('some_template_identifier'))
        {
            return templateCache.Get('some_template_identifier');
        }
        String renderedTemplate = Template.Render();
        templateCache.Cache(renderedTemplate);
        return renderedTemplate;
    }
}
</code>```

Is this bad practice? Should I always be returning the original decorated object or is it ok to break the flow like this and return a different object?

答:
This doesn't seem to be breaking any chain to me.

The intent of the Decorator is that your calling code should be able to render your string just fine, if it's holding the Template object, or cached if it's holding the Cached object. It shouldn't know or care how many objects are wrapped around the basic object. The calling code should simply call Render and handle what it gets.

Breaking the chain would be if your Template's Render method had a different signature from the Cached Render method, so that the calling code needs to know which it has.

All this said, I also don't feel this is, by strict definition, a Decorator pattern.

Decorators tend to decorate whatever they're rendering, rather than change where it's getting that string from. So you might have had a QuotesWrapper and an LCaseWrapper so that if your Template returns Hello World!, you might wrap it in QuotesWrapper to get "Hello World!" or the LCaseWrapper to get hello world! or in both to get "hello world!". All the time, the calling code doesn't care.

What you're doing is similar but not the same. In no way are you decorating anything. If anything, it's more like a Proxy, at least in AOP terms.


答:
Construction metaphors are often helpful when explaining software concepts to non-technical folks.

You can say, for example, "This code was so jury-rigged, it was like using a 2x4 to prop open the garage door instead of installing a proper garage door opener."

Construction metaphors lend themselves nicely to a continuum of explanations.

Title: Communications regarding maintainability of code

Body:
I'm in search of good language or metaphors to discuss the maintainability of code with non-technical folks (PMs, business sponsors &c).

In particular, I've recently created a few one-off, get-it-done-tonight, gets-the-job-done pieces of code. Everyone, including the internal sponsor, knew that we were saving a couple hours based on the premise that the code would be used once, for the immediate need, and not again.

Then the inevitable: "Hey, remember that thing we did? Let's do it again, but with these minor changes." Of course, the minor changes aren't so minor, all the more so because the code was written as a big ol' procedural nastiness hinging on assumptions about the environment. [Yes, yes, I know, avoid the problem in the first place. Don't write bad code. Write everything as if it will be maintained by someone else, or me years from now. That's a different question, though. This is after it's happened.]

So what are some good metaphors for the internal sponsor (non-technical) to quickly explain why the code isn't maintenance or minor-change friendly?  The walls on a movie set: There's no garage there, it's just a door. -or- The doors are welded shut on this car.

How do you describe this continuum?

I want to find some terms for our group that will help talk about how much effort goes in up front and how that will improve maintainability: illustrating the trade-offs in "Do you want this tonight or do you want it maintainable?"

(In writing this up, I realize this might be the same as defining 'maintainable' for non-technical stakeholders. Seems like explaining loose coupling to non-technical types may not be the best way out of this. If you've successfully done that, how?)

Edited for answer:
For now I will continue to use building construction metaphors. This will turn into the size and strength of the foundation: "Yes we can build that building on this, but we will need to rework the foundation to be larger and cover the right area."


问:
Greenspun's Tenth Rule, does every large project include a Lisp interpreter?
Greenspun's tenth rule (actually the only rule) states that:

Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.

My memory is that there are some papers on the topic, perhaps for Borland's Quattro (spreadsheet) project and possibly others.  Google is unhelpful, maybe the right search terms are not coming to mind.  I am looking for papers or articles supporting this claim, if any.

答:
Curiously, one answer to this question is already in Programmers SE.

To quote the relevant part:

Greenspun's point was (in part) that many complex programs have built-in interpreters. Rather than building an interpreter into a language he suggested it might make more sense to use a language like Lisp that already has an interpreter (or compiler) built-in.

At the time I had been working on a rather big app that performed user-defined calculations using a custom interpreter for a custom language. I decided to try re-writing its core in Lisp as a large-scale experiment.

It took roughly six weeks. The original code was ~100,000 lines of Delphi (a Pascal variant). In Lisp that was reduced to ~10,000 lines. Even more surprising, though, was the fact that the Lisp engine was 3-6 times faster. And keep in mind that this was the work of a Lisp neophyte! That whole experience was quite an eye-opener for me; for the first time I saw the possibility of combining performance and expressiveness in a single language.

  -- Michael Lenaghan

To further clarify that part, Michael responded to a comment with:

Wow, that must have been some really horrible Delphi code if it somehow managed to perform 3-6x slower than a Lisp implementation!" Right, I'll count that as my fail for not explaining it better. The Lisp implementation was able to transform user expressions into Lisp expressions--a trivially easy process--and then compile the Lisp expressions to native code (with full optimization). That's the meaning of Greenspun's Tenth Rule.

  -– Michael Lenaghan

Given this answer is composed of someone else's answer elsewhere, it is community wiki.


问:
Servicing background tasks on a large site
We're dealing with an interesting problem on StackOverflow.

We've got a whole bunch of little "needs to be done soon-ish" tasks.  An example is updating "Related Questions" lists.  What we've done in the past is to piggy-back those tasks onto some users' page loads.

This was never ideal, but it wasn't really noticeable.  Now that SO has passed the 1,000,000 question mark, those unlucky users are starting to feel it.

The natural solution is to actually push these tasks into the background.  There are two broad ways of doing this I'm considering.

1. In IIS as a custom Thread-Pool/Work-Queue

Basically, we spin up a few (non-ThreadPool, so as to not interfere with IIS) threads and have them services some collections we're shoving Funcs into.

The big pro here is simplicity.  We don't have to worry about marshaling anything, nor do we have to make sure some external service is up and responding.

We also get access to all of our common code.

The con is, well, that we shouldn't use background threads.  The objections I know of are all centered around starving IIS (if you use ThreadPool) and the threads dieing randomly (due to AppPool recycling).

We've got existing infrastructure to make the random thread death a non-issue (its possible to detect a task has been abandoned, basically), and limiting the number of threads (and using non-ThreadPool threads) isn't difficult either.

Am I missing any other objections to in IIS process thread-pooling/work-queues?

Moved to StackOverflow, as it wasn't really addressed here.

2. As a Service

Either some third-party solution, or a custom one.

Basically, we'd marshal a task across the process boundary to some service and just forget about it.  Presumably we're linking some code in, or restricted to raw SQL + a connection string.

The pro is that its the "right way" to do this.

The cons are that we're either very restricted in what we can do, or we're going to have to work out some system for keeping this service in sync with our code base.  We'll also need to hook all of our monitoring and error logging up somehow, which we get for free with the "In IIS" option.

Are there any other benefits or problems with the service approach?

In a nutshell, are there unforseen and insurmountable problems that make approach #1 unworkable and if so are there any good third-party services we should look into for approach #2?

答:
A few weeks back I asked a similar question on SO. In a nut shell, my approach for some time now has been to develop a Windows Service. I would use NServiceBus (essentially MSMQ under the covers) to marshal requests from my web app to my service. I used to use WCF but getting a distributed transaction to work correctly over WCF always seemed like a pain in the ass. NServiceBus did the trick, I could commit data and create tasks in a transaction and not worry whether my service was up and running at the time. As a simple example, if ever I needed to send an email (for example a registration email) I would create the user account and fire off a signal to my Windows Service (to send the email) in a transaction. The message handler on the service side would pick up the message and process accordingly.

Since ASP .NET 4.0 and AppFabric have been released, there are a number of viable alternatives to the mechanism above. Referring back to the question I mentioned above, we now have AppFabric's AppInitialize(via net.pipe) as well as ASP .NET 4.0's Auto-Start feature which make developing Windows Services as web apps a viable alternative. I have started doing this now for a number of reasons (biggest one being deployment is no longer a pain in the ass):

You can develop a web UI over your service (since it's running as a web app). This is extremely useful to see what is happening at runtime.

Your deployment model for your web apps will work for your service application.

IIS provides a few neat features for handling application failures (similar in some respects to a Windows Service).

Web developers are very familiar with developing web apps (naturally), most don't know much about best practice when developing a Windows Service.

It provides a number of alternatives to exposing an API for other apps to consume.

If you go this route (forgive me for copying and pasting from my original post) I would definitely consider running the background logic in a separate web application. There are number of reasons for this:

Security. There may be a different security model for the UI displaying information about the running background processes. I would not want to expose this UI to anyone else but the ops team. Also, the web application may run as a different user which has an elevated set of permissions.

Maintenance. It would be great to be able to deploy changes to the application hosting the background processes without impacting on user's using the front end website.

Performance. Having the application separated from the main site processing user requests means that background threads will not diminish IIS's capability to handle the incoming request queue. Furthermore, the application processing the background tasks could be deployed to a separate server if required.

Doing this gets back to the marshaling aspect. WCF, NServiceBus/RabbitMQ/ActiveMQ etc., vanilla MSMQ, RESTful API (think MVC) are all options. If you are using Windows Workflow 4.0 you could expose a host endpoint which your web app could consume.

The web hosting approach for services is still fairly new to me, only time will tell if it was the correct choice. So far so good though. By the way, if you don't want to use AppFabric (I couldn't because for some bizarre reason, Windows Server Web Edition ain't supported), the Auto-Start capability mentioned in the Gu's post works nicely. Stay away from the applicationhost.config file though, everything in that post is possible to setup through the IIS console (Configuration Editor on the main server level).

Note: I had originally posted a few more links in this message but alas, this is my first post to this exchange and only one link is supported! There was basically two others, to get them Google "Death to Windows Services...Long Live AppFabric!" and "auto-start-asp-net-applications". Sorry about that.


答:
Greenspun's "tenth rule" was an off-the-cuff bit of snark.  When stretched far enough, if you make it cover "any scripting or configuration system," then obviously the answer to this question will have to be "yes," since configuration is something that any non-trivial program requires in some degree, and scripting is only slightly less common as you move up the complexity scale.

On the other hand, have a look at GOAL, a Lisp variant invented by Naughty Dog for game programming.  It doesn't look much like "classic" Lisp at all.  It's a highly imperative-style system, with object-oriented functionality, no interpreter, minimal support for garbage collection (relying on runtime-level cleanup facilities instead), and extensive support for inline assembly.

In other words, when they tried to use Lisp for a sufficiently complex project, they found that to do anything useful they had to turn the language into an ad-hoc, informally specified implementation of half of C++! ;)  (And they eventually had to stop using it after the guy who designed GOAL left, because no one could understand his code.)

Title: Greenspun's Tenth Rule, does every large project include a Lisp interpreter?

Body:
Greenspun's tenth rule (actually the only rule) states that:

Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.

My memory is that there are some papers on the topic, perhaps for Borland's Quattro (spreadsheet) project and possibly others.  Google is unhelpful, maybe the right search terms are not coming to mind.  I am looking for papers or articles supporting this claim, if any.


答:
Here try this, works for my students all the time :)

Take a pack of spaghetti to the meeting (uncooked) and ask them to remove a single noodle or multiple ones. It's easy.

Now take a cooked one or just 'dump the uncooked ones' on the table and ask them to pick something without disturbing the surroundings (or in case of the cooked one, trace it's start/end).

This usually hits the point home: The uncooked spaghetti is well architected, separation of concerns, clean and takes effort discipline to make it (think of the manufacturing process).

The latter, just dump in a pan to cook or on the table, quick to do but a nightmare to sift through later.

Hence the term 'spaghetti code' :)


问:
How useful is a project log or diary?
I want to know how difficult/useful it is to keep a project log or diary. I'm worried that keeping track of what I did will eat up too much time...</p>

答:
It's time well spent.  I maintain all of my notes in a program called Connected Text.  I refer back to problems, meetings, CYA items, programming notes, language notes, API snippets, etc.  I also use Evernote to clip things from the web and then turn them into notes.  A lot of what you will do in your career will come up again, so keeping notes on how you solved those problems is a good idea.  I look at this like off loading the minutiae to keep the important things on my mind, knowing that I can refer back to my notes.  Afterall, it's why you takes notes to begin with.

It is not a waste of time.

Title: How useful is a project log or diary?