答:
```<code>X x;
try
{
     x = exampleObject.DoSomething ();
}
catch (ThisCanGoWrongException ex)
</code>```

If doSomething returns something, it can't meanwhile return an error, except there is enough room in the result Space. A well known instance of this phenomenon is a C-library, which reads a byte and returns an int. While bytes are considered unsigned, the error-case is/was a -1.

But now you have to do an ugly cast to do.

What do you do, if the result space does not give you room for results, meaning "invalid"? Well, you can use a Wrapper, which returns, instead of an T an Either[Error, T]. The right result usually means an result which is alright, and left is left to mean a kind of error.

Instead of the Error as special kind of value, the user of your library is - in statically typed languages - informed beforehand, that there is something which might go wrong.

In contrast, for

```<code>  String ips = getIP ("programmers.se.com");
  // returns "err.or.in.DNS" in errorcase - but programmer
  // forgot to check
  for (String b : ips.split (".")) {
       Integer.parseInt (b); // crash here
</code>```

Sometimes, methods get called for their side effect, and the return value isn't inspected at all. Then an error can slip through undetected.

```<code>  user.setAge (-42);
</code>```

Maybe the class returns a "false" or a message "Invalid age, must be >= 0". But many languages allow to ignore the returned result. An exception would be preferred here.

A problem with exceptions and wrapped result is, that they sometimes clutter the code, and make it harder to follow the healthy case. Maybe we will see improvements there in the future - Java is for example trying to simplify the handling of exceptions recently. IDEs could probably hide or fold exception code on demand.

In some cases, it might be reasonable to return a special Null object. Think about searching a special User in the Database. If something goes wrong, you could return null.

```<code>    println (null.getName ()); // crash: NPE
</code>```

An often seen solution is, to return a List with one Element in the normal case, and zero values in the defect case.

```<code>    users = db.get ("Zappa");
    for (User u : users) {
         u.doSomething ();
</code>```

This will work with one or none Element, and Languages like Haskell or Scala have a special purpose class for this, a Maybe or an Option.

Option is a parametrized class. An Option[T] is either a Some (T) or a None. The user still has to check the result, but can't forget it that easily.

This is similar to the result of an empty List, and might not be appropriate everywhere, but often it is.

Title: if/else statements or exceptions

Body:
X x;
try
{
     x = exampleObject.DoSomething ();
}
catch (ThisCanGoWrongException ex)

If doSomething returns something, it can't meanwhile return an error, except there is enough room in the result Space. A well known instance of this phenomenon is a C-library, which reads a byte and returns an int. While bytes are considered unsigned, the error-case is/was a -1.

But now you have to do an ugly cast to do.

What do you do, if the result space does not give you room for results, meaning "invalid"? Well, you can use a Wrapper, which returns, instead of an T an Either[Error, T]. The right result usually means an result which is alright, and left is left to mean a kind of error.

Instead of the Error as special kind of value, the user of your library is - in statically typed languages - informed beforehand, that there is something which might go wrong.

In contrast, for

  String ips = getIP ("programmers.se.com");
  // returns "err.or.in.DNS" in errorcase - but programmer
  // forgot to check
  for (String b : ips.split (".")) {
       Integer.parseInt (b); // crash here

Sometimes, methods get called for their side effect, and the return value isn't inspected at all. Then an error can slip through undetected.

  user.setAge (-42);

Maybe the class returns a "false" or a message "Invalid age, must be >= 0". But many languages allow to ignore the returned result. An exception would be preferred here.

A problem with exceptions and wrapped result is, that they sometimes clutter the code, and make it harder to follow the healthy case. Maybe we will see improvements there in the future - Java is for example trying to simplify the handling of exceptions recently. IDEs could probably hide or fold exception code on demand.

In some cases, it might be reasonable to return a special Null object. Think about searching a special User in the Database. If something goes wrong, you could return null.

    println (null.getName ()); // crash: NPE

An often seen solution is, to return a List with one Element in the normal case, and zero values in the defect case.

    users = db.get ("Zappa");
    for (User u : users) {
         u.doSomething ();

This will work with one or none Element, and Languages like Haskell or Scala have a special purpose class for this, a Maybe or an Option.

Option is a parametrized class. An Option[T] is either a Some (T) or a None. The user still has to check the result, but can't forget it that easily.

This is similar to the result of an empty List, and might not be appropriate everywhere, but often it is.


问:
Non-Profit Technology for Non-Profits?
I've been looking around for a way to give back to the community, but I haven't found my right fit yet, so an idea came to mind: A non-profit technology "company" that targets non-profits.

Do these exist? I've been doing some google searches and can only find software that is targeted for non-profits that is created by for-profit companies or that charges what I believe to be an outrages amount, conferences directed towards non-profits and technology they may use -- or articles complaining about the digital divide and how non-profits view technology as key but dont have the funds or the knowledge to employ it.

Pseudo "Business Model"

An open source 501(3)(c) organization that targets directly targets non-profits to fill the "digital divide." Most services would be free and consulting fees would be charged for customization. Donations would be accepted and government grants would be sought after. This would enable non-profits to keep pace with the for-profits in the technology sector, but at little to no cost. Perhaps the first "industry" to be targeted would be those that fill key social needs like unemployment, or food banks.

答:
There are hordes of already thriving nonprofit technology nonprofits.

Just to get you started:

Nonprofit Technology Network

Social Coding 4 Good

NPower

Technology Service Corps

Idealware

TechSoup

Aspiration

Nonprofit Open Source Initiative

CiviCRM

ContentLicense: CC BY-SA 3.0

Title: Non-Profit Technology for Non-Profits?


问:
What is an effective way to organize tasks for a new project?
Is there a practical solution to organizing the initial tasks for a new project?

To elaborate, imagine the features/stories/goals are laid out for a project. How might one go about organizing those into sane tasks for the first few versions?

The scenario I typically have in mind has the features listed as a high-level reference for what the end user-experience should involve. The tasks for constructing such features are then broken down into chunks (such as "create interface for X component"). Such a task is not necessarily "tied" to only that feature and may be useful when building subsequent features. Is breaking features down into small, code-able solutions valid? Or should they be slightly removed from any specific implementation?

I do not expect that there is one "right" answer to this question, but I am looking for a fairly pragmatic and unobtrusive approach.

As a note, I'm looking for solutions that are independent of any tools or "systems" used for managing the tasks themselves.

答:
There definitely isn't a "one size fits all" solution to this.

For most of my projects however, I usually start out brainstorming in TextEdit what I want my program to do. By writing it out, I can easily self-reflect, and decide what to scrap or what to improve. Drawing a possible GUI out on paper can help to, depending on the nature of the project.

After a semi-definite plan is made, I'll usually make a few test modules to see if what I want is practical (or possible).

Last, I basically piece together the test programs I made into one application, and repeat the process indefinitely.


问:
Optimal Database design regarding functionality of letting user share posts by other users
I want to implement functionality which let user share posts by other users similar to what Facebook and Google+ share button and twitter retweet.

There are 2 choices:

1) I create duplicate copy of the post and have a column which keeps track of the original post id and makes clear this is a shared post.

2) I have a separate table shared post where I save the post id which is a foreign key to post id in post table.

Talking in terms of programming basically I keep pointer to the original post in a separate table and when need to get post posted by user and also shared ones I do a left join on post and shared post table

```<code>    Post(post_id(PK), post_content, posted_by)

    SharedPost(post_id(FK to Post.post_id), sharing_user, sharedfrom(in case someone shares from non owners profile))
</code>```

I am in favour of second choice but wanted to know the advice of experts out there?

One thing more posts on my webapp will be more on the lines of facebook size not tweet size.

答:
I would just duplicate the original posting. This will simplify your domain layer when dealing with deletions, duplications (from another duplication) and etc.

If you duplicate the posting, marking it as a duped one (simple flag), you gain the delete, share, etc, for free, instead of creating complicated logic behind duplications.


问:
if/else statements or exceptions
I don't know whether this question fits better on this site or on Stack Overflow, but because my question is connected rather to practices, that some specified problem.

So, consider an object that does something. And this something can (but should not!) can go wrong. So, this situation can be resolved in two ways:

first, with exceptions:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
try
{
     exampleObject.DoSomething();
}
catch (ThisCanGoWrongException ex)
{
     [...]
}
</code>```

And second, with if statement:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
if(!exampleObject.DoSomething())
{
     [...]
}
</code>```

Second case in more sophisticated way:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
ErrorHandler error = exampleObject.DoSomething();
if (error.HasError)
{
     if(error.ErrorType == ErrorType.DivideByPotato)
     {
         [...]
     }
}
</code>```

Which way is better? On one hand, I heard that exceptions should be used only for real unexpected situations, and if the programmer knows that something may happen, they should use if/else. On the other hand, Robert C. Martin in his book Clean Code wrote: "exceptions are far more object oriented, and more simple to keep clean."

答:
Another thing to consider is that when exceptions occur there is a performance penalty or a cost associated with that exception.

For example, run X/Y in a loop.

One way is to use an if statement.  Example:

```<code>if (Y != 0)
{
   result = X/Y;
}
</code>```

Another way is to use a try/catch.

```<code>try
{
  result = X/Y;
}
catch (DevideByZeroException zeroEx)
{
  //Log Error
}
</code>```

If you run this in a loop (million times) you will find the if statement runs a lot faster over the try catch when Y = 0.

So, when coding ask yourself, will I hit this condition alot.  In this example, how often will Y be zero?  1% or 50% of the time?  If 50% then use an if.    If just occasionally use a try. If there are 500,000 excpetions occurring, then that is not really an exception to the rule, it is the rule.  You want to avoid that.

That's why I tend to think exceptions are for cases that don't happen that frequently.  If you have popular use cases that are handled via exception logic, then they should probably be converted to use logic statements (ifs) versus exceptions.  And as a bonus your code will speed up as well.

ContentLicense: CC BY-SA 4.0

Title: if/else statements or exceptions

Body:
Another thing to consider is that when exceptions occur there is a performance penalty or a cost associated with that exception.

For example, run X/Y in a loop.

One way is to use an if statement.  Example:

if (Y != 0)
{
   result = X/Y;
}

Another way is to use a try/catch.

try
{
  result = X/Y;
}
catch (DevideByZeroException zeroEx)
{
  //Log Error
}

If you run this in a loop (million times) you will find the if statement runs a lot faster over the try catch when Y = 0.

So, when coding ask yourself, will I hit this condition alot.  In this example, how often will Y be zero?  1% or 50% of the time?  If 50% then use an if.    If just occasionally use a try. If there are 500,000 excpetions occurring, then that is not really an exception to the rule, it is the rule.  You want to avoid that.

That's why I tend to think exceptions are for cases that don't happen that frequently.  If you have popular use cases that are handled via exception logic, then they should probably be converted to use logic statements (ifs) versus exceptions.  And as a bonus your code will speed up as well.


问:
Using "prevent execution of method" flags
First of all I want to point out my concern with some pseudocode (I think you'll understand better)

Assume you have a global debug flag, or class variable named "debug",

```<code>class a :
   var debug = FALSE
</code>```

and you use it to enable debug methods. There are two types of usage it as I know:

first in a method :

```<code> method a :
      if debug then call method b;

 method b :
</code>```

second in the method itself:

```<code> method a :
       call method b;

 method b :
      if not debug exit
</code>```

And I want to know, is there any File IO or stack pointer wise difference between these two approaches. Which usage is better, safer and why?

答:
First, I don't think you should be concerned about speed here. My primary concern would be designing a proper API, otherwise speed wont be an issue because nobody would actually use it. Even if this is just for an internal application, I personally like to design things with the intent that someday they can be factored out into their own library.

So what are the API trade-offs? If you should be able to call method b with out having it check the state of the debug variable, then the second example is not an option. You may also be concerned with whether or not the debug variable is part of the public API. If it is, then exposing an isDebug method and allowing the users to decide when method b should be called might make sense. However, if method b has no other reason to exist other than to be called when debugging is on, then it does makes sense to encapsulate the conditional inside the method.


答:
It's the classic "link vs copy".

I reccomend making a duplicate copy. Although "duplicate" may not be the correct term since you are sharing a snap shot of time. It's "unique" with regard to that context.

For example if you have a history table you want to store copies of the data, not foriegn keys. With a history you are not interested in the latest values. You want the values from that moment in time. It would be incorrect to use a FK.

If a poster deletes their post, then your shared link is broken. Minus 1 to links.

What if the poster edits their post to something offensive after you share it? That would make the sharing user look bad. Minus 1 to links.

Performance. The copy is wasteful on disk space. However it does get rid of the need to maintain an index on a foreign key. It may not sound like much, but on an extremely large database that is a huge deal. With any face book caliber dataset you are going to have to break with tradition a bit to make things fast. Minus 1 to links.

What does this mean for your post sharing? It depends on what you want. Are you by design sharing a "link" or a "copy"? There are advantages and drawbacks to both designs. I'll let others talk about the pros of links.

EDIT: Please don't let my post shy you away from links. For the goals of your application, they may be what you need. The web has gotten by with links pretty well so far.

Title: Optimal Database design regarding functionality of letting user share posts by other users

Body:
I want to implement functionality which let user share posts by other users similar to what Facebook and Google+ share button and twitter retweet.

There are 2 choices:

1) I create duplicate copy of the post and have a column which keeps track of the original post id and makes clear this is a shared post.

2) I have a separate table shared post where I save the post id which is a foreign key to post id in post table.

Talking in terms of programming basically I keep pointer to the original post in a separate table and when need to get post posted by user and also shared ones I do a left join on post and shared post table

```<code>    Post(post_id(PK), post_content, posted_by)

    SharedPost(post_id(FK to Post.post_id), sharing_user, sharedfrom(in case someone shares from non owners profile))
</code>```

I am in favour of second choice but wanted to know the advice of experts out there?

One thing more posts on my webapp will be more on the lines of facebook size not tweet size.


答: Ignoring compiler optimizations, of course testing to avoid a function call (your first solution) can avoid whatever overhead is associated with the function call.  This is not specific to global debug flags though, and is certainly small stuff in the bigger picture.  If you have any reason at all to prefer the second solution, that's fine.  Worry about other stuff.</p>

Title: Using "prevent execution of method" flags

Body:
First of all I want to point out my concern with some pseudocode (I think you'll understand better)

Assume you have a global debug flag, or class variable named "debug",

```<code>class a :
   var debug = FALSE
</code>```

and you use it to enable debug methods. There are two types of usage it as I know:

first in a method :

```<code> method a :
      if debug then call method b;

 method b :
</code>```

second in the method itself:

```<code> method a :
       call method b;

 method b :
      if not debug exit
</code>```

And I want to know, is there any File IO or stack pointer wise difference between these two approaches. Which usage is better, safer and why?


问:
Long term plan of attack to learn math?
I am a web-developer with a desire to expand my skill-set to mathematics relevant to programming.

As 2nd career, I am stuck in college doing some of the requirements while working.

I was hoping the my education will teach me the needed skills to apply math, however I am quickly finding it to be too much easily-testable breadth-based approach very inefficient for the time invested.

For example in my calculus 2 class, the only remotely useful mind expanding experience I had was volumes and areas under the curve.  The rest was just monotonous glorified algebra, which while comes easy to me, could be done by software like wolfram alpha within seconds.  This is not my idea of learning math.

So here I am a frustrated student looking for a way to improve my understanding of math in a way that focuses on application, understanding and maximally removed needless tedium.

However I cannot find a good long term study strategy with this approach in mind.

So for those of like mind, how would you go about learning the necessary math without worrying too much about stuff a computer can do much better?

答:
If you want to do algorithms in general, finite math and abstract algebra courses should help out (or, you could just take an algorithms course...).  Finite math will also help with encoding, encryption, and a variety of other computational algorithm domains.  You should try taking a look at Knuth's The Art of Computer Programming, if only as a pointer to the kind of math you might find useful.

If you want to do number crunching (the kind of thing that will use your calculus and linear algebra), look through the latest edition of Numerical Recipes.  I also recommend Golub & van Loan's Matrix Computations as a more mathematically correct text on computational linear algebra.

In general, if there is an application domain you are interested in, you should visit the library and look through some books on the subject, to find the kind of math they require.  There may not be a specific course on the subject available, but you should not let that stop you.  The ability to track down and learn a body of knowledge on your own initiative is one of the most valuable skills you can acquire: if that were the only thing you learned in school, your time and money would still be well-spent.

Title: Long term plan of attack to learn math?


问:
functional requirements - use wording based on verbs?

Question

Should the functional requirements in a requirements doc use wording based on verbs?

Context

School assignment, working in a team, working through the SDLC. The requirements doc has been done and we are now into design.

Problem

The requirements doc has an enumerated list of what I'd call features of the app - the
 functional requirements. In that list are things that I'd think of as "how's" rather
 than "what's" and now, trying to work on design, I feel like a part of design has been
 prematurely dictated.

I've not done this before! To me, I should be dealing strictly with things that
 describe "what."

Example of current

Pretend that the job is to make an omelet. Listing: crack the egg, break into bowl, scramble, etc.; crosses over the line into the territory of how. Along that track, so does wording like: create, generate, list, calculate, determine, validate, etc. - verbs, basically. Right now, I have a list of requirements that are partially rooted in verbs.

My idea of a requirements doc for an omelet would be more like: has two eggs, x ounces of ham, x ounces of bacon, x ounces of montery-jack cheese, x ounces of cilantro, etc.—nothing but what (nouns).

I might have, and could have, spoken up before finalizing the requirements doc if I'd had any experience.

答:
A functional program is composed of functions.  What are functions?  They are methods that perform actions.  What are action words?  Verbs.

If you were doing object oriented programming, then you would be working with nouns.  Actually, you would be working with both nouns and verbs.

Functional style:

```<code>crack(egg)
</code>```

Object-oriented style:

```<code>egg.Crack();
</code>```

At the requirements level, I'm not sure that any of this matters, although it would certainly be helpful if the requirements were stated in the form of actions, since functions are what you will be writing.

Body:
A functional program is composed of functions.  What are functions?  They are methods that perform actions.  What are action words?  Verbs.

If you were doing object oriented programming, then you would be working with nouns.  Actually, you would be working with both nouns and verbs.

Functional style:

crack(egg)

Object-oriented style:

egg.Crack();

At the requirements level, I'm not sure that any of this matters, although it would certainly be helpful if the requirements were stated in the form of actions, since functions are what you will be writing.


答:
You can and should use verbs in your requirements.  The important thing is to make sure each requirement is:

Unambiguous - each requirement can only mean one thing and can only be interpreted one way.

Atomic - each requirement cannot be broken down into multiple requirements.

Testable - each requirement can be shown to have been met or not met via some form of testing.

You'd be surprised how good your requirements turn out by just following these three guidelines at all costs.

Also, be sure to write a rationale for each requirement.  This is very important and useful down the road when someone wonders why a particular requirement was created.

And yes, you are correct, the requirements should describe WHAT the software will do, not HOW it will do it.

Title: functional requirements - use wording based on verbs?

Body:
Question

Should the functional requirements in a requirements doc use wording based on verbs?

Context

School assignment, working in a team, working through the SDLC. The requirements doc has been done and we are now into design.

Problem

The requirements doc has an enumerated list of what I'd call features of the app - the
 functional requirements. In that list are things that I'd think of as "how's" rather
 than "what's" and now, trying to work on design, I feel like a part of design has been
 prematurely dictated.

I've not done this before! To me, I should be dealing strictly with things that
 describe "what."

Example of current

Pretend that the job is to make an omelet. Listing: crack the egg, break into bowl, scramble, etc.; crosses over the line into the territory of how. Along that track, so does wording like: create, generate, list, calculate, determine, validate, etc. - verbs, basically. Right now, I have a list of requirements that are partially rooted in verbs.

My idea of a requirements doc for an omelet would be more like: has two eggs, x ounces of ham, x ounces of bacon, x ounces of montery-jack cheese, x ounces of cilantro, etc.—nothing but what (nouns).

I might have, and could have, spoken up before finalizing the requirements doc if I'd had any experience.


问:
Does knowing Latin or other logical languages contribute to being a better programmer?
I'm currently studying Latin at school, and what I've learned is that it's a very logical language. I feel this has contributed to my programming ability, as it makes it my code easier to understand.

Is there any relation between knowledge of a very logical language such as Latin and the comprehension of code?

答:
I have learnt Latin for five years and I do not think it is more logical
than other natural languages. But this may help you to learn programming
because some programming languages (which I do not want to mention here
to avoid any kind of language war) are also somewhat illogical in their
design, syntax and semantics.

Seriously, I do not think learning Latin has helped me to be a better programmer.
Also, many teachers of Latin like to repeat that Latin is a particularly
logical language (it was said to me as well), but I think this is only
commonplace.


问:
Working for free?
I came across this article Work for Free that got me thinking.

The goal of every employer is to gain
  more value from workers than the firm
  pays out in wages; otherwise, there is
  no growth, no advance, and no
  advantage for the employer.
  Conversely, the goal of every employee
  should be to contribute more to the
  firm than he or she receives in wages,
  and thereby provide a solid rationale
  for receiving raises and advancement
  in the firm.

I don't need to tell you that the
  refusenik didn't last long in this
  job.

In contrast, here is a story from last
  week. My phone rang. It was the
  employment division of a major
  university. The man on the phone was
  inquiring about the performance of a
  person who did some site work on
  Mises.org last year. I was able to
  tell him about a remarkable young man
  who swung into action during a crisis,
  and how he worked three 19-hour days,
  three days in a row, how he learned
  new software with diligence, how he
  kept his cool, how he navigated his
  way with grace and expertise amidst
  some 80 different third-party plug-ins
  and databases, how he saw his way
  around the inevitable problems, how he
  assumed responsibility for the
  results, and much more.

What I didn't tell the interviewer was
  that this person did all this without
  asking for any payment. Did that fact
  influence my report on his
  performance? I'm not entirely sure,
  but the interviewer probably sensed in
  my voice my sense of awe toward what
  this person had done for the Mises
  Institute. The interviewer told me
  that he had written down 15 different
  questions to ask me but that I had
  answered them all already in the
  course of my monologue, and that he
  was thrilled to hear all these
  specifics.

The person was offered the job. He had
  done a very wise thing; he had earned
  a devotee for life.

The harder the economic times, the
  more employers need to know what they
  are getting when they hire someone.
  The job applications pour in by the
  buckets, all padded with degrees and
  made to look as impressive as
  possible. It's all just paper. What
  matters today is what a person can do
  for a firm. The resume becomes pro
  forma but not decisive under these
  conditions. But for a former boss or
  manager to rave about you to a
  potential employer? That's worth
  everything.

What do you think? Has anyone here worked for free? If so, has it benefited you in any way? Why should(nt) you work for free (presuming you have the money from other means to keep you going)? Can you share your experience?

Me, I am taking a year out of college and haven't gotten a degree yet so that's probably why most of my job applications are getting ignored. So im thinking about working for free for the experience?

答:
I used to be a fresh graduate, with no real job experience and who only thought he knows something. In my country many graduates are in this position. Fortunately for me, programming is one of, if not the only one industry, where unemployment is no threat. Unless you’re over 40, that is.

A lot of my friends are working for nothing or next-to-nothing, only to have anything to show off in their resumes. They are not programmers though. But I've also been there. And IMHO that is okay only if it’s compulsory traineeship, that you have to do to finish your degree. Or I would accept being paid less to be able to learn some new technology, since in starting months I wouldn't be much help. But there needs to be a boundary. One needs to support himself.

I agree with lot of points here. Working for free is like a slap in a face. And usually, if someone gets something for free, doesn't appreciate that. But there are situations, where you can be so desperate that you will agree to anything just to get a job.

ContentLicense: CC BY-SA 2.5

Title: Working for free?


答:
Exceptions handle exceptional cases; that is, cases that do not fall into the "happy path" of normal program execution. Given this very important caveat, it is generally acceptable, and in fact, expected, to use try/catch in cases where (a) something can fail, and (b) you know what to do when it does.

The primary situation in which you would not use try-catch is when knowing the success or failure of a method is at least as important as the actual result of the operation. An example is string parsing: many times, it's at least as useful to know if a string consists of a number or not, rather than what the number actually is. Thus .NET provides "TryParse" flavors of the Parse functions built into the primitive types. They allow you to structure your code with a simple decision at the beginning of an if/else fork, that then determines entry into one or the other code blocks.

For instance, say DoSomething()'s success determines whether to print "Yes" or "No" to the console. Both are "normal" things for the program to do. You could write it like this:

```<code>try
{
   DoSomething();
   Console.WriteLine("Yes");
}
catch(Exception)
{
   Console.WriteLine("No");
}
</code>```

... but there are a couple of problems: first, from a design standpoint, it's not obvious without comments that DoSomething() is a decision being made. Second, DoSomething() may not be the only thing in the try block that could throw an exception. Let's say another developer added some additional code that they need to run when DoSomething succeeds:

```<code>try
{
   DoSomething();
   Console.WriteLine("Yes");
   DoSomethingElse();
}
catch(Exception)
{
   Console.WriteLine("No");
}
</code>```

Now, you have a scenario in which DoSomethingElse() could fail after DoSomething() succeeded, and the result to the end-user from one input would be very confusing:

```<code>Yes
No
</code>```

Instead, consider this:

```<code>if(TryDoSomething()) //a "non-throwing" variant that returns success or failure
{
   Console.WriteLine("Yes");
   DoSomethingElse();
}
else
{
   Console.WriteLine("No");
}
</code>```

The concept that DoSomething is the criteria of a decision between two "normal" execution paths is much clearer in the above code. And, your desired logic flow is enforced no matter what; If DoSomething() succeeds, the user will never see "No" displayed on screen no matter what DoSomethingElse() does.

In most other cases, try-catch is preferred, for one or more of the following reasons:

try-catch allows you to use the return value of a method for what it was conceptually designed to do; return the result of the operation, instead of a status code indicating whether a valid result is contained in an output or reference parameter that is the REAL product of the method.

try-catch allows for more object-oriented error-handling, as was mentioned, by avoiding the use of "magic numbers"; you don't have to know that return code -2 of this method is an error that an argument was null, you just catch an ArgumentNullException. And, you can catch that same ArgumentNullException thrown from any method that cares whether one of its passed parameters was null, instead of having to know that this method would return -2 and another method returns -3 in the same situation.

By that token, try-catch helps to standardize the expected behavior in a particularly exceptional case: If you pass a null parameter to a method that requires that parameter to not be null, you will get an ArgumentNullException, and it is usually bad practice to throw any other exception or to assume some base case that equates null with a discrete value.

try-catch isn't limited to calling methods; you can "try" a possible division-by-zero operation inline in your code and catch the exception thrown by the runtime should it occur.

try-catch isn't limited to one method at a time; you can, with minimal additional code, handle exceptions from a series of several methods, and abort processing, without having to examine the most recent return code of each method you call.

Title: if/else statements or exceptions

Body:
I don't know whether this question fits better on this site or on Stack Overflow, but because my question is connected rather to practices, that some specified problem.

So, consider an object that does something. And this something can (but should not!) can go wrong. So, this situation can be resolved in two ways:

first, with exceptions:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
try
{
     exampleObject.DoSomething();
}
catch (ThisCanGoWrongException ex)
{
     [...]
}
</code>```

And second, with if statement:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
if(!exampleObject.DoSomething())
{
     [...]
}
</code>```

Second case in more sophisticated way:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
ErrorHandler error = exampleObject.DoSomething();
if (error.HasError)
{
     if(error.ErrorType == ErrorType.DivideByPotato)
     {
         [...]
     }
}
</code>```

Which way is better? On one hand, I heard that exceptions should be used only for real unexpected situations, and if the programmer knows that something may happen, they should use if/else. On the other hand, Robert C. Martin in his book Clean Code wrote: "exceptions are far more object oriented, and more simple to keep clean."

Body:
Exceptions handle exceptional cases; that is, cases that do not fall into the "happy path" of normal program execution. Given this very important caveat, it is generally acceptable, and in fact, expected, to use try/catch in cases where (a) something can fail, and (b) you know what to do when it does.

The primary situation in which you would not use try-catch is when knowing the success or failure of a method is at least as important as the actual result of the operation. An example is string parsing: many times, it's at least as useful to know if a string consists of a number or not, rather than what the number actually is. Thus .NET provides "TryParse" flavors of the Parse functions built into the primitive types. They allow you to structure your code with a simple decision at the beginning of an if/else fork, that then determines entry into one or the other code blocks.

For instance, say DoSomething()'s success determines whether to print "Yes" or "No" to the console. Both are "normal" things for the program to do. You could write it like this:

try
{
   DoSomething();
   Console.WriteLine("Yes");
}
catch(Exception)
{
   Console.WriteLine("No");
}

... but there are a couple of problems: first, from a design standpoint, it's not obvious without comments that DoSomething() is a decision being made. Second, DoSomething() may not be the only thing in the try block that could throw an exception. Let's say another developer added some additional code that they need to run when DoSomething succeeds:

try
{
   DoSomething();
   Console.WriteLine("Yes");
   DoSomethingElse();
}
catch(Exception)
{
   Console.WriteLine("No");
}

Now, you have a scenario in which DoSomethingElse() could fail after DoSomething() succeeded, and the result to the end-user from one input would be very confusing:

Yes
No

Instead, consider this:

if(TryDoSomething()) //a "non-throwing" variant that returns success or failure
{
   Console.WriteLine("Yes");
   DoSomethingElse();
}
else
{
   Console.WriteLine("No");
}

The concept that DoSomething is the criteria of a decision between two "normal" execution paths is much clearer in the above code. And, your desired logic flow is enforced no matter what; If DoSomething() succeeds, the user will never see "No" displayed on screen no matter what DoSomethingElse() does.

In most other cases, try-catch is preferred, for one or more of the following reasons:

try-catch allows you to use the return value of a method for what it was conceptually designed to do; return the result of the operation, instead of a status code indicating whether a valid result is contained in an output or reference parameter that is the REAL product of the method.

try-catch allows for more object-oriented error-handling, as was mentioned, by avoiding the use of "magic numbers"; you don't have to know that return code -2 of this method is an error that an argument was null, you just catch an ArgumentNullException. And, you can catch that same ArgumentNullException thrown from any method that cares whether one of its passed parameters was null, instead of having to know that this method would return -2 and another method returns -3 in the same situation.

By that token, try-catch helps to standardize the expected behavior in a particularly exceptional case: If you pass a null parameter to a method that requires that parameter to not be null, you will get an ArgumentNullException, and it is usually bad practice to throw any other exception or to assume some base case that equates null with a discrete value.

try-catch isn't limited to calling methods; you can "try" a possible division-by-zero operation inline in your code and catch the exception thrown by the runtime should it occur.

try-catch isn't limited to one method at a time; you can, with minimal additional code, handle exceptions from a series of several methods, and abort processing, without having to examine the most recent return code of each method you call.


答:
First method: O(n) in methods * O(m) in call sites.

Second method: O(n) methods.

It's clear that the first method requires way too much code and violates DRY all over the place.


问:
Why do we study Java at university?
Java is often found in academia. What is the reason behind that? </p>

答:
I think a large part of it is that's what's being used in the industry.

My CS program had an Industrial Advisory Board, made up of senior staff from local tech and aerospace companies, and they had a lot of input into the curriculum.  The intro CS classes dropped Pascal in favor of C the year I started (1986), largely at the behest of the IAB.  Similarly, there was a push to teach Ada in some of the higher-level courses since the local aerospace companies were having to use it for DoD work.

Java's pretty ubiquitous now, especially now that Android devices are taking off.  It sucks from a didactic perspective, but then, so did C.

Title: Why do we study Java at university?


答:
I was once in my life working for free: A local company provided a topic for a students project that was mentored by both the company and the school. The company did not offer any payment, since I was a 17 year old kid with not much experience back then. I accepted nevertheless, since the project was rather interesting and I saw it as an opportunity to get experience and contacts. After finishing the project 10 months later, I was asked if I wanted to work for them after finishing school. Since I decided to go to university, I didn't accept the full time position but have been working part time for them every since.

However, I would not work for free anymore now: I do have a bit of experience now even if I've not yet finished university and I'm skilled enough to get paid.

Title: Working for free?

Body:
I came across this article Work for Free that got me thinking.

The goal of every employer is to gain
  more value from workers than the firm
  pays out in wages; otherwise, there is
  no growth, no advance, and no
  advantage for the employer.
  Conversely, the goal of every employee
  should be to contribute more to the
  firm than he or she receives in wages,
  and thereby provide a solid rationale
  for receiving raises and advancement
  in the firm.

I don't need to tell you that the
  refusenik didn't last long in this
  job.

In contrast, here is a story from last
  week. My phone rang. It was the
  employment division of a major
  university. The man on the phone was
  inquiring about the performance of a
  person who did some site work on
  Mises.org last year. I was able to
  tell him about a remarkable young man
  who swung into action during a crisis,
  and how he worked three 19-hour days,
  three days in a row, how he learned
  new software with diligence, how he
  kept his cool, how he navigated his
  way with grace and expertise amidst
  some 80 different third-party plug-ins
  and databases, how he saw his way
  around the inevitable problems, how he
  assumed responsibility for the
  results, and much more.

What I didn't tell the interviewer was
  that this person did all this without
  asking for any payment. Did that fact
  influence my report on his
  performance? I'm not entirely sure,
  but the interviewer probably sensed in
  my voice my sense of awe toward what
  this person had done for the Mises
  Institute. The interviewer told me
  that he had written down 15 different
  questions to ask me but that I had
  answered them all already in the
  course of my monologue, and that he
  was thrilled to hear all these
  specifics.

The person was offered the job. He had
  done a very wise thing; he had earned
  a devotee for life.

The harder the economic times, the
  more employers need to know what they
  are getting when they hire someone.
  The job applications pour in by the
  buckets, all padded with degrees and
  made to look as impressive as
  possible. It's all just paper. What
  matters today is what a person can do
  for a firm. The resume becomes pro
  forma but not decisive under these
  conditions. But for a former boss or
  manager to rave about you to a
  potential employer? That's worth
  everything.

What do you think? Has anyone here worked for free? If so, has it benefited you in any way? Why should(nt) you work for free (presuming you have the money from other means to keep you going)? Can you share your experience?

Me, I am taking a year out of college and haven't gotten a degree yet so that's probably why most of my job applications are getting ignored. So im thinking about working for free for the experience?


问:
Should main method be only consists of object creations and method calls?
A friend of mine told me that, the best practice is class containing main method should be named Main and only contains main method. Also main method should only parse inputs, create other objects and call other methods. The Main class and main method shouldn't do anything else. Basically what he is saying that class containing main method should be like:

```<code>public class Main
{
    public static void main(String[] args)
    {
        //parse inputs
        //create other objects
        //call methods
    }
}
</code>```

Is it the best practice?

答:
The main() method is an ugly throwback to procedural programming, providing the entry point into the application. Attempts are made in various programming languages to encapsulate it, but its very nature makes this difficult (it has to be public and static, but it should NEVER be called from anything else in the program, which is highly contradictory). WPF succeeded (by hiding main() from you deep in the bowels of the WPF application project and providing configurable "hooks" for custom processing), as did Java (in a similar way for Android apps), but WinForms and most other types of apps still make you deal with main().

So, most experts say that the LOC of the main() function should be as low as possible. There is one approach (which I think is slightly overkill) in which the main() function has one line:

```<code>public class Program
{
   private Program(string[] args)
   {
      //parse args and perform basic program setup
   }

   //Reduce the ugliness to the absolute minimum
   public static void main(string[] args)
   {
      new Program(args).Run();
   }

   private void Run()
   {
      //kick off the driving O-O code for the app; i.e. Application.Run()
   }
}
</code>```

This is a little much, but I agree with the basic principle; main() should to as little as possible to get your object-oriented, event-driven application into a "ready" state.

Body:
The main() method is an ugly throwback to procedural programming, providing the entry point into the application. Attempts are made in various programming languages to encapsulate it, but its very nature makes this difficult (it has to be public and static, but it should NEVER be called from anything else in the program, which is highly contradictory). WPF succeeded (by hiding main() from you deep in the bowels of the WPF application project and providing configurable "hooks" for custom processing), as did Java (in a similar way for Android apps), but WinForms and most other types of apps still make you deal with main().

So, most experts say that the LOC of the main() function should be as low as possible. There is one approach (which I think is slightly overkill) in which the main() function has one line:

public class Program
{
   private Program(string[] args)
   {
      //parse args and perform basic program setup
   }

   //Reduce the ugliness to the absolute minimum
   public static void main(string[] args)
   {
      new Program(args).Run();
   }

   private void Run()
   {
      //kick off the driving O-O code for the app; i.e. Application.Run()
   }
}

This is a little much, but I agree with the basic principle; main() should to as little as possible to get your object-oriented, event-driven application into a "ready" state.


答:
...Pretend that the job is to make an omelet. Listing: crack the egg, break into bowl, scramble, etc.; crosses over the line into the territory of how...

  ...

  My idea of a requirements doc for an omelet would be more like: has two eggs, x ounces of ham, x ounces of bacon, x ounces of montery-jack cheese, x ounces of cilantro, etc. - nothing but what (nouns)...

Well for omelet, I would prefer first version requirements to second one, simply because second version puts me at risk of getting two eggs, x ounces of ham, etc - nothing but that, neither fried nor scrambled.

Second version guarantees getting what I need, but it somewhat sucks, too - just because the only way to make sure that requirements are met seem to be to stay in the kitchen closely watching each and every step of making a meal.

You see, I would prefer requirements that would somehow allow me to test / verify the result without being forced to watching how you prepare the meal.

One way to achieve that would be to specify requirements as passing comparison against reference. Using omelet example, I would make my own "reference" omelet following same instructions as you, then compare yours for being close enough to it.

I used that approach when I needed to test a heavily optimized version of particular algorithm. "Reference omelet" in this case was presented by simplified, non optimized algorithm. I run the same input with two kinds of algorithm then checked if output produced by optimized version was close enough to the reference.

Another way would be to state requirements so that these describe result. For omelet that would be like "4 oz of eggs, scrambled and fried, etc...". I dealt mostly with this kind of requirements - I think this is most typical way.

For the sake of completeness, I probably have to describe yet another kind of specifying requirements I have dealt with - test-based. I can't imagine a way that wouldn't sound lame for omelet example - something like "when expert looks at and tastes it, they say OK" - but have to admit, in the only case I've seen it used for software, it didn't feel particularly smart either.


答:
I read through every answer and this is why I'm adding my own:

OP didn't mean will you work completely for free and assuming somehow you have money for gas, food and shelter.  The question seems to imply this: If you are salaried (or hourly but capped) and are only paid for 40 hours, would you give your employer anything on top of that? Would you work 50 or 60 hours even though you won't see a single cent (or whatever your local currency is) increase in your paycheck? His example was +11 hours for 3 days = 33 free hours.

The word "free" seems to imply money/cash and that is only a small part of total compensation.

So here's my take: to all those people that violently stated "NEVER" would they ever work for free. More than likely that's just a bunch of BULLCRAP. At one time or another all of us have to stay extra 5-10 hours (sometimes more) and finish things up. Would you be doing it consistently for a duration of a full year... that's a different story.  In OP's example the guy only did 3-day stretch of extra work.  Don't tell me you've never had to work longer to finish a bug or a feature that had to go into some fixed-schedule build.

As for the second point. When I look at my place of employment, this is my total compensation formula (yours should be very similar):

```<code>Total Compensation = Salary + Quality of life
                     + Other benefits(vacation, insurance...)
                     + non-financial factors (flexible time, choosing work...)
                     + having fun + learning/gaining skills
                     - management treating me like a "resource"
</code>```

Ever since I was a co-op I've often worked extra hours but I do not consider that being "free" just because my salary part of the equation didn't go up.

While still a co-op, I was promoted to a team lead. Sure, someone here will read this and say, "ha, sucker, you are a lead and doing more work for free". But I've learned a ton of new skills: managing requirements, working with people, driving product architecture and design... list goes on.

Every year I've always been at the top end of salary increase range. This pays back for some extra time, which is nice, but doesn't really come close to covering all of it.

I love coding. I used to code my projects for free because it was fun and sometimes I do find myself not being able to stop writing code just because it is time to go home. What is wrong with that?? I've written some really nifty things, which my employer ended up using, but my compensation was simply the fun aspect of it.

I will put in extra time if that improves quality of life (at work) for myself and my team. I've spent extra outside of normal work hours to ramp up our transition to TDD. I did projects which were not part of "requirements" but saved everyone a ton of time.  Sure, I never got financially compensated for it, but if that means I spend that much less time in QA fighting bugs and that much more time writing new code, I'm all for putting in a little extra effort.

With the extra hours, if I want to go kayak or go camping for a few days, I do not need to request or even ask for vacation days. I just go.  My boss knows I'm gone but it's never been an issue and yeah, I love this extra flexibility. I'd rather code at night and then go to the beach the next morning.

Title: Working for free?

Body:
I read through every answer and this is why I'm adding my own:

OP didn't mean will you work completely for free and assuming somehow you have money for gas, food and shelter.  The question seems to imply this: If you are salaried (or hourly but capped) and are only paid for 40 hours, would you give your employer anything on top of that? Would you work 50 or 60 hours even though you won't see a single cent (or whatever your local currency is) increase in your paycheck? His example was +11 hours for 3 days = 33 free hours.

The word "free" seems to imply money/cash and that is only a small part of total compensation.

So here's my take: to all those people that violently stated "NEVER" would they ever work for free. More than likely that's just a bunch of BULLCRAP. At one time or another all of us have to stay extra 5-10 hours (sometimes more) and finish things up. Would you be doing it consistently for a duration of a full year... that's a different story.  In OP's example the guy only did 3-day stretch of extra work.  Don't tell me you've never had to work longer to finish a bug or a feature that had to go into some fixed-schedule build.

As for the second point. When I look at my place of employment, this is my total compensation formula (yours should be very similar):

Total Compensation = Salary + Quality of life
                     + Other benefits(vacation, insurance...)
                     + non-financial factors (flexible time, choosing work...)
                     + having fun + learning/gaining skills
                     - management treating me like a "resource"

Ever since I was a co-op I've often worked extra hours but I do not consider that being "free" just because my salary part of the equation didn't go up.

While still a co-op, I was promoted to a team lead. Sure, someone here will read this and say, "ha, sucker, you are a lead and doing more work for free". But I've learned a ton of new skills: managing requirements, working with people, driving product architecture and design... list goes on.

Every year I've always been at the top end of salary increase range. This pays back for some extra time, which is nice, but doesn't really come close to covering all of it.

I love coding. I used to code my projects for free because it was fun and sometimes I do find myself not being able to stop writing code just because it is time to go home. What is wrong with that?? I've written some really nifty things, which my employer ended up using, but my compensation was simply the fun aspect of it.

I will put in extra time if that improves quality of life (at work) for myself and my team. I've spent extra outside of normal work hours to ramp up our transition to TDD. I did projects which were not part of "requirements" but saved everyone a ton of time.  Sure, I never got financially compensated for it, but if that means I spend that much less time in QA fighting bugs and that much more time writing new code, I'm all for putting in a little extra effort.

With the extra hours, if I want to go kayak or go camping for a few days, I do not need to request or even ask for vacation days. I just go.  My boss knows I'm gone but it's never been an issue and yeah, I love this extra flexibility. I'd rather code at night and then go to the beach the next morning.


问:
Visually and audibly unambiguous subset of the Latin alphabet?
Imagine you give someone a card with the code "5SBDO0" on it.

In some fonts, the letter "S" is difficult to visually distinguish from the number five, (as with number zero and letter "O").

Reading the code out loud, it might be difficult to distinguish "B" from "D", necessitating saying "B as in boy," "D as in dog," or using a "phonetic alphabet" instead.

What's the biggest subset of letters and numbers that will, in most cases, both look unambiguous visually and sound unambiguous when read aloud?

Background:

We want to generate a short string that can encode as many values as possible while still being easy to communicate.

Imagine you have a 6-character string, "123456".  In base 10 this can encode 10^6 values.

In hex "1B23DF" you can encode 16^6 values in the same number of characters, but this can sound ambiguous when read aloud. ("B" vs. "D")

Likewise for any string of N characters, you get (size of alphabet)^N values.

The string is limited to a length of about six characters, due to wanting to fit easily within the capacity of human working memory capacity.

Thus to find the max number of values we can encode, we need to find that largest unambiguous set of letters/numbers.  There's no reason we can't consider the letters G-Z, and some common punctuation, but I don't want to have to go manually pairwise compare "does G sound like A?", "does G sound like B?", "does G sound like C" myself.  As we know this would be O(n^2) linguistic work to do =)...

答: For English, the soundex and Metaphone algorithms encode which sounds are ambiguous. Soundex is probably too simple, but Metaphone incorporates some good points.  Do you want the sequence "OU" ? That could be pronounced in many ways, as this sentence demontrates ;)</p>


问:
Better word for Optional Requirements?
What's a better word for an optional requirement in software engineering? The phrase is contradictory. I've used "Non-Core Requirements" in previous projects.</p>

答:
I am quite surprised no one has mentioned that those are called "objectives". Every company I have worked for has called them that. They are denoted by use of the words "will" or "should" instead of "shall". Sometimes they are included in Braces when talking about numbers. e.g. The system shall operate continuously without need of operator attention for 100 {250} hours.  Meaning that the requirement that must be met is 100 hours, but the objective is 250 hours.

As a side note, very seldom does anyone ever actually design to meet the objective requirement, unless there is some sort of incentive involved.

Title: Better word for Optional Requirements?


答:
Because they hope that less students will fail the course, which is a FAIL in itself, IMHO. Maybe one of the reasons why almost no one takes University degrees seriously any more, at least here.

Java is too simple of a language, and doesn't teach the PC has limited resources paradigm. While at the same time forces into "there is nothing that can't be solved with another layer of abstraction" line of thinking.

Yes, it's good for OOP concepts and toy problems, but it teaches to approach the problems from the wrong angle. Use neat construct here, screw the rest.

But academia is known for being dreamy about AI, OWL and other toy technologies. While they keep researching such things, sometimes, someone invents something amazing there as well, but if you want to be a good developer you have to learn that independently.

Title: Why do we study Java at university?

Body: Java is often found in academia. What is the reason behind that? </p>


问:
Good books or tutorials on building projects without an IDE?
While I'm certainly under no illusions that building software without an IDE is possible, I don't actually know much about doing it well.  I've been using graphical tools like Visual Studio or Code::Blocks so long that I'm pretty well lost without them.

And that really stinks when I want to change environments or languages.  I couldn't really do anything in D until someone made a Visual Studio plugin, and now that I'm trying to do more development on Mac, I can't use D again because the XCode plugins don't work.

I'm sick of being lost when I see a .make file and having no idea what I'm supposed to do with a folder full of source files.  People can't be compiling them one by one using the console and then linking them one by one.  You'd spend more time typing file names than code.  So what are the automation and productivity tools of the non-IDE user?  How do you manage a project when you're writing all the code in emacs or vim or nano or whatever?

I would love it if there was a book or a guide online that spells some of this out.

答:
There was a recent HackerNews post on using the Unix/Linux shell and its many tools as an IDE.  Another post spoke of using a combination of Vim and tmux to get the goodies that an IDE brings.

Installing tmux on Mac should be easy with Macports.  Here is the Vim + tmux link.  ATM, the other link eludes me.  It should be easy with Google, I hope.

I think you would need to learn to read and write Makefile fluently, from what you say in the question.


答:
What do I think? This article sounds like class warfare propaganda. The sort of pamphlet a boss would pass around before he announces pay cuts while company profits soar.

I understand the goal of an employer. If they didn't make money employing people, they wouldn't. But the part about the employee's goal starts in the wrong place.

Conversely, the goal of every employee should be to contribute more to
  the firm than he or she receives in wages, and thereby provide a solid
  rationale for receiving raises and advancement in the firm.

No, the goal of the employee is to maximize his pay, benefits, etc. (both long-term and short), while putting in the minimal amount of effort and resources to achieve that. FROM THERE you can rationalize that "working for free" be it overtime or straight up pro-bono will secure better long-term rewards, but that's a pretty shoddy argument and it ignores the short term goal. Most companies today have very little loyalty to their employees. Pensions are a thing of the past. When profits slump, layoffs are quick. And if there are problems they'd rather bring in temporary contractors than hire someone full-time. Unless they contractually owe you for your extra work, why would they reward you? That goes against their stated goal.

The part of the story where the previous boss is the primary decider of future employment is downright tyrannical.

If you need experience to help your resume, contribute to or start an open source project. I've had potential employers request to view my projects. I couldn't show him anything I've done for previous jobs because it was proprietary. My single open-source project was all I could legally show him. And it was * cough * a little rough around the edges.

Title: Working for free?


答:
There is nothing substantially different between working for free, working for very little, or even paying to work for someone! You have to decide whether you come out ahead in the end, and if you have any better options. That's all that matters.

While in college, I created a few websites for dirt cheap or even nothing to get experience and to look good on my resume. I could have made more money flipping burgers with the time I spent, but for me, working for "free" was more valuable because it allowed me to earn more in the future. Money isn't the only benefit of a job, so worrying about working for "free" is a red herring.

In the real world, if you're salaried, any time you work above the amount you need to not get fired is time you're working for "free". If you can get by working 35 hours/week, why would you choose to work 45 and get paid the same amount? Are you being exploited? Of course not, you know that you won't get promoted if you don't work hard.

For those who argue that working for free for open source projects or charity is different are wrong. Whether somebody is profiting from your work is irrelevant to the algebra of whether it's a good idea from your perspective. It's irrelevant how much your employer benefits, all you care about is how much you benefit.

The one point to note is that if somebody wants for you to work for free, they're probably going to be a terrible employer, so make sure you factor that in.

Title: Working for free?


答: The term "Desirement" is sometimes used for optional requirements. However, it may not be appropriate for a formal document. </p>

Title: Better word for Optional Requirements?

Body: What's a better word for an optional requirement in software engineering? The phrase is contradictory. I've used "Non-Core Requirements" in previous projects.</p>


问:
Java web app, with plugin framework and ability to connect to source for updates
I've searched all around for some good sources, but either have been searching for the wrong keywords, or I'm just missing something. I'm looking to redevelop a web app I've been using for some time now. Many parts are out of date, and we're constantly throwing in little hacks to attempt to give it new life.

So what I'd like to do is re-engineer it from the ground up, built on some sort of plug-in framework. Before I continue, I'm more or less an intermediate Java programmer. In some ways, I'm hoping to use this project as a big learning experience.

I've read a lot about OSGi, and it seems that's the most complete framework. Ideally, I would like an end result web app which I can run one instance as my hosting environment, and other instances can connect to it to grab new and updated plug-ins. Eventually I'll want to lock down these plug-ins based on some undecided criteria of who can get them (basically some will simply be updates, others will provide new functionality and should be "purchased" through an external system). But that will probably be handled in a later phase. There should be an administration view for managing bundles in a hot environment (looking to avoid having to restart the server for an update).

I know all these things are possible, I'm just trying to find some good resources for reference. All the OSGi tutorials I'm finding seem to be too simplistic. If anyone here can guide me in the right direction on any or all of the items I'm looking for, it would be much appreciated. Also, this is my first post, so I'll take any comments/criticisms about the content of my post. Thanks!

答:
I'm on a limited connection here, so will be short.

I'd strongly suggest you look at OSGi & Project Jigsaw going forwards.  Also you might find success with JSR-330 (aka Dependency Injection for Java).  Sonatype and others are using it as basis for a plugin framework on Hudson amongst other things.  HTH a little and hopefully a more complete answer blows mine away :-)


问:
Is there any algorithm book that teaches like Head First series?
As a Java programmer I need to learn algorithms (for programming Challenges). I read some Head First Series (JAVA owned by me) and they are pretty brain friendly. So I was wondering is there any algorithm book that will be simple to understand and also goes to the crux of each algo.</p>

答: I personally like the book Algorithms by Robert Sedgewick and Kevin Wayne very much. The book has very beautiful illustrations show how different algorithms work, and also provides very practical examples. You can get some feeling about the quality of the book by visit the companion website.</p>


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答:
The answer lies in the middle.

Have one fast box to run the dev environment (eg Eclipse)

And another slow box for testing the output. This is especially important for web apps.

Side-by-side screens, one for each box.

If the code is acceptable on the output box, it will be more than acceptable for most users.

Fast dev boxes make programmers lazy. For example, searching for an element in the DOM every time it's needed. Find it once and cache the result.

You'll really notice the difference on a slow box running IE 6....

OwnerDisplayName: David Semeria


问:
Where do other programming languages fit in Windows 8 development model?
Today, Windows applications can be developed in numerous languages and frameworks. But in the upcoming Windows 8, with the introduction of WinRT, the development model is going change at a large scale. So, where do other programming languages fit in this model?</p>

答: Native C++ a first-class citizen! Well, those of us who have stuck with C++ (and perhaps cross-platform) through the years have always felt so - and even more so now with C++11 (big thanks to all the contributors)!!. Yes, there were many detractors who thought the language was dead or dying (I've heard the words myself), and maybe at times it seemed we chose the desert route (lower pay, fewer opportunities) rather than accepting the shackles. But now, does anyone else care to join me in saying Hallelujah, we're back, and we've been justified?!:)</p>


问:
Are there design patterns or generalised approaches for particle simulations?
I'm working on a project (for college) in C++.
The goal is to write a program that can more or less simulate a beam
of particles flying trough the LHC synchrotron.

Not wanting to rush into things, me and my team are thinking about how to implement this and I was wondering if there are general design patterns that are used to solve this kind of problem.

The general approach we came up with so far is the following:

there is a World that holds all objects

you can add objects to this world such as Particle, Dipole and Quadrupole

time is cut up into discrete steps, and at each point in time, for each Particle the magnetic and electric forces that each object in the World generates are calculated and summed up (luckily electro-magnetism is linear).

each Particle moves accordingly (using a simple estimation approach to solve the differential movement equations)

save the Particle positions

repeat

This seems a good approach but, for instance, it is hard to take into account symmetries that might be present (such as the magnetic field of each  Quadrupole) and is this thus suboptimal.

To take into account such symmetries as that of the Quadrupole field, it would be much easier to (also) make space discrete and somehow store form of the Quadrupole field somewhere. (Since 2532 or so Quadrupoles are stored this should lead to a massive gain of performance, not having to recalculate each Quadrupole field)

So, are there any design patterns? Is the World-approach feasible or is it old-fashioned, bad programming? What about symmetry, how is that generally taken into acount?

答: Check into the graphics community for particle physics simulations.  There are many existing patterns (physics solvers and such for particle systems), and it is a well-understood concept for that community, and there are many implementations.  You will save yourself a great deal of time.</p>


答: Ask the client if they would create more efficient business processes using slow PCs.</p>

Title: Does giving a developer a slower development machine result in faster/more efficient code?

Body:
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards


答:
Typically each OS and framework has it's own preferred way to build things. Linux uses various flavors of make, Java has ANT and MAVIN, QT has QMake, to name a small number of the ones out there.

Your problem is likely that you have yet to learn how build tools work under the bonnet- even your Microsoft IDE  has a complex build control system that revolves around a list of files, dependencies and what to do with them.

I would suggest starting with the basics of the ubiquitous Make. It's been around so long a variation is available on every platform. It's not the best for 2012, difficult to use ( and rarely used )  properly and has a steep learning curve.  Once you have "mastered" a simple make file containing a couple of files, extend it to include building a library of a couple and  linking to that library. Don't go much further.

Then have a look at more modern replacements such as ANT and SCons.

Once you have grasped the ideas of these tools, you will be able to get a simple project off the ground on any OS/Framework quite quickly. Don't get discouraged - there are teams of people in large software houses whose sole job is this kind of thing.

Another option is a portable IDE such as Eclipse where these things are largely dealt with for you. However at some time in you career, you will benefit if you learn whats happening behind the scenes.

Title: Good books or tutorials on building projects without an IDE?

Body:
While I'm certainly under no illusions that building software without an IDE is possible, I don't actually know much about doing it well.  I've been using graphical tools like Visual Studio or Code::Blocks so long that I'm pretty well lost without them.

And that really stinks when I want to change environments or languages.  I couldn't really do anything in D until someone made a Visual Studio plugin, and now that I'm trying to do more development on Mac, I can't use D again because the XCode plugins don't work.

I'm sick of being lost when I see a .make file and having no idea what I'm supposed to do with a folder full of source files.  People can't be compiling them one by one using the console and then linking them one by one.  You'd spend more time typing file names than code.  So what are the automation and productivity tools of the non-IDE user?  How do you manage a project when you're writing all the code in emacs or vim or nano or whatever?

I would love it if there was a book or a guide online that spells some of this out.


答:
Okay most large build systems are scripted with command line tools or specialized tools. I have used make, nmake, ant, nant, perl, python, bash and batch files. I have also used specialized tools like Visual Build and Final Builder to produce builds for production systems. Tool chains are different for each environment.

Make is the grandfather of most commandline build tool chains and it does have a book from O'Reilly: http://shop.oreilly.com/product/9780596006105.do

You should consider O'Relly's Unix in a Nutshell 4th Edition as it touches on Unix and (by extension the GNU tool chain) commandline tool chains for builds: http://shop.oreilly.com/product/9780596100292.do

Also consider more general material in the search for tools chain understanding. The Build Master by Vincent Maraia: http://www.amazon.com/The-Build-Master-Microsofts-Configuration/dp/0321332059
Vincent Maraia book chapter 5 touches build chains and the whole book is touches on the whole software configuration environment.

A more recent book for a "modern" holistic approach look at Continuous Delivery by Jez Humble and David Farley ( http://www.amazon.com/Continuous-Delivery-Deployment-Automation-Addison-Wesley/dp/0321601912 )

The Window tool chain is a little different using MSBuid in present versions for the command line so Look at the Microsoft press book http://www.amazon.com/Inside-Microsoft®-Build-Engine-Pro-Developer/dp/0735626286

I have all books I recommended except the MSBuild book ( And I do plan to get it )

Also the java commandline tool chain is yet a third command-line tool chain and it is documented several books on Java.  Ant and Mavin are useful in scripting java builds (and have been extended to do other types of builds as well) a book on Ant I have is Ant the Definitive Guide 2nd Edition ( http://shop.oreilly.com/product/9780596006099.do ) but it is a bit dated.


答:
"Should the functional requirements in a requirements doc use wording based on verbs?"

The short answer is "yes", but the path to get there is winding.

If the requirements doc is a collection of "shall" statements written as English sentences, you must have a verb phrase.  And that verb phrase will the "shall xxx" as in "the system shall xxx".  The "xxx" part is one of three types of verbs, "be", "do" and "have".  These sentences must describe the system as a black box, only recording those things that can be seen from the outside.  As you said, "the what rather than the how".  If it is visible from the outside it is a "what".

The only possible function that is available to a digital system is to change the value of a variable.  Therefore, all functional requirements must state what variable is changed and the calculations that are used to do the changing.  These are the "do" requirements.

The "be" requirements tend to describe features rather than functions.  "The system shall be able to ...".  They describe a "state of being".

The "have" requirements are the nouns that you talked about.  "The system shall have ..."  They provide the nouns for the functional requirements sentences.

At a high level there are very few functional requirements.  Most of the requirements are either feature requirements, performance requirements or compositional (have) requirements.

All high level requirements that need children are, by definition, ambiguous.  If they were unambiguous they would not need children to define them.  Further, a requirement is only unambiguous if the majority of the people in a requirements review declare that it is.  I.e, ambiguity is subjective.  The closest definition for an unambiguous FUNCTIONAL requirement that I know of is at BarBaraBea.com on the "Unambiguous Functional Requirements" page. Basically is says that all of the nouns in a functional requirement must be derived from the system inputs through a chain of unambiguous functional requirements, and that the statement of the computation in the requirement must describe an algorithm.  The definition of "algorithm" is much less subjective than the definition of "unambiguous requirement".


答:
All requirements can essentially be reduced to a collection of statements that revolve around the use of verbs.  Yes, you can throw in a few nouns and adjectives, but it's the verbs that describe how a system behaves, and what it is that the customer wants the software to do.  Even a lot of the state-specific functionality of a program can be thought of in terms of behaviours when you present state through getter and setter methods.

It's just like CFL_Jeff mentions in his answer, that you want to have your requirements describing what a system will do, and not to describe how it should be done.  This is possibly why I find the behaviour-driven development so compelling, because it encourages the use of verbs do describe requirements, and the use of verbs when writing unit tests to describe requirements as behaviours to be tested.

Consider for a moment the following requirements and scenario templates:

As an {actor} I want to {do something} in order to {achieve an outcome}

Given {an initial context} When {something is done} Then {expect an outcome}

In BDD, features are always the bit described in the "I want" section of the template, and they are always loaded with verbs describing what the feature does. When testing, a Given-When-Then template is used to validate specific scenarios pertaining to the feature, and once again the "When" section of the template is always defined by the verbs used, which relate back in some manner to the verbs used in the feature specification.

Using your omelete example, defining a number of behaviours as a series makes a lot of sense. You have a collection of behaviours, and outcomes, and as a series they form a workflow. If you were to instead define a list of ingredients, you are effectively describing the architecture very loosely, however you are left with a lot of questions.  What is the workflow?  How are the ingredients to be used? You are basically missing the "glue" that will guide your decisions about how to put your system together, and how your system is supposed to behave.

By defining requirements in terms of behaviours and outcomes, you are able to provide a very clear picture of what it is you want the software to achieve, without worrying about how to specifically achieve such outcomes in software.


问:
How do you track bugs in your personal projects?
I'm trying to decide if I need to reassess my defect-tracking process for my home-grown projects.  For the last several years, I really just track defects using TODO tags in the code, and keeping track of them in a specific view (I use Eclipse, which has a decent tagging system).

Unfortunately, I'm starting to wonder if this system is unsustainable.  The defects I find are typically associated with a snippet of code I'm working on; bugs which are not immediately understood tend to be forgotten, or ignored.  I wrote an application for my wife which has had a severe defect for almost 9 months, and I keep forgetting to fix it.

What mechanism do you use to track defects in your personal projects?  Do you have a specific system, or a process for prioritizing and managing them?

答:
For my personal projects I use Omnifocus.

Update:25/10/2010
If i find a bug that I can't or don't want to fix immediately I quickly add it to the Omnifocus inbox. Then later, when I'm doing a review I will gather all the info that I think I will need to fix the bug and then add it to the project. It's position in the task list indicates it's relative importance.

I treat bugs the same way as requirements/features in most respects.


问:
How to improve designer and developer work flow?
I work in a small startup with two front end developers and one designer. Currently the process starts with the designer sending a png file with the whole page design and assets if needed. My task as front end developer is to convert it to a HTML/CSS page. My work flow currently looks like this:

Lay out the distinct parts using html elements.

Style each element very roughly (floats, minimal fonts and padding) so I can modify it using inspection.

Using Chrome Developer Tools (inspect) add/change css attributes while updating the css file.

Refresh the page after X amount of changes

Use Pixel Perfect to refine the design more.

Sit with the designer to make last adjustments.

Inferring the paddings, margins, font sizes using trial and error takes a lot of time and I feel the process could become more efficient but not sure how to improve it.

Using PSD files is not an option since buying Photoshop for each developer is currently not considered. Design guide is also not available since design is still evolving and new features are introduced.

Ideas for improving the process above and sharing how the process looks like in your company will be great.

答:
The solution is a design or style guide and if your team isn't ready then you are gonna have to rough it out until you are.

I would suggest drafting a design standards document, and iteratively revisiting it every set period of time.

If you know every button will have a padding of 10, you don't have to check with the designer everytime you implement a button.

Even if the first draft is wrong at least it's a start and it's easier to coordinate cross teams with a single file.  This is why programmers use interfaces, and the designer can and will modify it over time.  It's up to you to maintain your css as cleanly as possible, so making these tweaks over time aren't a terrible chore.

Also, if/when the designer leaves the team a solid style guide can be used and maintained by future designers.


答:
Jon Purdy's answer above seems most correct.  For practical purposes, I am trying z-base-32, a non-standard base32 encoding designed with communicability in mind.  It looks functional, though not ideal--e.g. they explicitly didn't focus on spoken disambiguation.

http://philzimmermann.com/docs/human-oriented-base-32-encoding.txt

http://pypi.python.org/pypi/zbase32/

Title: Visually and audibly unambiguous subset of the Latin alphabet?

Body:
Imagine you give someone a card with the code "5SBDO0" on it.

In some fonts, the letter "S" is difficult to visually distinguish from the number five, (as with number zero and letter "O").

Reading the code out loud, it might be difficult to distinguish "B" from "D", necessitating saying "B as in boy," "D as in dog," or using a "phonetic alphabet" instead.

What's the biggest subset of letters and numbers that will, in most cases, both look unambiguous visually and sound unambiguous when read aloud?

Background:

We want to generate a short string that can encode as many values as possible while still being easy to communicate.

Imagine you have a 6-character string, "123456".  In base 10 this can encode 10^6 values.

In hex "1B23DF" you can encode 16^6 values in the same number of characters, but this can sound ambiguous when read aloud. ("B" vs. "D")

Likewise for any string of N characters, you get (size of alphabet)^N values.

The string is limited to a length of about six characters, due to wanting to fit easily within the capacity of human working memory capacity.

Thus to find the max number of values we can encode, we need to find that largest unambiguous set of letters/numbers.  There's no reason we can't consider the letters G-Z, and some common punctuation, but I don't want to have to go manually pairwise compare "does G sound like A?", "does G sound like B?", "does G sound like C" myself.  As we know this would be O(n^2) linguistic work to do =)...


问:
Some Insight on the Field of Knowledge Representations and Reasoning
I started following an MS in computer sciences after about two years of work for a software company. I worked primarily in data warehousing and business intelligence related software development during my previous occupation.

There is a high chance for me to select a research in knowledge representations, ontologies and reasoning, as there are no other research available in any other interesting fields, such as pattern recognition and navigation. I developed an interest towards knowledge representation with what I learnt from the courses I am taking currently. But I do not have a deep understanding of it in terms of which areas such a field would have an impact in a real life scenario, and how it will help me when I am hunting for a job in the near future.

Some thought about this would be greatly appreciated.

答: The W3C publishes a list of case studies and use cases which might be of interest. Apart from that, I know several law firms keep ontological descriptions of their cases.</p>


问:
How to write less code
A quality what I would like to develop is to write more concise code. With writing more concise, at least in my opinion, the opportunity to add bugs to the code is smaller. It is easier to read the code for other.

My question is if it is something that just comes with experience or is it something you can do explicitly for developing that quality?

答:
Go back yo your older long winded code,

put it under version control,

write some tests for it to have a reasonable hope not be introducing new bugs,

rewrite.

Repeat ad libitum. And welcome to hell.

Title: How to write less code


问:
Are there open source alternatives to Bitbucket, Github, Kiln, and similar DVCS browsing and management tools?
I am aware of several tools/services that provide DVCS browsing and management such as Bitbucket, Github, Kiln, SCM-Manager and Rhodecode.

However, the use case I am considering is one such that:

Any source code must reside on an employers internal servers.

The solution must be open source.

It should provide a Bitbucket or Github like experience, including a project wiki, repository browsing and management, and social coding aspects such as code review.

The solution should have mercurial support (if not support for other DVCSs).

Of these, only SCM-Manager and RhodeCode come close as they can be installed on your own servers and are open source. However they do not have the Bitbucket or Github experience. There is no issue tracker or wiki and the UI, while functional, is not up to par with Github or Bitbucket.

I can get close with Trac or Redmine with their repository browsers but unfortunately they do not have any repository management capabilities.

Are there other open source tools out there that would provide a similar experience to Bitbucket, Github or Kiln?

答:
Gitorious is open source and you can install it on your own server using scripts provided by the Gitorious community edition (see http://www.getgitorious.com/installer). Gitorious now has support for wikis and issue tracking. There is also a Docker image available for quickly getting it running.

Another option would be Gitlab which is basically a GitHub clone, not as mature as gitorious but it's under heavy development with monthly releases.

You might also want to check out more options here


问:
Which programming language for text editing?
I need a programming language for text editing and processing (replace, formatting, regular expressions, string comparison, word processing, text analysis, etc.). Which programming language is more powerful and has more functions for this purpose?

Since I work PHP for my web projects, I currently use PHP, but the fact is that PHP is a scripting language for web applications; my current project is offline.

I am curious if other programming languages such as Perl, Python, C, C++, Java, etc. have more functionality for this purpose, and worth of shifting the project?

答:
Every popular language has facilities for text editing and processing; it's mostly a matter of personal preference. Since you are already familiar with PHP, I'd suggest Perl, as the syntax is similar, and PHP's regular expression facilities are heavily based on Perl's. Furthermore, Perl was originally designed as a text processing language, and although it has largely outgrown its origins, it might be a little bit easier to find related resources.

I'd advice against a language with a large stack, like Java or .NET, unless of course you are interested in learning the stack as well.

The bottom line is: this is less about the language and more about you. Even PHP would make a good choice, depending on your needs. Granted, there is some tweaking necessary, but if the time it takes you to learn a new language is significantly more than learning how to use PHP in an offline manner, then PHP would possibly be the better choice.


答:
As you are on Linux, I would suggest looking at Tcl, Perl and Python. Depending on what you actually want to do, these three should be able to handle it. Also educate yourself about sed, AWK and grep, etc... and use Bash, sh, and or tcsh scripts to your advantage also. (There is no reason why you cannot use a sh script to split the work into three bits and use Tcl, Perl and Python for each bit according to their aptitudes!)

I'm not sure compiled languages like C/C++, Java, etc. offer much unless you need performance and/or detailed error messages.

Title: Which programming language for text editing?

Body:
I need a programming language for text editing and processing (replace, formatting, regular expressions, string comparison, word processing, text analysis, etc.). Which programming language is more powerful and has more functions for this purpose?

Since I work PHP for my web projects, I currently use PHP, but the fact is that PHP is a scripting language for web applications; my current project is offline.

I am curious if other programming languages such as Perl, Python, C, C++, Java, etc. have more functionality for this purpose, and worth of shifting the project?


答:
I used to use a spreadsheet/text file per project (ToDo comments in the code don't scale well for the reasons you list; they're local to the code, and if there's an issue that's not, it tends to slip through the cracks).

Recently I've set up a Redmine server on my home network. It's a bit heavyweight for a "team" of one, but I'm working on quite a few projects on my own time, and tend to just use the Issue Tracker + Repository options with maybe the odd wiki page in more complex places.

A friend of mine swears by Pivotal Tracker for the same purposes, but my current employer uses Redmine internally, so I figured this would give me some practice. It's not bad.

For open source projects, I just use GitHub's issue tracking.

Title: How do you track bugs in your personal projects?

Body:
I'm trying to decide if I need to reassess my defect-tracking process for my home-grown projects.  For the last several years, I really just track defects using TODO tags in the code, and keeping track of them in a specific view (I use Eclipse, which has a decent tagging system).

Unfortunately, I'm starting to wonder if this system is unsustainable.  The defects I find are typically associated with a snippet of code I'm working on; bugs which are not immediately understood tend to be forgotten, or ignored.  I wrote an application for my wife which has had a severe defect for almost 9 months, and I keep forgetting to fix it.

What mechanism do you use to track defects in your personal projects?  Do you have a specific system, or a process for prioritizing and managing them?


答:
Perl and Ruby would be good choices. </p>

<p>However, what you really want might be AWK, which is rather old, but it will do what you want. There are a few good books on AWK, but all of them are more than 10 years old. However, don't let that phase you; it's still a powerful tool. </p>

Body:
Perl and Ruby would be good choices.

However, what you really want might be AWK, which is rather old, but it will do what you want. There are a few good books on AWK, but all of them are more than 10 years old. However, don't let that phase you; it's still a powerful tool.


答:
Test Driven development might help.
Using this, you write only the minimum code required to pass that test.</p>

Title: How to write less code

Body:
A quality what I would like to develop is to write more concise code. With writing more concise, at least in my opinion, the opportunity to add bugs to the code is smaller. It is easier to read the code for other.

My question is if it is something that just comes with experience or is it something you can do explicitly for developing that quality?