问:
Why is CATALINA_HOME named that way and other interesting program names
I work with open source software a lot and keep coming across weird and funny names for executables, variables, constants and etc. Currently I am wondering why CATALINA_HOME environment variable was named that way? I did a quick search on google with but nothing relative came up. My only guess is that it is named after the island of the shore of south California.

On the related note, very often I find amusing and clever names used in open source programs. One of my favorites are slapd and slurpd executables of OpenLDAP suite. What are your favorite/noteworthy variable/executable names that you have seen in your programming career? Do you think it is OK to name your variables/executables this way, or would you rather see boring but clear names?

PS. This is not really a programming question but I think it somewhat fits in here, according to faq.

答:
I believe it comes as a result of thinking about your applications home directory, which may in turn have been influenced by Unix home directories before that. Typical examples are

JAVA_HOME for the JDK installation directory

MAVEN_HOME for the Maven installation directory

ANT_HOME

CATALINA_HOME because the project name for the servlet engine within the overall Tomcat project was called Catalina

As a general convention for naming environment variables, the _HOME suffix has stood the test of time and so has become generally adopted for new projects that require them.

In terms of my personal favourite names, here's a short list

grep (global regular expression print) is synonymous with search among *nixers

awk (named after the programmers) is great for awkward text manipulation

For more Unix weirdness have a look at this article.


问:
When was source control invented?
I'm aware of many version control systems:  CVS, SVN, TFS etc...

I've googled for the very first "revision control/version control system" and seen various conflicting answers.

When was source control invented?  Who invented it?  What was it called?

答:
Here is a pretty decent timeline of the major players in video form (no sound).

It suggests that SCCS was first, by a margin of about 9 years.

There is a lot missing off there though, as evidenced by this blog and the resulting comments.

ContentLicense: CC BY-SA 3.0

Title: When was source control invented?


问:
Is the number of bugs in a section of code proportional to the # of lines ? The square of the # of lines ?
Are there any studies that aggregate data over a wide population of contributed code, that establish a correlation between amount of code written in a commit and the # of bugs discovered in that code ? It'd be hard to do in github without knowing whether a change was due to new functionality or a bug, but you could determine a relation between lines of code per commit and how much thrashing eventually goes on in that code. </p>

答:
It just depends.

If all your program does is Console.WriteLine over and over.. chances are it won't have any bugs no matter how big it gets.  If you're writing the next great document database, chances are you'll have a lot of bugs.

You couldn't scrape this information from github because you don't know how hard the problems people are trying to solve.. If most projects on gitHub are the complexity of a tic tac toe game, again, you probably won't see a ton of bugs. Your analysis could fool you and say "Wow codebases can expand with relatively few bugs or none at all!".

Bugs are more related to complexity, is what I'm getting at.


答:
The only metric that I'm familiar with that tries to relate possible defects to program size is one of Halstead's complexity measures. The figure used is B = (E^(2/3))/3000 or B = V/3000 where B is the number of delivered bugs, E is the amount of effort, and V is the program volume. If you simplify down to the counted values, these equate to either B = ((n1/2)(N2/n2))/3000 or B = (N1 + N2) * log2(n1 + n2) where n1 is the number of distinct operators, n2 is the number of distinct operands, N1 is the total number of operators, and N2 is the total number of operands.

Your number of bugs per commit may be related to the delta in bugs before the commit and bugs after the commit.

However, the validity of Halstead's metrics have been questioned - if you search for academic studies, you'll find papers that indicate their validity as well as papers that seem to indicate little to no validity of the metric. To the best of my knowledge, they are not widely accepted nor is there overwhelming evidence that they are empirically valid.

Title: Is the number of bugs in a section of code proportional to the # of lines ? The square of the # of lines ?

Body: Are there any studies that aggregate data over a wide population of contributed code, that establish a correlation between amount of code written in a commit and the # of bugs discovered in that code ? It'd be hard to do in github without knowing whether a change was due to new functionality or a bug, but you could determine a relation between lines of code per commit and how much thrashing eventually goes on in that code. </p>


问:
I've been told that Exceptions should only be used in exceptional cases. How do I know if my case is exceptional?
My specific case here is that the user can pass in a string into the application, the application parses it and assigns it to structured objects.  Sometimes the user may type in something invalid.  For example, their input may describe a person but they may say their age is "apple".  Correct behavior in that case is roll back the transaction and to tell the user an error occurred and they'll have to try again.  There may be a requirement to report on every error we can find in the input, not just the first.

In this case, I argued we should throw an exception.  He disagreed, saying, "Exceptions should be exceptional:  It's expected that the user may input invalid data, so this isn't an exceptional case"  I didn't really know how to argue that point, because by definition of the word, he seems to be right.

But, it's my understanding that this is why Exceptions were invented in the first place.  It used to be you had to inspect the result to see if an error occurred.  If you failed to check, bad things could happen without you noticing.

Without exceptions every level of the stack needs to check the result of the methods they call and if a programmer forgets to check in one of these levels, the code could accidentally proceed and save invalid data (for example).  Seems more error prone that way.

Anyway, feel free to correct anything I've said here.  My main question is if someone says Exceptions should be exceptional, how do I know if my case is exceptional?

答:
Exceptions should represent conditions that it's likely the immediate calling code will not be prepared to handle, even if the calling method might.  Consider, for example, code which is reading some data from a file, may legitimately assume that any valid file will end with a valid record, and is not required to extract any information from a partial record.

If the read-data routine didn't use exceptions but simply reported whether or not the read succeeded, the calling code would have to look like:

```<code>temp = dataSource.readInteger();
if (temp == null) return null;
field1 = (int)temp;
temp = dataSource.readInteger();
if (temp == null) return null;
field2 = (int)temp;
temp = dataSource.readString();
if (temp == null) return null;
field3 = temp;
</code>```

etc. spending three lines of code for each useful piece of work.  By contrast, if readInteger will throws an exception upon encountering the end of a file, and if the caller can simply pass on the exception, then the code becomes:

```<code>field1 = dataSource.readInteger();
field2 = dataSource.readInteger();
field3 = dataSource.readString();
</code>```

Much simpler and cleaner looking, with far greater emphasis on the case where things work normally.  Note that in cases where the immediate caller would be expecting to handle a condition, a method which returns an error code will often be more helpful than one which throws an exception.  For example, to total all the integers in a file:

```<code>do
{
  temp = dataSource.tryReadInteger();
  if (temp == null) break;
  total += (int)temp;
} while(true);
</code>```

versus

```<code>try
{
  do
  {
    total += (int)dataSource.readInteger();
  }
  while(true);
}
catch endOfDataSourceException ex
{ // Don't do anything, since this is an expected condition (eventually)
}
</code>```

The code which asking for the integers is expecting that one of those calls is going to fail.  Having the code use an endless loop which will run until that happens is far less elegant than using a method that indicates failures via its return value.

Because classes often won't know what conditions their clients will or will not expect, it's often helpful to offer two versions of methods that could fail in ways that some callers will expect and other callers won't.  Doing so will allow such methods to be used cleanly with both types of callers.  Note also that even "try" methods should throw exceptions if situations arise the caller probably isn't expecting.  For example, tryReadInteger should not throw an exception if it encounters a clean end-of-file condition (if the caller weren't expecting that, the caller would have used readInteger).  On the other hand, it probably should throw an exception if the data could not be read because e.g. the memory stick containing it was unplugged.  While such events should always be recognized as a possibility, it's unlikely that the immediate calling code would be prepared to do anything useful in response; it should certainly not be reported the same way as would be an end-of-file condition.

Body:
Exceptions should represent conditions that it's likely the immediate calling code will not be prepared to handle, even if the calling method might.  Consider, for example, code which is reading some data from a file, may legitimately assume that any valid file will end with a valid record, and is not required to extract any information from a partial record.

If the read-data routine didn't use exceptions but simply reported whether or not the read succeeded, the calling code would have to look like:

temp = dataSource.readInteger();
if (temp == null) return null;
field1 = (int)temp;
temp = dataSource.readInteger();
if (temp == null) return null;
field2 = (int)temp;
temp = dataSource.readString();
if (temp == null) return null;
field3 = temp;

etc. spending three lines of code for each useful piece of work.  By contrast, if readInteger will throws an exception upon encountering the end of a file, and if the caller can simply pass on the exception, then the code becomes:

field1 = dataSource.readInteger();
field2 = dataSource.readInteger();
field3 = dataSource.readString();

Much simpler and cleaner looking, with far greater emphasis on the case where things work normally.  Note that in cases where the immediate caller would be expecting to handle a condition, a method which returns an error code will often be more helpful than one which throws an exception.  For example, to total all the integers in a file:

do
{
  temp = dataSource.tryReadInteger();
  if (temp == null) break;
  total += (int)temp;
} while(true);

versus

try
{
  do
  {
    total += (int)dataSource.readInteger();
  }
  while(true);
}
catch endOfDataSourceException ex
{ // Don't do anything, since this is an expected condition (eventually)
}

The code which asking for the integers is expecting that one of those calls is going to fail.  Having the code use an endless loop which will run until that happens is far less elegant than using a method that indicates failures via its return value.

Because classes often won't know what conditions their clients will or will not expect, it's often helpful to offer two versions of methods that could fail in ways that some callers will expect and other callers won't.  Doing so will allow such methods to be used cleanly with both types of callers.  Note also that even "try" methods should throw exceptions if situations arise the caller probably isn't expecting.  For example, tryReadInteger should not throw an exception if it encounters a clean end-of-file condition (if the caller weren't expecting that, the caller would have used readInteger).  On the other hand, it probably should throw an exception if the data could not be read because e.g. the memory stick containing it was unplugged.  While such events should always be recognized as a possibility, it's unlikely that the immediate calling code would be prepared to do anything useful in response; it should certainly not be reported the same way as would be an end-of-file condition.


答:
Its proportional to the number of functions/methods not covered by unit tests.</p>

```<code>Bugs = K + M * <functions that are not tested> - N * <Integration Test Coverage>
</code>```

Body:
Its proportional to the number of functions/methods not covered by unit tests.

Bugs = K + M * <functions that are not tested> - N * <Integration Test Coverage>


问:
Good idea to move logic out of SQL statements?
I'll preface this question by saying that I am very new to professional software dev.

I work on a team that takes data in from other groups in my company and turns this data into reports usable by business execs.

In the process of transferring and parsing data we have some SQL statements that do a lot of processing of the data. Nearly every SELECT uses TRIM, SUBSTR, CAST etc extensively to reduce fields to the proper size and format. Additionally there are a lot of special cases that are accounted for by using CASE statements within SELECT's.

The Teradata server software that we use emits remarkably cryptic error messages. As a result we do a lot of guesswork about what data is breaking which SQL statement.

My question is: would it be a good idea to reduce these somewhat complex SQL statements to a less complex form that omits the processing and special case handling, and instead do this work in an external script or program? Does this make any sense?

答:
I'd be inclined to leave the CASE bits in place as these are related to the actual logic of producing the data for somone/thing to consume. So taking these out means you have to send a larger data-set back and the client has to do some processing on it - now you have split your report "logic" over two separate layers and this is not good.

But I'd drop like a hot brick any formatting from your code (unless it's specifically part of JOIN predicates, etc) because formatting it is the consumer's job...so whatever reporting tool they use, be it Excel, Crystal, etc, is good at formatting stuff in the correct locale and all that jazz. Let the client do whatit's good at (showing things in pretty colours) and let the server focus on what it does best - crunching data.


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
This is a bit over 60 characters but it really depends on variable naming (so I'm including it!)

let readLines (rdr : StreamReader) =

          seq { while not rdr.EndOfStream do

 yield rdr.ReadLine()}

Nice little function to read a file into a sequence line by line in F#.

ContentLicense: CC BY-SA 2.5


答:
A big advantage of moving the processing code out of your SQL is that your SQL becomes much simpler to manage.

A disadvantage is that if you ever want to use those queries in some other program, you now have to make your result-processing processes available to the other program. It could be as simple as copying a library file that contains the necessary classes, but it still means that any changes to the library have to propagated and all clients rebuilt with the new library.

Another option: Why not use a view (or multiple views if you need differently formatted results for different clients) to contain most of the formatting code? That way you can get the "raw" query results, or the nicely formatted one, depending on what you need.

Title: Good idea to move logic out of SQL statements?

Body:
I'll preface this question by saying that I am very new to professional software dev.

I work on a team that takes data in from other groups in my company and turns this data into reports usable by business execs.

In the process of transferring and parsing data we have some SQL statements that do a lot of processing of the data. Nearly every SELECT uses TRIM, SUBSTR, CAST etc extensively to reduce fields to the proper size and format. Additionally there are a lot of special cases that are accounted for by using CASE statements within SELECT's.

The Teradata server software that we use emits remarkably cryptic error messages. As a result we do a lot of guesswork about what data is breaking which SQL statement.

My question is: would it be a good idea to reduce these somewhat complex SQL statements to a less complex form that omits the processing and special case handling, and instead do this work in an external script or program? Does this make any sense?


答:
Adding an external process usually just makes the system harder to debug, but it really depends on the situation.  Use your judgment.  Consider the time required to develop/maintain out-of-band projects.

Are you already using an ETL process?  I don't have experience with Teradata, but separating your steps provides a much clearer view of what's going on. Here's a 2 second overview:

Extract: Pull your data out of the source and place it into stage 1 temporary storage.  Do not change the format of the data.

Transform: Pull from stage 1, and do all of the case / trim / substr / cast / formatting etc... that you require here.  Place it into stage 2 temporary storage.

Load: Pull from stage 2, and put all of the data into the target storage.

This usually provides enough information to successfully manage this type of system.


问:
Refactoring: Two big chunks within a function
I am designing an API which mostly involves refactoring the original code.

So Right now I have a method which has two big chunks which are seperated by an If-else condition, which in my opinion is not exactly the best idea.

The code looks like

```<code>do_something():
     if (isTrue):
         #Large block of statements.
     else:
         #another large block of statements.
</code>```

The reason I have them both under a single function is because both the chunks do the same thing but with some slight variations, which introduces the ugly if-else block.

I wanted to know what would be the best idea to refactor this code in a better way, if it is possible to do that using OOP, that would be even better.

I am not going with the obvious defining two methods way because at the moment both the chunks are doing the same thing.

答:
I've seen code like this in the past, with "the large block of statements" being many hundreds of lines of code.

For starters, any "large block of statements" is, in itself, a code smell.  As some of the other posters have mentioned, you need to break this down into smaller chunks of code.

As for handling the differences, there's no shame in using multiple if-else blocks on the same condition.  Writing something like:

```<code>do_something():
    if(condition):
        do_stuff()
    else:
        do_other():
    # shared code
    if(condition):
        make_thing()
    else:
        make_other()
    # shared code
    if(condition):
        return this_stuff()
    else:
        return that_stuff()
</code>```

If you're lucky, the differences really just come down to a few constants and you can clean up this mess by writing

```<code>do_something():
    if(condition):
        a = 10
        b = -1
        c = 1.5
    else:
        a = 100
        b = +1
        c = 1.9
    # shared code
</code>```

Body:
I've seen code like this in the past, with "the large block of statements" being many hundreds of lines of code.

For starters, any "large block of statements" is, in itself, a code smell.  As some of the other posters have mentioned, you need to break this down into smaller chunks of code.

As for handling the differences, there's no shame in using multiple if-else blocks on the same condition.  Writing something like:

do_something():
    if(condition):
        do_stuff()
    else:
        do_other():
    # shared code
    if(condition):
        make_thing()
    else:
        make_other()
    # shared code
    if(condition):
        return this_stuff()
    else:
        return that_stuff()

If you're lucky, the differences really just come down to a few constants and you can clean up this mess by writing

do_something():
    if(condition):
        a = 10
        b = -1
        c = 1.5
    else:
        a = 100
        b = +1
        c = 1.9
    # shared code


答:
Reference

From The Pragmatic Programmer:

We believe that exceptions should rarely be used as part of a program's normal flow; exceptions should be reserved for unexpected events. Assume that an uncaught exception will terminate your program and ask yourself, "Will this code still run if I remove all the exception handlers?" If the answer is "no," then maybe exceptions are being used in nonexceptional circumstances.

They go on to examine the example of opening a file for reading, and the file doesn't exist - should that raise an exception?

If the file should have been there, then an exception is warranted. [...] On the other hand, if you have no idea whether the file should exist or not, then it doesn't seem exceptional if you can't find it, and an error return is appropriate.

Later, they discuss why they chose this approach:

[A]n exception represents an immediate, nonlocal transfer of control - it's a kind of cascading goto. Programs that use exceptions as part of their normal processing suffer from all the readability and maintainability problems of classic spaghetti code. These programs break encapsulation: routines and their callers are more tightly coupled via exception handling.

Regarding your situation

Your question boils down to "Should validation errors raise exceptions?" The answer is that it depends on where the validation is happening.

If the method in question is within a section of the code where it is assumed that input data has already been validated, invalid input data should raise an exception; if the code is designed such that this method will receive the exact input entered by a user, invalid data is to be expected, and an exception should not be raised.

Title: I've been told that Exceptions should only be used in exceptional cases. How do I know if my case is exceptional?

Body:
My specific case here is that the user can pass in a string into the application, the application parses it and assigns it to structured objects.  Sometimes the user may type in something invalid.  For example, their input may describe a person but they may say their age is "apple".  Correct behavior in that case is roll back the transaction and to tell the user an error occurred and they'll have to try again.  There may be a requirement to report on every error we can find in the input, not just the first.

In this case, I argued we should throw an exception.  He disagreed, saying, "Exceptions should be exceptional:  It's expected that the user may input invalid data, so this isn't an exceptional case"  I didn't really know how to argue that point, because by definition of the word, he seems to be right.

But, it's my understanding that this is why Exceptions were invented in the first place.  It used to be you had to inspect the result to see if an error occurred.  If you failed to check, bad things could happen without you noticing.

Without exceptions every level of the stack needs to check the result of the methods they call and if a programmer forgets to check in one of these levels, the code could accidentally proceed and save invalid data (for example).  Seems more error prone that way.

Anyway, feel free to correct anything I've said here.  My main question is if someone says Exceptions should be exceptional, how do I know if my case is exceptional?


问:
What has been your experience with SQL CLR for complex business logic?
So I thought I had a perfect use-case for a CLR SQL Procedure. I've search the Net for perhaps a similar example where data is retrieved, records added and updated. I have not looked at a SQL CLR procedure for awhile, but since it was released in 2005 (some 6 years ago!) I would have hoped there were plenty of examples!

I'm considering it because I have to look at some data, run it through a bunch of procedural logic, update, and then get it back to the client. My thinking here is to get as close to the DB metal as possible, and use that hardware to make it happen quickly.

Is anybody using SQL CLR? If you have, what has been your experience with it?

p.s. originally posted on stackoverflow and moved here based on a comment.

答:
Firstly, try very very hard not to use it - whilst I implemented both a CLR stored procedure and a streaming vector table function, both had problems, mainly in performance.

My sproc basically bombed out when presented with a million rows of data, whereas a sql procedure that called a scalar function (in CLR - in my case it provided a regex function) worked, and worked far far quicker than the sproc did. The SVTF had some issues with security such that it would only work on a developer edition DB (we like security at our place) so that was dropped. Performance was similarly bad but not as bad as the sproc.

So stick to simple scalar functions but try not to use them much and keep them really simple.


问:
Should I calculate hotness of a post on request or pre-calculate it?
Here is the Reddit's hot algorithm:

```<code>cpdef double _hot(long ups, long downs, double date):
    """The hot formula. Should match the equivalent function in postgres."""
    s = score(ups, downs)
    order = log10(max(abs(s), 1))
    if s > 0:
        sign = 1
    elif s < 0:
        sign = -1
    else:
        sign = 0
    seconds = date - 1134028003
    return round(order + sign * seconds / 45000, 7)
</code>```

My brain says hotness of a post should be calculated on every request because old posts should have a low hotness score.

I implemented this function in MySql but as you might guess, it's slow. Very slow even indexes are there.

And then I think to update the hotness field of the post on every upvote or downvote of the post. Let's assume we have a post just posted now and has 100 upvote and 1 downvote and it's hotness is 78 (example). But it doesn't get any votes for 3 days. After 3 days a new post appears and gets 100 upvotes and 1 downvote and has 78 score. If I'm updating hotness score on votes, the 3 days old post and the new post will be show together. But in theory, the 3 days old post shouldn't even show up in front page.

What is the most viable method to implement for this situation?

答:
My brain says hotness of a post should be calculated on every request because old posts should have a low hotness score.

You're brain is wrong.  The date in the function is the original time of the post.  The function's value is independent of calculation time and remains constant between votes.  Keeping this in mind, you only need to update it when votes are cast.  You just store the number in the database & query on an indexed column.  Performance issues disappear.

This also addresses your second issue - a post with 100 upvotes made today will always be hotter than a post at +100 made yesterday.


答: I agree with the suggestion already made about using a View for this logic.  I would just like to add one more thing about the Case statements.  Be aware that pulling the Case statements out of the SQL might result in a significant performance impact to the system.  Those Case statements might be significantly reducing the amount of data returned.  Running the Case filtering in the database layer through SQL statements is normally much more efficient than pulling all the data back and doing the filtering in an external script or program.  If you are considering this, I highly recommend doing some data analysis and performance testing before moving forward with that solution.</p>


问:
Ensuring conceptual integrity in Python project with multiple programmers
One objection that I have often heard raised against Python that it is difficult to synchronize a team of many programmers on large Python project. Note: that synchronization is possible in such a project does not necessarily entail that it is practical, cheap or easy. There's still n*(n-1) communication channels between programmers, so communication cost grows more or less with square of number of programmers, on average.

One thing I liked in Java are interfaces. Sadly, both PEP 245 and even modified Guido's version on interfaces ( http://www.artima.com/forums/flat.jsp?forum=106&thread=87182 ) have not been implemented. I was thinking that duck-typing style limited interfaces (no types, just method names) might be very useful, emphatically not for sake of pychecker, faster code, or forcing (dumb) programmers to follow (smart) architect's design, but as means of easy synchronization between 2+ programmers.

So, apart from typical but not working very well suggestion of "more documentation" (nobody wants to write it really), what are your means of synchronization high-level design and conceptual integrity on such large, multi-person projects?

(in part I ask because large projects I have participated in never used Python)

I heard objections mentioned above in person: At least 3 times when talking to startups (2 Scala startups, so they have slant towards static typing) and at least once within corp when considering various programming languages for projects. On the web: can't remember this now, I have vague memory of reading it on some OO blogs and forums. Static typing guys (Java, Scala) seem to have had big on this point, even though typically static typing and interfaces are usually meant for other things (speed, IDE autocompletion).

Note I know TDD defense on this but the problem here is that it is defensive since typically it's one person that writes unit tests. Of course, one could envision 1+ programmers sitting down together and writing unit tests before coding as sort of indirect spec + test but have you seen it done? I haven't.  I also feel that unit tests, even written by groups, are not quite (limited) design or spec. They are low level after all. There's a reason (good maybe?) that Java has interfaces in addition to and not instead of JUnit.

答:
I like GlenH7's answer, and I believe there is truth there.

However, my perspective is that the answer to your problems is Code Ownership.

If five large teams are re-using the same model classes, and want to pile on unnecessary crap into them, then the only way out is to say "Team X owns this code, if you want to change it talk to them". Or, "John owns this code, if you want to change it talk to him."

You still need communication, but the nature of it changes. The assumption is that your request for change will be shot down unless there is a very good reason to put it in. Also, this creates a decision making body with final say, rather than co-owned code being modified by a 'design committee' (which frequently leads to either chaos or analysis paralysis).

Consider this also: there is nothing magical about Java interfaces. They give some design hints from the (hopefully smart) architect, but they don't protect against someone who needs a quick hack from going in there and changing your interfaces anyway. The only thing that really protects from that is code control, code ownership, and some degree of personal responsibility.

So if you're facing "interface" madness, designate responsible people for it and allocate code ownership. Make sure these people do their jobs.


问:
Should I return from a function early or use an if statement?
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

答:
Like you, I usually write the first one, but prefer the last one.
If i have a lot of nested checks i usually refactor to the second method.

I don't like how the error handling is moved away from the check.

if not error A
  if not error B
    if not error C
      // do something
    else handle error C
  else handle error B
else handle error A
```

<p>I prefer this:</p>

<pre class="lang-java prettyprint-override"><code>if error A
  handle error A; return
if error B
  handle error B; return
if error C
  handle error C; return

// do something
</code>```

Body:
Like you, I usually write the first one, but prefer the last one.
If i have a lot of nested checks i usually refactor to the second method.

I don't like how the error handling is moved away from the check.

if not error A
  if not error B
    if not error C
      // do something
    else handle error C
  else handle error B
else handle error A

I prefer this:

if error A
  handle error A; return
if error B
  handle error B; return
if error C
  handle error C; return

// do something


问:
Randomly select from list with increased odds
I have a list of entities. Every entity contains a number that holds how many times the entity has been selected. I need to make a function that selects n (say 25%) of the entities, randomly. What I want to do is increase the odds for entities that have been selected the least times. Suppose after 5 runs the times the entities have been selected can be anywhere from 0 to 5. But I don't want to have such a spread. I want the  times the entities are selected more or less to be equal.

How can I write a function that increases the odds for entities that haven't been selected as often as others?

One way I could think of is to make a list that has more occurrences of lesser selected entities, increasing the chance the randomizer selects that entity. Any hints, tips, ideas?

EDIT:
Wow. Closed as not being a real question and reopened again. For not being a real question it did get a lot of answers and comments. Thanks for that. I got exactly what i wanted from them. I got some nice ideas to work out and to test.

答:
If you an want to limit the difference in occurences to a maximum of 1:

Shuffle the list of entities (using a Fisher-Yates shuffle)

Pick your random values according to the order of the shuffled list

Once you reached the end of the shuffled list goto 1

You can also allow higher differences in occurences by adding each entity n-times to the list when you want a maximum difference of n.


答:
First, it's worth pointing out that if your selection function is truly random (or even convincingly pseudorandom), all items will have about the same number of selections over the long run.

I can think of a number of ways to accomplish what you want. Here's one:

Give each item an initial weight of, say, 1.0.

Arrange all the items in a list. Sort the list according to the items' weights.

When you want to choose new item, use a random function to choose a number between 0 and the sum of the weights of all items. Next, add the weights of the items starting from the beginning of the list until you reach the number you just chose. Choose that item.

Finally, you'll need to adjust the weights and ensure that the list stays sorted (either sort it again, or adjust in a way that maintains the sort).

How you adjust the weights will have a big impact on your algorithm, but I'd suggest something like: subtract 1.0 from the chosen item's weight and add 1/(n-1) to the weights of all the other items.

Title: Randomly select from list with increased odds

Body:
I have a list of entities. Every entity contains a number that holds how many times the entity has been selected. I need to make a function that selects n (say 25%) of the entities, randomly. What I want to do is increase the odds for entities that have been selected the least times. Suppose after 5 runs the times the entities have been selected can be anywhere from 0 to 5. But I don't want to have such a spread. I want the  times the entities are selected more or less to be equal.

How can I write a function that increases the odds for entities that haven't been selected as often as others?

One way I could think of is to make a list that has more occurrences of lesser selected entities, increasing the chance the randomizer selects that entity. Any hints, tips, ideas?

EDIT:
Wow. Closed as not being a real question and reopened again. For not being a real question it did get a lot of answers and comments. Thanks for that. I got exactly what i wanted from them. I got some nice ideas to work out and to test.


答:
The times entities are selected will average out to be equal... given time and enough selections. There is indeed a chance that one entity could get lucky and win the first 5 gambles. But that's rare. In general, I'd say that you don't have to worry about it.

But if you want it to be impossible, simply exclude any entity from the lotto which has more than a standard deviation of wins. At low numbers, this would exclude anyone who has won a single gamble.

Note, that is this is for a game, gamers are particularly keen about when the odds have been tampered with. If someone can never win twice in a row, they'll notice it.


答:
I once implemented something like this:

Initially assign every item in your pool the same number of chances.  When making a random choice add up the total number of chances and then go through your list to find which one you got.  (Yes, that's O(n) rather than O(1).  You'll need something fancier if your list is gigantic or not in memory.)

When an item is picked you remove a chance from it.

When you have picked as many items as your list contains go through and add one to every chance.

(I didn't have the last step as I actually wanted the successful picks to go away and never return.)


问:
Is 'using' appropriate in a context where there is nothing to dispose?
In C#, using statement is used to dispose in a deterministic manner the resources without waiting for garbage collector. For example, it may be used to:

Dispose SQL commands or connections,

Close streams, freeing the underlying source like a file,

Free GDI+ elements,

etc.

I noticed that using is used more and more in cases where there is nothing to dispose, but where it's just more convenient for the caller to write a using block rather than two separate commands.

Examples:

MiniProfiler, written by Stack Overflow team, uses using to denote blocks to profile:

```<code>using (profiler.Step("Name goes here"))
{
    this.DoSomethingUseful(i - 1);
}
</code>```

One alternative approach would be to have two blocks:

```<code>var p = profiler.Start("Name goes here");
this.DoSomethingUseful(i - 1);
profiler.Stop(p);
</code>```

Another approach would be to use actions:

```<code>profiler.Step("Name goes here", () => this.DoSomethingUseful(i - 1));
</code>```

ASP.NET MVC also picked using for forms:

```<code><% using (Html.BeginForm())
   { %>
       <label for="firstName">Name:</label>
       <%= Html.TextBox("name")%>
       <input type="submit" value="Save" />
<% } %>
</code>```

Is such usage appropriate? How to justify it, given that there are several drawbacks:

Beginners would be lost, since such usage doesn't correspond to the one which is explained in books and language specification,

The code should be expressive. Here, the expressiveness suffers, since the appropriate usage of using is to show that behind, there is a resource, like a stream, a network connection or a database which should be released without waiting the garbage collector.

答:
The use of using implies the presence of a Dispose() method.  Other programmers will assume that such a method exists on the object.  Consequently, if an object is not disposable, you should not use using on it.

Code clarity is king. Either omit the using, or implement IDisposable on the object.

MiniProfiler appears to be using using as a mechanism to "fence in" the code being profiled.   There is some merit to this; presumably, MiniProfiler is either calling Dispose() to stop a timer, or the timer is stopped when the MiniProfiler object goes out of scope.

More generally, you would invokeusing when some sort of finalization needs to occur automatically.  The documentation for html.BeginForm states that, when the method is used in a using statement,  it renders the closing </form> tag at the end of the using block.

That doesn't necessarily mean it's still not abuse.


答:
Sort By Random Range

You can sort the items by an expression, where a random number is selected between the items current number of views and the max number of views. This ensures that items with a high view count are more likely to be given a random number that is large. While items with a low view count are more likely to be randomized.

Sort the list by the following expression random(item.views,max_viewx+1)

I gave the max_views+1 so that a new list of items with 0 views will still produce a random sort order.

Tested via SQL

I think this is something I could one day use on a blog site. So here is an attempt to verify this approach as a MySQL table.

First create a basic articles table.

```<code>CREATE  TABLE `articles` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `title` VARCHAR(45) NOT NULL ,
  `views` INT NOT NULL DEFAULT 0 ,
  PRIMARY KEY (`id`) );
</code>```

Now insert some articles with different view counters.

```<code>INSERT INTO `articles` (`title`, `views`) VALUES ('Home Page', 20);
INSERT INTO `articles` (`title`, `views`) VALUES ('Portfolio', 10);
INSERT INTO `articles` (`title`, `views`) VALUES ('Contact Us', 5);
INSERT INTO `articles` (`title`, `views`) VALUES ('Product - ABC', 2);
INSERT INTO `articles` (`title`, `views`) VALUES ('Product - SHR', 1);
INSERT INTO `articles` (`title`, `views`) VALUES ('Product - DBS', 0);
INSERT INTO `articles` (`title`, `views`) VALUES ('Product - ZZZ', 100);
</code>```

Now I could sort by the views column to put Product - ZZZ at the bottom, but we want this to feel random.

```<code>SELECT * FROM `articles`
    ORDER BY `views`+(RAND()*(100-`views`+1));
</code>```

That works for me, placing Product - ZZZ at the bottom 100% of the time, but low view items are more likely to be sorted higher in the list.

```<code>SELECT * FROM `articles`
    ORDER BY `views`+(RAND()*(100-`views`+25));
</code>```

By adding +25 to the ORDER BY, then I'm able to raise Product - ZZZ slightly higher in the list and make the rest of the items more random. So you can control the randomizing effect.

Body:
Sort By Random Range

You can sort the items by an expression, where a random number is selected between the items current number of views and the max number of views. This ensures that items with a high view count are more likely to be given a random number that is large. While items with a low view count are more likely to be randomized.

Sort the list by the following expression random(item.views,max_viewx+1)

I gave the max_views+1 so that a new list of items with 0 views will still produce a random sort order.

Tested via SQL

I think this is something I could one day use on a blog site. So here is an attempt to verify this approach as a MySQL table.

First create a basic articles table.

CREATE  TABLE `articles` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `title` VARCHAR(45) NOT NULL ,
  `views` INT NOT NULL DEFAULT 0 ,
  PRIMARY KEY (`id`) );

Now insert some articles with different view counters.

INSERT INTO `articles` (`title`, `views`) VALUES ('Home Page', 20);
INSERT INTO `articles` (`title`, `views`) VALUES ('Portfolio', 10);
INSERT INTO `articles` (`title`, `views`) VALUES ('Contact Us', 5);
INSERT INTO `articles` (`title`, `views`) VALUES ('Product - ABC', 2);
INSERT INTO `articles` (`title`, `views`) VALUES ('Product - SHR', 1);
INSERT INTO `articles` (`title`, `views`) VALUES ('Product - DBS', 0);
INSERT INTO `articles` (`title`, `views`) VALUES ('Product - ZZZ', 100);

Now I could sort by the views column to put Product - ZZZ at the bottom, but we want this to feel random.

SELECT * FROM `articles`
    ORDER BY `views`+(RAND()*(100-`views`+1));

That works for me, placing Product - ZZZ at the bottom 100% of the time, but low view items are more likely to be sorted higher in the list.

SELECT * FROM `articles`
    ORDER BY `views`+(RAND()*(100-`views`+25));

By adding +25 to the ORDER BY, then I'm able to raise Product - ZZZ slightly higher in the list and make the rest of the items more random. So you can control the randomizing effect.


答:
From an OO point of view, there are two patterns that maybe appropriate in this case; Template and Strategy.

The Template pattern allows you to change the steps of your algorithm at runtime.
Strategy pattern allows you to to change the algorithm.

Your pseudo code looks a bit like Python, and implementation of patterns vary depending on the idioms of the language.

Here is an example of Strategy:

```<code>class Context:
    def __init__(self, strategy):
        self.strategy = strategy
    def DoSomething(self):
        self.strategy.DoSomething();

class Strategy:
    def DoSomething(self):
        raise NotImplementedError # You have to override.

class StrategyA(Strategy):
    def DoSomething(self):
        #Large block of statements.
        print "Evaluate StrategyA"

class StrategyB(Strategy):
    def DoSomething(self):
        #another large block of statements.
        print "Evaluate StrategyB"

c = Context(StrategyA())
c.DoSomething();

c = Context(StrategyB())
c.DoSomething();
</code>```

Template pattern:

```<code>class Context:
    def __init__(self, template):
        self.template = template
    def DoSomething(self):
        self.template.Step1(); # represents a difference between the two algorithms
        # common steps in here...
        self.template.Step2(); # difference...
        # another common step here...
        self.template.Step3(); # difference...
        self.template.Step4();

class Template:
    def Step1(self):
        raise NotImplementedError # You have to override.
    def Step2(self):
        raise NotImplementedError # You have to override.
    def Step3(self):
        raise NotImplementedError # You have to override.
    def Step4(self):
        raise NotImplementedError # You have to override.

class TemplateA(Template):
    def Step1(self):
        print "Step1A"
    def Step2(self):
        print "Step2A"
    def Step3(self):
        print "Step3A"
    def Step4(self):
        print "Step4A"

class TemplateB(Template):
    def Step1(self):
        print "Step1B"
    def Step2(self):
        print "Step2B"
    def Step3(self):
        print "Step3B"
    def Step4(self):
        print "Step4B"

c = Context(TemplateA())
c.DoSomething();

c = Context(TemplateB())
c.DoSomething();
</code>```

However, without more context, if is difficult to tell if this is best in this situation. Both patterns maybe overkill for just two steps. It might be better just to break up your method into separate methods.

Title: Refactoring: Two big chunks within a function

Body:
I am designing an API which mostly involves refactoring the original code.

So Right now I have a method which has two big chunks which are seperated by an If-else condition, which in my opinion is not exactly the best idea.

The code looks like

```<code>do_something():
     if (isTrue):
         #Large block of statements.
     else:
         #another large block of statements.
</code>```

The reason I have them both under a single function is because both the chunks do the same thing but with some slight variations, which introduces the ugly if-else block.

I wanted to know what would be the best idea to refactor this code in a better way, if it is possible to do that using OOP, that would be even better.

I am not going with the obvious defining two methods way because at the moment both the chunks are doing the same thing.

Body:
From an OO point of view, there are two patterns that maybe appropriate in this case; Template and Strategy.

The Template pattern allows you to change the steps of your algorithm at runtime.
Strategy pattern allows you to to change the algorithm.

Your pseudo code looks a bit like Python, and implementation of patterns vary depending on the idioms of the language.

Here is an example of Strategy:

class Context:
    def __init__(self, strategy):
        self.strategy = strategy
    def DoSomething(self):
        self.strategy.DoSomething();

class Strategy:
    def DoSomething(self):
        raise NotImplementedError # You have to override.

class StrategyA(Strategy):
    def DoSomething(self):
        #Large block of statements.
        print "Evaluate StrategyA"

class StrategyB(Strategy):
    def DoSomething(self):
        #another large block of statements.
        print "Evaluate StrategyB"

c = Context(StrategyA())
c.DoSomething();

c = Context(StrategyB())
c.DoSomething();

Template pattern:

class Context:
    def __init__(self, template):
        self.template = template
    def DoSomething(self):
        self.template.Step1(); # represents a difference between the two algorithms
        # common steps in here...
        self.template.Step2(); # difference...
        # another common step here...
        self.template.Step3(); # difference...
        self.template.Step4();

class Template:
    def Step1(self):
        raise NotImplementedError # You have to override.
    def Step2(self):
        raise NotImplementedError # You have to override.
    def Step3(self):
        raise NotImplementedError # You have to override.
    def Step4(self):
        raise NotImplementedError # You have to override.

class TemplateA(Template):
    def Step1(self):
        print "Step1A"
    def Step2(self):
        print "Step2A"
    def Step3(self):
        print "Step3A"
    def Step4(self):
        print "Step4A"

class TemplateB(Template):
    def Step1(self):
        print "Step1B"
    def Step2(self):
        print "Step2B"
    def Step3(self):
        print "Step3B"
    def Step4(self):
        print "Step4B"

c = Context(TemplateA())
c.DoSomething();

c = Context(TemplateB())
c.DoSomething();

However, without more context, if is difficult to tell if this is best in this situation. Both patterns maybe overkill for just two steps. It might be better just to break up your method into separate methods.


答:
Definitely the latter.  The former doesn't look bad right now, but when you get more complex code, I can't imagine anyone would think this:

public int SomeFunction(bool cond1, string name, int value, AuthInfo perms)
{
    int retval = SUCCESS;
    if (someCondition)
    {
        if (name != null && name != "")
        {
            if (value != 0)
            {
                if (perms.allow(name)
                {
                    // Do Something
                }
                else
                {
                    reval = PERM_DENY;
                }
            }
            else
            {
                retval = BAD_VALUE;
            }
        }
        else
        {
            retval = BAD_NAME;
        }
    }
    else
    {
        retval = BAD_COND;
    }
    return retval;
}
```

<p>is more readable than</p>

<pre class="lang-java prettyprint-override"><code>public int SomeFunction(bool cond1, string name, int value, AuthInfo perms)
{
    if (!someCondition)
        return BAD_COND;

    if (name == null || name == "")
        return BAD_NAME;

    if (value == 0)
        return BAD_VALUE;

    if (!perms.allow(name))
        return PERM_DENY;

    // Do something
    return SUCCESS;
}
</code>```

I fully admit I never understood the advantage of single exit points.

Title: Should I return from a function early or use an if statement?

Body:
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

Body:
Definitely the latter.  The former doesn't look bad right now, but when you get more complex code, I can't imagine anyone would think this:

public int SomeFunction(bool cond1, string name, int value, AuthInfo perms)
{
    int retval = SUCCESS;
    if (someCondition)
    {
        if (name != null && name != "")
        {
            if (value != 0)
            {
                if (perms.allow(name)
                {
                    // Do Something
                }
                else
                {
                    reval = PERM_DENY;
                }
            }
            else
            {
                retval = BAD_VALUE;
            }
        }
        else
        {
            retval = BAD_NAME;
        }
    }
    else
    {
        retval = BAD_COND;
    }
    return retval;
}

is more readable than

public int SomeFunction(bool cond1, string name, int value, AuthInfo perms)
{
    if (!someCondition)
        return BAD_COND;

    if (name == null || name == "")
        return BAD_NAME;

    if (value == 0)
        return BAD_VALUE;

    if (!perms.allow(name))
        return PERM_DENY;

    // Do something
    return SUCCESS;
}

I fully admit I never understood the advantage of single exit points.


答:
You've got the entries A, B, C, D, and E that have been selected 3, 1, 1, 0, 0 times.

The max of this set is 3.  Subtract the currently selected value from the max + 1 (an entry that has the max values should have some chance of still winning, though a one as that entry will only have one representative in the next raffle).

You now have the association of: A => 1, B => 3, C => 3, D => 4, E => 4.

Build an array based on this, for example: A,B,B,B,C,C,C,D,D,D,D,E,E,E,E and select a random winner.  The entries that have won the fewest times in the past will have an increased chance of winning this time.

Your question can be interpreted as the "selects n of the entries" being with or without replacement.  If it is without replacement, then recompute, removing the winner from the previous round until you select the required number of winners.

Variations:

Instead of using max of the set, one might instead use the sum of the set.

Change the value of N in max + N value to even out the distribution

I would suggest running a number of Monte-carlo simulations on the data set to identify what values work best for your situation.


问:
Why is Today() an example of an impure function?
It seems like, when reading something like this Wikipedia article about "pure functions", they list Today() as an example of an impure function but it seems pretty pure to me. Is it because there is no formal input argument? Why is the actual time of day not treated as the "input to the function" in which case if you gave it the same input, i.e. executed today() twice at the same time, or traveled back in time to execute it again (maybe a hypothetical :) ), the output would be the same time. Today() never gives you a random number. it always gives you the time of day.

The Wikipedia article says "different times it will yield different results" but that's like saying for different x sin(x) will give you different ratios. And sin(x) is their example of a pure function.

答:
First, there is no such thing as a function without argument (or an array without indexes or a map without keys). It is the defining characteristic of a function to map one or more argument values to another value.

Hence, today is either not a function at all, hence no pure function.
Or we may interpret the syntax

```<code>today()
</code>```

a bit so that it means

```<code>today   ()      -- today, applied to the value ()
</code>```

In Haskell, for example, this would be valid:

```<code>data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving Show
today :: () -> Day
today () = ....?
main = print (today())
</code>```

because there is a type () with a single value ().

The question is only, how can today compute the day of the week, if it only has ()?
It is just not possible without reading the system timer, directly or via helper impure functions.

The system timer is an excellent example for global state.

Body:
First, there is no such thing as a function without argument (or an array without indexes or a map without keys). It is the defining characteristic of a function to map one or more argument values to another value.

Hence, today is either not a function at all, hence no pure function.
Or we may interpret the syntax

today()

a bit so that it means

today   ()      -- today, applied to the value ()

In Haskell, for example, this would be valid:

data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun deriving Show
today :: () -> Day
today () = ....?
main = print (today())

because there is a type () with a single value ().

The question is only, how can today compute the day of the week, if it only has ()?
It is just not possible without reading the system timer, directly or via helper impure functions.

The system timer is an excellent example for global state.


答:
Your last statement - that "the appropriate usage of using is to show that behind, there is a resource, like a stream, a network connection or a database which should be released without waiting the garbage collector" is incorrect, and the reason why is given at the documentation for the IDisposable interface: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

The primary use of this interface is to release unmanaged resources.

So, if your class uses any unmanaged resouces, it doesn't matter when you may or may not want GC to happen - it's got nothing whatsoever to do with GC as unmanaged resources aren't GC'ed (https://stackoverflow.com/questions/3607213/what-is-meant-by-managed-vs-unmanaged-resources-in-net).

So the purpose of "using" is not to avoid waiting on GC, it's to force a release of those unmanaged resources now, before the class instance goes out of scope and it's Finalize is called.  This is important for reasons that should be obvious - an unmanaged resource may have dependencies on other unmanaged resources, and if they are disposed of (or finalized) in the wrong order Bad Things may happen.

So if the class being instanced in the using block uses any unmanaged resources, then then answer is yes - it is appropriate.

Note that IDisposable is not prescriptive about it being only for releasing unmanaged resources, however - just that this is it's primary purpose.  It may be the case that the author of the class has some action that they want to enforce happening at a certain time, and implementing IDisposable may be a way of getting that to happen, but whether or not that's an elegant solution is something that can only be answered on a case-by-case basis.

Whichever, the use of "using" implies that the class implements IDisposable, so it doesn't violate code expressiveness; it makes it quite clear what's going on, in fact.

Title: Is 'using' appropriate in a context where there is nothing to dispose?

Body:
In C#, using statement is used to dispose in a deterministic manner the resources without waiting for garbage collector. For example, it may be used to:

Dispose SQL commands or connections,

Close streams, freeing the underlying source like a file,

Free GDI+ elements,

etc.

I noticed that using is used more and more in cases where there is nothing to dispose, but where it's just more convenient for the caller to write a using block rather than two separate commands.

Examples:

MiniProfiler, written by Stack Overflow team, uses using to denote blocks to profile:

```<code>using (profiler.Step("Name goes here"))
{
    this.DoSomethingUseful(i - 1);
}
</code>```

One alternative approach would be to have two blocks:

```<code>var p = profiler.Start("Name goes here");
this.DoSomethingUseful(i - 1);
profiler.Stop(p);
</code>```

Another approach would be to use actions:

```<code>profiler.Step("Name goes here", () => this.DoSomethingUseful(i - 1));
</code>```

ASP.NET MVC also picked using for forms:

```<code><% using (Html.BeginForm())
   { %>
       <label for="firstName">Name:</label>
       <%= Html.TextBox("name")%>
       <input type="submit" value="Save" />
<% } %>
</code>```

Is such usage appropriate? How to justify it, given that there are several drawbacks:

Beginners would be lost, since such usage doesn't correspond to the one which is explained in books and language specification,

The code should be expressive. Here, the expressiveness suffers, since the appropriate usage of using is to show that behind, there is a resource, like a stream, a network connection or a database which should be released without waiting the garbage collector.


答:
using is error and exception safe. It ensures Dispose() will be called irregardless of any mistakes the programmer makes. It does not interfere with the catching or handling of exceptions, but the Dispose() method is executed recursively up the stack when an exception is thrown.

Objects that implement IDispose but have nothing to dispose when they are done. Are at best, future proofing their design. So that you don't have to refactor your source code, when in the future, they then need to dispose of something.


答:
The problem with today() is that it can yield a different result if called two or more times in a function.

Here is a code example, that could introduce a bug.

```<code>function doSomething(when)
{
     if(today() == when)
     {
           // open a resource or create a temp file.....
     }

     // do some other work

     if(today() == when)
     {
           // close the resource or delete temp file.....
     }
}
</code>```

It's possible in the above example. That the second if statement will not execute. Even if the first one did. Leaving a resource in a bad state.

Title: Why is Today() an example of an impure function?

Body:
It seems like, when reading something like this Wikipedia article about "pure functions", they list Today() as an example of an impure function but it seems pretty pure to me. Is it because there is no formal input argument? Why is the actual time of day not treated as the "input to the function" in which case if you gave it the same input, i.e. executed today() twice at the same time, or traveled back in time to execute it again (maybe a hypothetical :) ), the output would be the same time. Today() never gives you a random number. it always gives you the time of day.

The Wikipedia article says "different times it will yield different results" but that's like saying for different x sin(x) will give you different ratios. And sin(x) is their example of a pure function.

Body:
The problem with today() is that it can yield a different result if called two or more times in a function.

Here is a code example, that could introduce a bug.

function doSomething(when)
{
     if(today() == when)
     {
           // open a resource or create a temp file.....
     }

     // do some other work

     if(today() == when)
     {
           // close the resource or delete temp file.....
     }
}

It's possible in the above example. That the second if statement will not execute. Even if the first one did. Leaving a resource in a bad state.


问:
Why can't we write nested shorthand functions in Clojure?
I tried to evaluate a Clojure expression with nested shorthand functions today, and it wouldn't let me.

The expression was:

```<code>(#(+ % (#(+ % (* % %)) %)) 5) ; sorry for the eye bleed
</code>```

The output was:

```<code>IllegalStateException Nested #()s are not allowed  clojure.lang.LispReader$FnReader.invoke (LispReader.java:630)
...and a bunch of other garbage
</code>```

答:
It's completely arbitrary; there's a couple lines in the parser that explicitly disable it. If you edit that line out, you can have nested anonymous functions, and they act exactly like you'd expect.

specifically, lines 634-635 in https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/LispReader.java

```<code>public static class FnReader extends AFn{
    public Object invoke(Object reader, Object lparen) {
        PushbackReader r = (PushbackReader) reader;
        if(ARG_ENV.deref() != null) // <-- line 634
            throw new IllegalStateException("Nested #()s are not allowed");
        // ...
</code>```

Body:
It's completely arbitrary; there's a couple lines in the parser that explicitly disable it. If you edit that line out, you can have nested anonymous functions, and they act exactly like you'd expect.

specifically, lines 634-635 in https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/LispReader.java

public static class FnReader extends AFn{
    public Object invoke(Object reader, Object lparen) {
        PushbackReader r = (PushbackReader) reader;
        if(ARG_ENV.deref() != null) // <-- line 634
            throw new IllegalStateException("Nested #()s are not allowed");
        // ...


问:
Matching up articles with similar ones
I am creating a site where people can write on a niche topic. It is almost like a blog, however the area as I mentioned is a small niche with (hopefully) passionate users.

I want a functionality where once someone posts his article. People with similar experience can be notified, so that they can read about. Now my question is - how to determine similar articles? I know that tagging is a way - just like here in stackexchange and I will be implementing it. But suppose people do not tag, or tag incorrectly, the whole user experience will be hard to indulge in.

Does anyone have any pointers on how to match up articles other than the tagging method?

答:
I've got a few ideas:

A) You could pre-define a selection of categories that each poster is required to select, with either one category or multiple categories per post. This list of categories would have to be rather comprehensive, but could be edited over time.

B) You could implement a system along with poster tagging to allow users to suggest tags that should be added. As tags are suggested, the poster would be notified, and could easily approve or deny tags as necessary.

C) A hybrid approach: implement a tagging system, but allow users to subscribe to a collection of tags, allowing each user to customize categories that may require an article to have multiple tags in order to qualify.

I don't think you should worry too much about users not tagging articles. There is an incentive for them to tag correctly if they know that the tagging system is what attracts readers (and therefore feedback and future fame).

Title: Matching up articles with similar ones


问:
What’s the opposite of abstraction?
As I understand it, abstraction is the term we use for when more meaning is created out of something simpler without altering it. It is derived from the latin verb abstrahere (to ‘draw away’). For instance, text is just one abstraction of binary data—as are bitmaps. So, in computers, text and bitmaps exist on top of (are implemented in terms of) binary data.

My question is: what is the opposite term? If I want to know the possible more basic things that bitmaps could be implemented in terms of other than binary data—things like tiles for a mosaic or fabric patches for a patchwork quilt—what am I asking for? Is there a word for that?

Abstraction has connotations of generalization and the opposite process of that is specialization. IDK whether that helps.

答: Abstraction is the process of removing specifics to generalize something. If abstraction is removal of specifics, then maybe the opposite of abstraction is specification.</p>

Title: What’s the opposite of abstraction?


答: "Distraction" -- as in what happens when a piece of code cannot be understood without being aware of many tangential details of what actually happens when it is run. </p>

Title: What’s the opposite of abstraction?

Body:
As I understand it, abstraction is the term we use for when more meaning is created out of something simpler without altering it. It is derived from the latin verb abstrahere (to ‘draw away’). For instance, text is just one abstraction of binary data—as are bitmaps. So, in computers, text and bitmaps exist on top of (are implemented in terms of) binary data.

My question is: what is the opposite term? If I want to know the possible more basic things that bitmaps could be implemented in terms of other than binary data—things like tiles for a mosaic or fabric patches for a patchwork quilt—what am I asking for? Is there a word for that?

Abstraction has connotations of generalization and the opposite process of that is specialization. IDK whether that helps.


答:
Use an If

In Don Knuth's book about GOTO's I read him give a reason for always having the most likely condition come first in an if statement. Under the assumption that this is still a reasonable idea (and not one out of pure consideration for the speed of the era). I'd say early returns aren't good programming practice, especially considering the fact that they're more often than not used for error handling, unless your code is more likely to fail than not fail :-)

If you follow the above advice, you'd need to put that return at the bottom of the function, and then you might as well not even call it a return there, just set the error code and return it two lines hence. Thereby achieving the 1 entry 1 exit ideal.

Delphi Specific...

I'm of the mind that this is a good programming practice for Delphi programmers, although I don't have any proof.  Pre-D2009, we don't have an atomic way to return a value, we have exit; and result := foo; or we could just throw exceptions.

If you had to substitute

if (true) {
 return foo;
}
```

<p>for</p>

<pre class="lang-delphi prettyprint-override"><code>if true then
begin
  result := foo;
  exit;
end;
</code>```

you might just get sick of seeing that at the top of every one of your functions and prefer

if false then
begin
  result := bar;

   ...
end
else
   result := foo;
```

and just avoid exit altogether.

Body:
Use an If

In Don Knuth's book about GOTO's I read him give a reason for always having the most likely condition come first in an if statement. Under the assumption that this is still a reasonable idea (and not one out of pure consideration for the speed of the era). I'd say early returns aren't good programming practice, especially considering the fact that they're more often than not used for error handling, unless your code is more likely to fail than not fail :-)

If you follow the above advice, you'd need to put that return at the bottom of the function, and then you might as well not even call it a return there, just set the error code and return it two lines hence. Thereby achieving the 1 entry 1 exit ideal.

Delphi Specific...

I'm of the mind that this is a good programming practice for Delphi programmers, although I don't have any proof.  Pre-D2009, we don't have an atomic way to return a value, we have exit; and result := foo; or we could just throw exceptions.

If you had to substitute

if (true) {
 return foo;
}

for

if true then
begin
  result := foo;
  exit;
end;

you might just get sick of seeing that at the top of every one of your functions and prefer

if false then
begin
  result := bar;

   ...
end
else
   result := foo;

and just avoid exit altogether.


问:
How to code in a more functional style in Java?
I code Java for at least 5 years now and I really appreciate how the language works. When looking at new JVM languages (e.g. Scala, Clojure) there is a trend to more functional ways to code and this way has some major advantages.

Anyway, are there patterns to achieve a more functional style even when using Java or other pure OOP? And does this make sense in Java?

答:
Many of the Gang of Four design patterns are considered to be implementing functional concepts in an object oriented language.

Functional design patterns is a useful read.  Also the series "Functional Thinking".  Both from IBM.

A presentation (I haven't watched this to verify) on Functional Design Patterns is summarized as

Aino Vonge Corry reviews a number of well known design patterns showing that their implementation is simpler in functional languages because such languages have pattern-based constructs.

Within Java, closures can be implemented as local classes within a method and make for the ability to expand much more into the functional programing realm.  Java 8 extends this functionality with lambdas.

So, to answer your question - many of the design patterns are implementing functional concepts already.  And they do make sense in Java.

If all else fails, one can always invoke Greenspun's tenth rule to get whatever functional pattern you are after.


答:
Functional programming has two primary qualities that define it - emphasis on immutable data and first-class functions. Both are - with some effort and within reason - achievable in Java.

You can certainly have immutable objects. Have the object state explicitly set through the constructor, do not expose setters and apply the final keyword to the fields. Whenever you would have a method modify the object's internal state, have it return a new instance with the updated state instead. An approach like this was presented in Real-World Functional Programming, a book containing examples of functional code in F# and corresponding code in C#. While C# is better suited for functional programming than Java, a similar approach could still be applied to Java.

When it comes to first-class functions, things get a bit more tricky. At the moment Java has a rather clumsy and verbose mechanism of emulating functions using anonymous nested classes, with a limited support for closures. While it's enough to write at least some pieces of code in a functional style, it would be a lackluster experience compared to using a proper functional language. There are Java libraries available, most notably guava, that introduce some of the functional programming concepts into Java, like immutable collections and some functional idioms. That would probably make the experience less gruesome - yet even the official documentation for guava states that functional idioms should only be used sparingly, as they often lead to code that is more verbose, less clear and less efficient than the corresponding imperative version.

The situation for Java is reportedly going to get better with the release of SE 8, set to include proper closures and lambda expressions, deferred from SE 7. Meanwhile you can try one of JVM's several functional languages and interop with Java when needed.

Title: How to code in a more functional style in Java?

Body:
I code Java for at least 5 years now and I really appreciate how the language works. When looking at new JVM languages (e.g. Scala, Clojure) there is a trend to more functional ways to code and this way has some major advantages.

Anyway, are there patterns to achieve a more functional style even when using Java or other pure OOP? And does this make sense in Java?


问:
terms for the html/css/javascript model?
Are there any words for the design model implemented by HTML + CSS + JavaScript, either for that specific set of technologies or any abstract pattern that they follow?</p>

答:
It's hard to say. I think it depends on the context in which the technologies are applied, e.g. They could be used in a MVC pattern.

Really, they are separate technologies with different purposes. Together they provide structure, function and aesthetics to data across the web.


答:
One term which applies is Separation of Concerns -- the idea that parts of a program serving different purposes should be separated into pieces which can be designed, tested, and debugged separately, possibly by different people.

In an idealized web page, the HTML deals only with the semantic structure of the content of the page, the CSS deals only with the appearance of the page, and the JavaScript deals only with the behavior of the page. These three things can be in different files authored by different teams with different skill sets, and each might be reused independently of the others.

Of course, in the real world, this ideal is rarely met -- we adjust the semantic structure of our web page to make it easier to get the behavior or appearance we want, use JavaScript to deliver content to a page or adjust its appearance, and sneak CSS into the page itself.  Knowing the ideal, however, can help us do a better job of design even when we break the rules.

Title: terms for the html/css/javascript model?

Body: Are there any words for the design model implemented by HTML + CSS + JavaScript, either for that specific set of technologies or any abstract pattern that they follow?</p>


问:
Scalability: How does splitting a database table work on different replicated SQL Servers?
I would like to know more about the general concepts behind dividing data of a database into different servers. For example, suppose I have a SQL Server database which has a massive table. Assume one single server cannot handle the amount of data in this table. I would like to break that table down and split its contents among different servers with an identical database (replicated).

Now, suppose I have a single SQL (ADO) connection to any one of these servers, and choose to select records from this particular table. Since the data is in separate databases on separate servers, I need to gather the records from all the various servers and combine them into one.

I'm sure there's standard ways of accommodating for this, and I'm willing to go another route than a direct SQL Server connection (I plan to wrap it in my own HTTP Server API anyway) but I'm still going to use SQL Server as the actual engine. What is the most standard practice and where can I learn more about it?

答:
I think this covers your option(s): https://stackoverflow.com/questions/7926773/how-to-implement-distributed-database-in-sql-server-2008-r2

I also think this is what Cassandra was made for, but that doesn't help much in terms of SQL.


问:
Using ref instead of out. Would that be considered a bug?
Given that out and ref parameters have slight different connotations would writing code like below be considered a bug (even though it doesn't cause an issue at present), or just a lack of understanding on ref and out parameters?

```<code>public void MyMethod()
{
    int myInt = 0;
    MyMethodWithRef(ref myInt);
}

public void MyMethodWithRef(ref myInt)
{
    // not used before being assigned a value.  Does an out parameter make more sense then
    myInt = 5;
}
</code>```

I understand that this is the incorrect usage of ref but if you saw that in code constantly or even once would you consider it a bug and hence fix it as well as inform the original coder or just do it as part of general refactoring practices?

答: Yes, an out makes more sense in that case. It will be more readable as to intent.</p>


答:
From the C# documentation.

An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed.

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time.

I think that explains it well.

If you need the method to be passed a value, then use ref. If you need the method to just output a value, then use out.  You shouldn't use out if you expect the parameter of the method to contain a value already.

Your example is not a bug, because the compiler imposes this restriction. A ref can output a result. That is not it's requirement. The requirement is that it has been initialized.

It would be a bug if you expected out to already contain a value.

Title: Using ref instead of out. Would that be considered a bug?

Body:
Given that out and ref parameters have slight different connotations would writing code like below be considered a bug (even though it doesn't cause an issue at present), or just a lack of understanding on ref and out parameters?

```<code>public void MyMethod()
{
    int myInt = 0;
    MyMethodWithRef(ref myInt);
}

public void MyMethodWithRef(ref myInt)
{
    // not used before being assigned a value.  Does an out parameter make more sense then
    myInt = 5;
}
</code>```

I understand that this is the incorrect usage of ref but if you saw that in code constantly or even once would you consider it a bug and hence fix it as well as inform the original coder or just do it as part of general refactoring practices?


答:
It depends.

Early return if there is some obvious dead end condition to check for right away that would make running the rest of the function pointless.*

Set Retval + single return if the function is more complex and could have multiple exit points otherwise (readability issue).

*This can often indicate a design problem. If you find that a lot of your methods need to check some external/paramater state or such before running the rest of the code, that's probably something that should be handled by the caller.


答: In your example, I would change your return type from void to int, declare myInt local to the method, then return it at the end.


答:
It's not a bug in that the compiler won't flag it and given the existing code base, it will not cause a difference in behavior.

It is an issue that would be brought up in a code review or interview -- it is imprecise, it makes the next programmer ask "why", which if not a mortal sin is at least a venial sin. Is it left over from a copy/paste code reuse, a half implemented feature, part of an incomplete bug fix -- which way, changing from out to ref or vice-a-versa, is it necessary and I'm just not seeing it, is it a terrible mistake by someone that didn't know better and am I not seeing that....

Although I generally approve of extra restrictions, I'm not convinced that in practice this is a useful syntax -- that said, the language does make the distinction, and there's a cost to not following conventions.  Not in terms of performance or scale, but in readability and maintainability.


问:
Affero GPL with PHP application and DB keys in localSettings.php
I want to licence a non-trivial PHP application I have been working on under Affero GPL v3 (because I want every admin, who will use it, also release the source code).

However, something troubles me. I have a file localSettings.php, where the admin is supposed to write keys and some more information for MySQL database and some other secret info in the form

```<code>$dbPassword="mypassword";
</code>```

and so on.

BUT. Under the AGPL, if he changes this, isn't he obliged to release the changed source code together with the secret credentials? (Because the file localSettings.php is, too, licensed under AGPL.)

答: As the author (more strictly speaking, the copyright holder), you're entitled to license anything any way you want.  Just declare in your license that the localSettings.php is licensed differently, and not subject to the Aferro GPL.  Stuff like this is done all the time (e.g., the GNU Classpath exception) when then authors decide they want to allow exceptions to the license restrictions for whatever reason they want.  Heck, you could offer an exception for any file dated on a Thursday, because you were born on a Thursday.


问:
throwing runtime exception in Java application
I am working as a contractor designing enterprise Java application for my client in the role of  a technical lead. The application will be used by end users and there will be a support team who will support the application when we leave.

The other technical leads with whom I am working are under the impression that exception handling will make the code dirty. The system should throw checked exceptions only from the Service tier and the rest of the code should throw runtime exceptions from all other tiers so that there is no need to handle the unchecked exceptions.

What is a need to ever throw a unchecked exception in a business application?

From my experience in the past about runtime exceptions:

1) Unchecked exceptions make the code unpredictable because they do not show up even in the Javadoc.

2) Throwing Unchecked exceptions in a business application is non-sense because when you throw it and it goes straight on Users face, how do you explain it to the user? I have seen enough of web application which show 500 -Internal Error. Contact Administrator which means nothing for a end user or to the support team managing the application.

3) Throwing runtime exceptions forces the users of the class throwing the exception to walk through the source code to debug and see why the exception is thrown. This can only be avoided if the Javadoc of the runtime exception happens to be excellently documented which I find is never a case.

答:
My view is that what type of exception is thrown is dependant on what your code is doing.

I throw checked exceptions when I expect they can happen quite often (users entering dodgy data for example) and I expect the calling code to handle the situation.

I throw unchecked/runtime exceptions (not as often as checked) when I have a rare situation which I do not expect the calling code to handle. An example might be some sort of weird memory related error which I never expect to occur. Unchecked are the sorts of errors that you expect to bring down the application.

No exception should appear in front of a user without some level of support. Even if it's just a "please cut and paste this error dump to an email". Nothing is more annoying to a user than being told there is an error, but being given no details or action they can take to initiate it being fixed.

My guess is that the philosophy you mention comes from one of two sources:

Lazy programmers trying to avoid doing work.

Or developers who have had to support code which went the other way. i.e. over-error-handling. The sort of code that contains large amounts of exception handling, much of which does nothing, or even worse, is used for flow control and other incorrect purposes.


问:
What is a 'Null Terminated String' ?
I have just started reading C++, and I came across a term "Null Terminated String", I read about it but couldn't understand what it actually stands for.

I also want to know what is the difference between a c-string(also referred as "Null terminated String") and a c++ string.

答:
There are some excellent answers in this thread, but I'd like to add one meant for a person who learned computer programming starting from a strongly-typed language like Java or C#, and never programmed in a weakly-typed language like C or C++.

(Note that I'm talking about strong vs. weak typing, not dynamic vs. static typing. The exact definition of weak typing is a fascinating discussion on its own, but outside of the scope of this answer :)

To understand null-terminated strings we need to start from how the data is stored in weakly-typed systems. In these systems the entire memory is just one big sequence of bytes and the program has access to any of these bytes at any time. It is up to the program to interpret the bytes correctly. For instance, when the program needs to read an 32-bit integer at address A1, it reads 4 bytes starting at address A1 and interprets them as a single 32-bit integer. It knows that 32-bit integer is 4 bytes of size, so it doesn't need to have any marker for where is the integer supposed to end.

This is not true about text strings, which in most languages can be of arbitrary size, and are represented by a single byte per character (or 2 bytes for UNICODE strings). Thus knowing the starting address of a string does not mean the program knows where the string ends. Keep in mind - in weakly-typed languages there is nothing stopping the program from reading the memory beyond the end of the string and keep interpreting the bytes that represent the data stored behind the string as further characters.

So in order to read a text string at address A2 the program needs a way of knowing how long the string is, so that it knows how many bytes it should read. Some languages will deal with it by storing the size of the text string in the first byte (or 2 or even 4 bytes). A string "foo" might be 4 bytes long and look like this:

3 102 111 111

where 3 is the length of the string and 102 and 111 are ASCII codes for the characters 'f' and 'o'. This is pretty simple, but limits the maximum length of any string, in this case to 255 characters (since 255 is maximum integer value that can be stored in a single byte we used to keep the length of the string).

Another way of dealing with this problem is marking the end of the string, and this is exactly what a null-terminated string does. It uses a NULL character represented by ASCII value of 0 (zero). So the same string "foo" might look like this:

102 111 111 0

Note that in this case there is no limit for the length of a string that can be represented in this format and the overhead of the representation is always exactly one byte (the finial zero). Obviously text strings containing the NULL character cannot be represented as null-terminated strings at all.

Title: What is a 'Null Terminated String' ?


答:
Maybe you should do your own indexing of the articles and add metadata to your articles in order to facilitate search and grouping of categories.

I implemented such a system together with some colleagues, we used Lucene.net to create a green office environment. This would be useful to index your articles, you could create more searches based on the documents data. There are many indexing systems which create meta data and tags widely available on the internet. I found this one  link please try this one.

Title: Matching up articles with similar ones

Body:
I am creating a site where people can write on a niche topic. It is almost like a blog, however the area as I mentioned is a small niche with (hopefully) passionate users.

I want a functionality where once someone posts his article. People with similar experience can be notified, so that they can read about. Now my question is - how to determine similar articles? I know that tagging is a way - just like here in stackexchange and I will be implementing it. But suppose people do not tag, or tag incorrectly, the whole user experience will be hard to indulge in.

Does anyone have any pointers on how to match up articles other than the tagging method?


答:
If you do not want unchecked runtime exceptions, then why are you using java? There is the possibility of runtime exceptions almost everywhere - notably NullPointerException, ArithmeticException, ArrayIndexOutOfBounds exceptions, etc.

And when you once read the log files of some J2EE system, like, for instance, a SAP NetWeaver installation, you'll see that such exceptions happen literally all the time.

Title: throwing runtime exception in Java application

Body:
I am working as a contractor designing enterprise Java application for my client in the role of  a technical lead. The application will be used by end users and there will be a support team who will support the application when we leave.

The other technical leads with whom I am working are under the impression that exception handling will make the code dirty. The system should throw checked exceptions only from the Service tier and the rest of the code should throw runtime exceptions from all other tiers so that there is no need to handle the unchecked exceptions.

What is a need to ever throw a unchecked exception in a business application?

From my experience in the past about runtime exceptions:

1) Unchecked exceptions make the code unpredictable because they do not show up even in the Javadoc.

2) Throwing Unchecked exceptions in a business application is non-sense because when you throw it and it goes straight on Users face, how do you explain it to the user? I have seen enough of web application which show 500 -Internal Error. Contact Administrator which means nothing for a end user or to the support team managing the application.

3) Throwing runtime exceptions forces the users of the class throwing the exception to walk through the source code to debug and see why the exception is thrown. This can only be avoided if the Javadoc of the runtime exception happens to be excellently documented which I find is never a case.


答:
Checked exceptions are a failed expriment in language design. They force you to have extremely leaky abstractions and dirty code. They should be avoided as much as possible.

As for your points:

1) Checked exceptions make the code dirty, and no less unpredictable because they show up everywhere.

2) How is a checked exception being shown to the user any better? The only real  difference between checked and unchecked exceptions is technical and affects only the source code.

3) Ever heard of stack traces? They tell you exactly where the exception was thrown, no matter whether it's checked or unchecked. Actually, checked exceptions tend to be worse for debugging because they're often wrapped which leads to longer and uglier stack traces, or even lost atogether because the wrapping was done wrong.

There are two kinds of exceptions: those that occur "normally" and are typically handled very close to where they occur, and those that are reallly exceptional and can be handled generically in a very high layer (just abort the current action and log it / show an error).

Checked exceptions were an attempt to put this distinction into the language syntax at the point the exceptions are defined. The problems with this are

The distinction is really up to the caller, not the code that throws the exception

It's completely orthogonal to the semantic meaning of an exception, but tying it to the class hierarchy forces you to mix the two

The whole point of exceptions is that you can decide at what level to catch them without risking to lose an error silently or having to pollute the code at intermediate levels or ; checked exceptions lose that second advantage.


答: Java 8 will introduce Lambdas which will be a gentle (or not so gentle for some) start for developers to get into functional programming with Java.  Technically Java already has some functional programming capabilities, but they're very clumsy (anon inner classes).</p>


问:
Is Groovy going away?
I am sure this question has been asked many times. However, I like to ask it again with the intention of what is the future of these languages.

I was first introduced to Groovy and really liked it. I felt the syntax was simpler and it was much closer to Java and I was able to quickly learn Grails.

Then there was Scala, and the web frame work Lift. I am still learning Scala and I find the syntax very difficult at times.

However, I still wonder what is the future of Groovy. When the author of Groovy says he would have never created groovy if he knew about Scala, then it makes me wonder if there is a future at all. Of course Groovy has came a long way and Grails is used today by many large companies.

If one was to look at Grails vs Lift today, then Grails would be clear winner. More companies are using it.  But given everything I have said so far, I am interested to know if one should invest in Groovy? Is Groovy going away and Scala the better choice? If the CEO of BMW says he drives a Mercedes then one would wonder why shouldn't we all drive Mercedes too, right?

(I understand if this question is really broad and might be closed. I hope to make it an open Wiki for others though.)

答:
The performance of Groovy 2.0 puts Groovy now into a league very close to Java, see http://java.dzone.com/articles/groovy-20-performance-compared The benchmark in this article is very very rough, but I'm working now on a new benchmark for Groovy 2.1 based on the one by Robert Hundt (https://days2011.scala-lang.org/sites/days2011/files/ws3-1-Hundt.pdf) made to compare performance of Google Go with other languages. I need 2-3 weeks till I'm done with writing the article, but the measurements look very good so far. Groovy2.1 with @CompileStatic and JDK7 has about the same performance as Java with JDK6 (!). </p>

<p>I think Groovy will compete more with Kotlin and maybe Ceylon rather than with Scala. Scala is more an academic research language (albeit a very interesting one) and not that much a language to get work done as Groovy and Kotlin. If you are simply missing mixins, extension methods, true closures and things in Java it is a big step you have to make for just getting this. The syntax of Groovy is very close to Java which think is a real selling point compared to Kotlin. </p>

Title: Is Groovy going away?

Body:
The performance of Groovy 2.0 puts Groovy now into a league very close to Java, see http://java.dzone.com/articles/groovy-20-performance-compared The benchmark in this article is very very rough, but I'm working now on a new benchmark for Groovy 2.1 based on the one by Robert Hundt (https://days2011.scala-lang.org/sites/days2011/files/ws3-1-Hundt.pdf) made to compare performance of Google Go with other languages. I need 2-3 weeks till I'm done with writing the article, but the measurements look very good so far. Groovy2.1 with @CompileStatic and JDK7 has about the same performance as Java with JDK6 (!).

I think Groovy will compete more with Kotlin and maybe Ceylon rather than with Scala. Scala is more an academic research language (albeit a very interesting one) and not that much a language to get work done as Groovy and Kotlin. If you are simply missing mixins, extension methods, true closures and things in Java it is a big step you have to make for just getting this. The syntax of Groovy is very close to Java which think is a real selling point compared to Kotlin.