答:
In addition to Caleb's answer

1) Will be well received, and was probably obvious as such.
2) Will possibly not be very well received.  Regardless of how well it is received it will be very difficult to enforce. In addition, the code you receive may be of dubious quality.  Do you really wish to invest the time reviewing garbage code that may not (okay, it won't) fit into your standards and deal with all of the associated integration headache?

As Caleb suggests, give it away and ask them to contribute back in return.  You can always offer up some sort fixed scope royalty payment if the code they offer up is useful to you.  This is a case where rewarding the desired behavior will have a greater likelihood of occurrence instead of attempting to force that behavior through questionable means.


问:
ISC license advice
Is the ISC license suitable as a MIT or Simplified BSD license replacement?

What are the pros and cons of ISC compared to MIT or BSD?

答:
"It's okay."  Removing the now redundant language due to the effects of the Berne convention is good.

FSF has this to say:

... However, to help make sure this language cannot cause any trouble in the future, we encourage developers to choose a different license for their own works.

Which basically means that the terminology is just vague enough that people might shy away from using your software.  The problem is that the license doesn't explicitly grant the right to distribute modified versions of the software.

If you decide to use this license, you'll need to expressly indicate your intent on whether users are allowed to distribute the modified version of the code.  Even then, people will still shy away as that intent is not explicitly spelled out in the license.

Honestly, I'd recommend a different license.  FSF recommends FreeBSD or Expat (aka MIT) over OpenBSD / ISC. This is the Wikipedia article comparing Open Source licenses.

In general, stick with the bigger, better known licenses.  Why, you might ask?  The less work people have to invest in order to understand your license then the more likely they are to consider using your software.  If you use an obscure license, they'll simply move on to the next project or roll their own so they don't have to worry about potential legal issues.

ContentLicense: CC BY-SA 3.0

Title: ISC license advice


问:
Explanation on how "Tell, Don't Ask" is considered good OO
This blogpost was posted on Hacker News with several upvotes. Coming from C++, most of these examples seem to go against what I've been taught.

Such as example #2:

Bad:

```<code>def check_for_overheating(system_monitor)
  if system_monitor.temperature > 100
    system_monitor.sound_alarms
  end
end
</code>```

versus good:

```<code>system_monitor.check_for_overheating

class SystemMonitor
  def check_for_overheating
    if temperature > 100
      sound_alarms
    end
  end
end
</code>```

The advice in C++ is that you should prefer free functions instead of member functions as they increase encapsulation. Both of these are identical semantically, so why prefer the choice that has access to more state?

Example 4:

Bad:

```<code>def street_name(user)
  if user.address
    user.address.street_name
  else
    'No street name on file'
  end
end
</code>```

versus good:

```<code>def street_name(user)
  user.address.street_name
end

class User
  def address
    @address || NullAddress.new
  end
end

class NullAddress
  def street_name
    'No street name on file'
  end
end
</code>```

Why is it the responsibility of User to format an unrelated error string? What if I want to do something besides print 'No street name on file' if it has no street? What if the street is named the same thing?

Could someone enlighten me on the "Tell, Don't Ask" advantages and rationale? I am not looking for which is better, but instead trying to understand the author's viewpoint.

答:
Asking the object about its state, and then calling methods on that object based on decisions made outside of the object, means that the object is now a leaky abstraction; some of its behavior is located outside of the object, and internal state is exposed (perhaps unnecessarily) to the outside world.

You should endeavor to tell objects what you want them to do; do not
  ask them questions about their state, make a decision, and then tell
  them what to do.

The problem is that, as the caller, you should not be making decisions
  based on the state of the called object that result in you then
  changing the state of the object. The logic you are implementing is
  probably the called object’s responsibility, not yours. For you to
  make decisions outside the object violates its encapsulation.

Sure, you may say, that’s obvious. I’d never write code like that.
  Still, it’s very easy to get lulled into examining some referenced
  object and then calling different methods based on the results. But
  that may not be the best way to go about doing it. Tell the object
  what you want. Let it figure out how to do it. Think declaratively
  instead of procedurally!

It is easier to stay out of this trap if you start by designing
  classes based on their responsibilities; you can then progress
  naturally to specifying commands that the class may execute, as
  opposed to queries that inform you as to the state of the object.

http://pragprog.com/articles/tell-dont-ask


问:
Does it still make sense to think about effective code on micro scale in C++?
Early in my programming career I was in love with pointer twiddling, lean code, doing everything with as little layers of abstraction as possible and so on. The code was very C like I would say, close to metal and clever.

Time has passed, I have a lot more experience, and I'm noticing my attitude towards the code has changed.

And with changed, I mean, I don't want to bother about everyday stuff anymore, unless it's super easy to do.

If there is a string concatenation, I will never choose raw pointers deliberately. If I need to concatenate stuff, I might add a quick guess reserve for an STL container, but I don't want to bother with preallocated buffers, C like APIs, caches, avoiding hitting the disk, or trashing. I know realloc might happen from time to time, including all the heap locks, extra copying and so on, but I don't even bother anymore.

Maybe, it is because I have spent some time early in my career where I thought of a clean and beautiful schemes with worker threads that process large amount of trivial data, only to find out later that the whole unoptimized realloc+copy+realloc+copy+realloc+copy+5 layers of wrappers doesn't even register in profiler.

Maybe it's because I've seen how compilers sometimes do magic.

However, such trivial things do add up. When all your code base uses higher order constructs, it has chances that there will be some realloc all over the place, or cold disk hits, that can cause a general perception of a slow application.

Sort of like WTL vs MFC. Or how you instantly know that the application is written in Java when you launch it.

But is it really? Is there any comparisons of software that's using only very lean and smart code vs software that uses generic containers all over the place?

Would you even feel a difference if the string allocation throughout the program would be using prereserves and smart moves vs lazily calling string.append in every place where there is a need for such functionality?

Do you try to implement mitigation solutions for such simple, well known things that are cheap to execute anyway?

Can software turn into bloatware just because extra caution is not applied to every line of code?

答:
Compilers of advanced languages are like credit cards - they are really handy, and they make it so easy to buy great things you don't really need, but if you can keep that whole tendency under control, they are the best thing.
The problem is if, like most of us, you lose self-control and spend more than you should.

If you only do little academic-style programs, it's never going to be much of an issue, but here's an example where a realistically complex program was done in C++ using seemingly sensible collection classes and design approach.
In that program, there were six(6) performance enhancements, resulting in (pay attention) a speedup factor of seven hundred thirty (730) times.
One of those six enhancements was the kind of thing an optimizing compiler could have produced.
The rest were simply design changes, irrespective of C++ vs. C.

So if you simply think "Compiler optimization is getting so good that I can just run wild", that's like assuming if you have a really good credit card with low interest and great on-line technology you can't outspend yourself.
You sure can, and probably will, and the technology won't help.

In the credit-card world I can't offer you a magic bullet, but in the software world I can.
I use a low-tech manual profiling technique that actually engages your brain and finds things that ordinary profilers do not find.
It is explained here.


答:
In addition to the other good answers about "tell, don't ask", some commentary on your specific examples that might help:

The advice in C++ is that you should prefer free functions instead of member functions as they increase encapsulation. Both of these are identical semantically, so why prefer the choice that has access to more state?

That choice does not have access to more state. They both use the same amount of state to do their jobs, but the 'bad' example requires the class state to be public in order to do its work. Further, the behavior of that class in the 'bad' example is spread out to the free function, making it harder to find and more difficult to refactor.

Why is it the responsibility of User to format an unrelated error string? What if I want to do something besides print 'No street name on file' if it has no street? What if the street is named the same thing?

Why is it the responsibility of 'street_name' to do both 'get street name' and 'provide error message'? At least in the 'good' version, each piece has one responsibility. Still, it's not a great example.

Title: Explanation on how "Tell, Don't Ask" is considered good OO

Body:
This blogpost was posted on Hacker News with several upvotes. Coming from C++, most of these examples seem to go against what I've been taught.

Such as example #2:

Bad:

```<code>def check_for_overheating(system_monitor)
  if system_monitor.temperature > 100
    system_monitor.sound_alarms
  end
end
</code>```

versus good:

```<code>system_monitor.check_for_overheating

class SystemMonitor
  def check_for_overheating
    if temperature > 100
      sound_alarms
    end
  end
end
</code>```

The advice in C++ is that you should prefer free functions instead of member functions as they increase encapsulation. Both of these are identical semantically, so why prefer the choice that has access to more state?

Example 4:

Bad:

```<code>def street_name(user)
  if user.address
    user.address.street_name
  else
    'No street name on file'
  end
end
</code>```

versus good:

```<code>def street_name(user)
  user.address.street_name
end

class User
  def address
    @address || NullAddress.new
  end
end

class NullAddress
  def street_name
    'No street name on file'
  end
end
</code>```

Why is it the responsibility of User to format an unrelated error string? What if I want to do something besides print 'No street name on file' if it has no street? What if the street is named the same thing?

Could someone enlighten me on the "Tell, Don't Ask" advantages and rationale? I am not looking for which is better, but instead trying to understand the author's viewpoint.


答:
Generally, the piece suggests that you should not expose member state for others to reason about, if you could reason about it yourself.

However, what's not clearly stated is that this law falls into very obvious limits when the reasoning is way over the responsibility of a specific class. For example, every class whose job is to hold some value or provide some value- especially generic ones, or where the class provides behaviour that must be extended.

For example, if the system provides the temperature as a query, then tomorrow, the client can check_for_underheating without having to change SystemMonitor. This is not the case when the SystemMonitor implements check_for_overheating itself. Thus, a SystemMonitor class whose job is to raise an alarm when the temp is too high does follow this- but a SystemMonitor class whose job is to allow another piece of code to read the temperature so that it can control, say, TurboBoost or something like that, should not.

Also note that the second example pointlessly uses the Null Object Anti-pattern.


答:
First off, I feel I must take exception to your characterization of the examples as "bad" and "good".  The article uses the terms "Not so good" and "Better", I think those terms were chosen for a reason: these are guidelines, and depending on  circumstances the "Not so good" approach may be appropriate, or indeed the only solution.

When given a choice, you should give preference to including any functionality that relies solely upon the class in the class instead of outside it -- the reason is because of encapsulation, and the fact that it makes it easier to evolve the class over time.  The class also does a better job of advertising it's capabilities than a bunch of free functions.

Sometimes you have to tell, because the decision relies upon something outside of the class or because it is simply something you don't want most users of the class to do.  Sometimes you want to tell, because the behavior is counter intuitive for the class, and you don't want to confuse most users of the class.

For example, you complain about the street address returning an error message, it isn't, what it is doing is providing a default value.  But sometimes a default value isn't appropriate. If this was State or City, you might want a default when assigning an a record to a salesman or a survey taker, so that all of the unknowns go to a specific person.  On the other hand, if you were printing envelopes, you might prefer an exception or guard that keeps you from wasting paper on letters that can't be delivered.

So there can be cases where "Not so good" is the way to go, but generally, "Better" is, well, better.


问:
What is the significance of each paragraph of the GPL "copying permission statement"?
Part of the FSF's instructions for placing a program under the GPL is including the following "copying permission statement" at the top of your file, under the copyright notice:

```<code>This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
</code>```

I am wondering what is the significance of each paragraph in this statement. In particular, for a program that I am about to release under the GPL, I am considering omitting the second and third paragraphs to reduce the length of the statement, and I'm wondering what would be the negative consequences (if any) of doing so.

答:
I don't see how the header could be shorter and effective in doing what needs to be done.  The first paragraph declares the code free under the stated license.  That license places some restrictions on what can be done with the software/source code.

The second paragraph is a disclaimer of warranty.  I am not a lawyer, but personally I would want that paragraph retained.  It may not prevent someone from suing you, but it makes it difficult for them to succeed.

The last paragraph is a pointer to a much larger set of information which should replace the paragraph.  It shortens the header significantly by omitting the contents of the document it points to.


问:
How can I write a set of functions that can be invoked from (almost) any programming language?
I'd like to find a way to write an API that can be accessed from any other programming language via language bindings (or some other framework). Is it possible to do this? If so, which programming language would be the most suitable for writing a "cross-language" API? My goal is to create a single set of functions that I can access from any programming language that I'm working with, so that I won't need to manually re-write the entire API in each language.</p>

答:
I think C or C++ would be most suitable for your purpose.  You can use SWIG (Simplified Wrapper and Interface Generator) to generate language bindings from your C or C++ API.

SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages. SWIG is used with different types of target languages including common scripting languages such as Perl, PHP, Python, Tcl and Ruby. The list of supported languages also includes non-scripting languages such as C#, Common Lisp (CLISP, Allegro CL, CFFI, UFFI), D, Go language, Java including Android, Lua, Modula-3, OCAML, Octave and R. Also several interpreted and compiled Scheme implementations (Guile, MzScheme/Racket, Chicken) are supported. SWIG is most commonly used to create high-level interpreted or compiled programming environments, user interfaces, and as a tool for testing and prototyping C/C++ software. SWIG is typically used to parse C/C++ interfaces and generate the 'glue code' required for the above target languages to call into the C/C++ code. SWIG can also export its parse tree in the form of XML and Lisp s-expressions. SWIG is free software and the code that SWIG generates is compatible with both commercial and non-commercial projects...


问:
Considering consistent change, how short of a planning period is too short?
Change is not uncommon, change in requirements, change in specs change in workflow. I've accepted that there will be change, but I wonder: knowing that change is going to happen, how short of a planning period is too short? (Justifications are encouraged)

An iteration (2-4 weeks)?

A week?

A 2-3 day period?

A day?

1/2 a day?

Assume that the company 'plans' 1 [time interval (from above)] in advance from the current so that any plan sounds like:

"[this morning/today/this week/etc.] you'll work on this and [this afternoon/tomorrow/next week/etc.] you'll be working on that.

Also assume that the changes in focus/direction will consistently occur every second to third time interval.

答:
Planning to often tends to make the bigger picture get lost in all the details, and you just end up spinning your wheels. That is a huge risk.

I prefer using XP (or Scrum) which says that you should plan once at the beginning of each iteration, which I find most effective when they are 1-2 weeks in length.

Having said that, there are some very cool things in Kanban which encourages planning to happen when needed, though I personally think Kanban is better suited for maintenance and support situations rather than when starting development from scratch.

ContentLicense: CC BY-SA 2.5


问:
Issues Tracker for both developers and end users
currently, we have a closed source project on hand. However, we would like to have a communication channel together with our end users.

We would like to have our end users to know, what features we are currently working on, and what features they are going to get in next release.

We would like to know users' thought, on our planned features. They may always provide input/suggestion on our planned features.

We do not planned to host on our own server. Hence, a ready-available service is welcomed.

But we would like to remain our source code in closed model

Is there any web based service available for this purpose? Free or commercial doesn't matter.

答:
I can think of a couple off the top of my head.

FogBugz can manage an email address and "sort emails into the correct project area."  It also has evidence-based scheduling.

JIRA is used by Linden Lab.  End users file reports themselves.


问:
Is it common to use partial classes to achieve 'modularity'?
I recently encountered a situation in our codebase where a different team created a 'god class' containing around 800 methods, split across 135 files as a partial class.

I asked the other team about this.  While my gut reaction was to nuke it from orbit, they insist that it's a good design, a common practice, and that it promotes 'modularity' and 'ease of implementation' because new developers can bolt on functionality with almost no knowledge of the rest of the system.

Is this actually a common practice or in any way a good idea?  I'm inclined to take immediate steps to bring this beast down (or at least prevent it from growing further) but I'm willing to believe I'm wrong.

答:
A utility class contains methods that can't sensibly be combined with other methods to create a class.  If you have 800+ methods, split into 135 files, it seems likely  someone has managed to find some common methods...

Just because you have one utility class, doesn't mean that you can't have another utility class.

Even if you do have 800 mostly unrelated methods, the solution isn't one big class and a lot of files.  The solution is a namespace, some sub namespaces and a lot of little classes.  This is a bit more work (you have to come up with a name for the class as well as the method). But it will make your life easier when it comes time to cleanup this mess, and in the meantime it will make intellisense easier to use (ie easier to discover where a method is to use it).

And no, this isn't common (more the number of files than the number of free functions).


问:
Best practice on if/return
I want to know what is considered better way of returning when I have if statement.

Example 1:

```<code>public bool MyFunction()
{
   // Get some string for this example
   string myString = GetString();

   if (myString == null)
   {
      return false;
   }
   else
   {
      myString = "Name " + myString;
      // Do something more here...
      return true;
   }
}
</code>```

Example 2:

```<code>public bool MyFunction()
{
   // Get some string for this example
   string myString = GetString();

   if (myString == null)
   {
      return false;
   }

   myString = "Name " + myString;
   // Do something more here...
   return true;
}
</code>```

As you can see in both examples function will return true/false but is it a good idea to put else statement like in first example or it is better to not put it?

答:
My rule of thumb is to either do a if-return without an else (mostly for errors) or do a full if-else-if chain over all possibilities.

This way I avoid trying to be too fancy with my branching, since whenever I end up doing that my I encode application logic into my ifs, making them harder to maintain (For example, if an enum OK or ERR and I write all my ifs taking advantage of the fact that !OK <-> ERR it becomes a pain in the ass to add a third option to the enum next time.)

In your case, for example, I would use a plain if, since "return if null" is sure to be a common pattern and its not likely that you will need to worry about a third possibility (in addition to null/not null) in the future.

However, if the test was something that did a more in-dept inspection over the data I would err towards a full if-else instead.

Title: Best practice on if/return


答:
I would write

```<code>public bool SetUserId(int id)
{
   // Get user name from id
   string userName = GetNameById(id);

   if (userName != null)
   {
       // update local ID and userName
       _id = id;
       _userNameLabelText = "Name: " + userName;
   }

   return userName != null;
}
</code>```

I prefer this style because it is most obvious that I would return userName != null.

Title: Best practice on if/return

Body:
I want to know what is considered better way of returning when I have if statement.

Example 1:

```<code>public bool MyFunction()
{
   // Get some string for this example
   string myString = GetString();

   if (myString == null)
   {
      return false;
   }
   else
   {
      myString = "Name " + myString;
      // Do something more here...
      return true;
   }
}
</code>```

Example 2:

```<code>public bool MyFunction()
{
   // Get some string for this example
   string myString = GetString();

   if (myString == null)
   {
      return false;
   }

   myString = "Name " + myString;
   // Do something more here...
   return true;
}
</code>```

As you can see in both examples function will return true/false but is it a good idea to put else statement like in first example or it is better to not put it?

Body:
I would write

public bool SetUserId(int id)
{
   // Get user name from id
   string userName = GetNameById(id);

   if (userName != null)
   {
       // update local ID and userName
       _id = id;
       _userNameLabelText = "Name: " + userName;
   }

   return userName != null;
}

I prefer this style because it is most obvious that I would return userName != null.


答:
We use Jira for this with different projects for developpers and users. Other trackers should be able to do this as well though. Users can make feature requests, report bugs, view release status etc in the user projects only. The issues reported by users are reviewed and corresponding developper issues are created, then linked to the user issues. At first sight this looks like total duplication, but in fact it is not.

Example: user requests 'feature A' and describes it. The corresponding developper then creates an issue (or issues, for example one in the core API prooject and one in the UI project) where he/she documents what piece of code needs to change, updates the user issue's estimated time to finish it and links it to the developper issues. This way the customer doesn't have to bother with code details (which they do not care about anyway), but the developpers have a nice seperated overview of what it takes to complete an issue. This gets combined with the ability to view git commits etc, handy workflows and so on.

Jira takes some time to set up, but it's extremely customizable and after a year of use (together with confluence) we are very happy with it.

Title: Issues Tracker for both developers and end users

Body:
currently, we have a closed source project on hand. However, we would like to have a communication channel together with our end users.

We would like to have our end users to know, what features we are currently working on, and what features they are going to get in next release.

We would like to know users' thought, on our planned features. They may always provide input/suggestion on our planned features.

We do not planned to host on our own server. Hence, a ready-available service is welcomed.

But we would like to remain our source code in closed model

Is there any web based service available for this purpose? Free or commercial doesn't matter.


答:
In your example, the else is obviously unnecessary, BUT ...

When skimming quickly through lines of code, one's eyes typically look at the braces and the indentations to get an idea of the flow of code; before they actually settle on the code itself.  Therefore, writing the else, and putting braces and indentation around the second block of code actually makes it quicker for the reader to see that this is an "A or B" situation, where one block or the other will run.  That is, the reader sees the braces and indentation BEFORE they see the return after the initial if.

In my opinion, this is one of those rare cases where adding something redundant to the code actually makes it MORE readable, not less.

Title: Best practice on if/return


问:
What's the most important, useful or enlightening thing you learnt in the last 12 months?
A lot of people in the coding community talk about continuous improvement, deliberate practice and so-on - but when they talk about their current practices it's almost like they 'sprang fully formed from the loins of Zeus' because you don't hear about how their opinions changed over time or what they learnt recently.

Every now and then though I go to a talk, or read a book, or talk to someone and they open up a bit more and I find that I learn a lot from these insights.

So, if you had to pick one thing from the last 12 months that you learnt what would it be?

答:
I would say using Microsoft unit testing within Visual Studio 2010.

I found it really easy to debug a specific test method.

I could run anytime my test project in order to see if business layer application is working fine. The testing process guarantees that my team should have no problems when deploying the complete solution for our website visitors.


答:
I'd prefer example 2 because it's immediately obvious that the function returns something. But even more than that, I'd prefer to return from one place, like this:

```<code>public bool MyFunction()
{
    bool result = false;

    string myString = GetString();

    if (myString != nil) {
        myString = "Name " + myString;

        result = true;
    }

    return result;
}
</code>```

With this style I can:

See right away that I'm returning something.

Catch the result of every invocation of the function with just one breakpoint.

Title: Best practice on if/return

Body:
I'd prefer example 2 because it's immediately obvious that the function returns something. But even more than that, I'd prefer to return from one place, like this:

public bool MyFunction()
{
    bool result = false;

    string myString = GetString();

    if (myString != nil) {
        myString = "Name " + myString;

        result = true;
    }

    return result;
}

With this style I can:

See right away that I'm returning something.

Catch the result of every invocation of the function with just one breakpoint.


答: If performance and call latency is not an issue, consider providing a comprehensive command line interface (probably, using a scripting language on top of it). ImageMagick can be a good example of such an "API". Another good example is Tk toolkit.</p>

Title: How can I write a set of functions that can be invoked from (almost) any programming language?

Body: I'd like to find a way to write an API that can be accessed from any other programming language via language bindings (or some other framework). Is it possible to do this? If so, which programming language would be the most suitable for writing a "cross-language" API? My goal is to create a single set of functions that I can access from any programming language that I'm working with, so that I won't need to manually re-write the entire API in each language.</p>


答:
My personal style tends to go

```<code>function doQuery(string) {
    if (!query(string)) {
        query("ABORT");
        return false;
    } // else
    if(!anotherquery(string) {
        query("ABORT");
        return false;
    } // else
    return true;
}
</code>```

Using the commented-out else statements to indicate the program flow and keep it readable, but avoiding massive indents that can easily reach across the screen if a lot of steps are involved.

Title: Best practice on if/return

Body:
My personal style tends to go

function doQuery(string) {
    if (!query(string)) {
        query("ABORT");
        return false;
    } // else
    if(!anotherquery(string) {
        query("ABORT");
        return false;
    } // else
    return true;
}

Using the commented-out else statements to indicate the program flow and keep it readable, but avoiding massive indents that can easily reach across the screen if a lot of steps are involved.


问:
Handling fast growing multi-function services
My team has been developing a web business application for more than a year. It started quite small, but now it is growing bigger and bigger. I think it's time for refactoring.

Looking at the code, I see the below situation:

IUserService

addUser

deleteUser

updateUser

addMember

deleteMember

updateMember

registerMember

deactivateMember

....

getExpiringMember

nominateMember

Generally saying, there are about 50 functions for more than 2500 lines of business logic. I once read "Clean code", it states that there should be no more than 200 lines for a normal class. Our code violates this requirement seriously, and I'm beginning to feel the hardship of code management.

The simple solution might be spliting this service into many other services, but it is not feasible/reasonable:

This service class serves as an API point for mobile client, so that every change on Interface (even renaming) requires change for the client as well. I don't want to spend the precious time of our team if not for good reason.

I already split a part of this service into another classes, but that class (RegistrationService) also grow quite fast and reach 500 lines of code recently.

More and more business logic request recently, and these services are going to grow even more.

I'm afraid that at some point we will lose the tracks if a team member who manage a specified service got retired.

Is there any way I can make this service more manageable? Any Design Pattern, Refactoring technique that I can apply? I'm still not experienced enough in this field... any suggestions or directions are welcome.

答:
I'm not a Spring expert but from general design/architecture experience this looks like way too many methods for a single API / Service. It's something of a design smell to see this many methods in one interface.

You should try an break it down into logically distinct areas of functionality, each with a separate interface. Then the code to implement each distinct area should become manageable.

If you have client code that is hard to change, then it's fine to keep the old version of the service - just turn it into a lightweight facade that calls into the new refactored versions. Your clients won't have to change anything if they don't want to (though you should make clear that they will have to move to the new interfaces if they want access to any future functionality).

From the just the methods listed in the question above you could have at least four separate domains:

User management

Member management

Registrations (registerMember etc.)

Nominations (nominateMember etc.)

etc.


问:
Appropriate data structure for deeply nested data?
I can't figure out what would be an appropriate data structure for my problem. I need to write a script that will count some events. Input is a list of events (thousands of them). Each event is an object with following attributes:

```<code>class Event
  company
  city
  office
  department
</code>```

You can look at it like this: „Each event is related to one company in a particular town in one office and in one department of that office“.

My script needs to output the total number of events  for company, town office and department. Basically it needs to output sentences like this:

```<code>Total events in company X in town Y in office Z in department T : 15
Total events in company X in town Y in office Z in department R: 36
...
Total events in company N in town Y in office G in department T: 89
...
</code>```

How should I store these counts and how should I count them. I was thinking of using nested dictionaries (in python) or in-memory SQL database. Is there any other way?

答:
If the example sentence is ONLY required output, then it would be good to create a single key from all the sub-keys (company, town, office, department) and then use it as lookup for dictionary, whose value would be count of occurrence of this key.

If there are different aggregate outputs (counts, averages, over different keys) then you are probably looking for some kind of OLAP tool.


答: Besides politics Frank Shearar mentioned, I've recently discovered QUnit and JSCoverage which made my day. And month. Never thought it would be possible to unit test JavaScript with code coverage, but there it is... :-)

Title: What's the most important, useful or enlightening thing you learnt in the last 12 months?

Body:
A lot of people in the coding community talk about continuous improvement, deliberate practice and so-on - but when they talk about their current practices it's almost like they 'sprang fully formed from the loins of Zeus' because you don't hear about how their opinions changed over time or what they learnt recently.

Every now and then though I go to a talk, or read a book, or talk to someone and they open up a bit more and I find that I learn a lot from these insights.

So, if you had to pick one thing from the last 12 months that you learnt what would it be?


答:
You have a few options:

Create an HTTP interface, almost everything can talk HTTP so that will get you a lot of languages.

Create something that can be linked into a language runtime, this will be rather time consuming as you will need to find a way to connect it to many different languages.


答:
First approach is to determine the smallest atomic information in your structure would be event that should have foreign keys on Company, Town, Office, Department.

Thus, you may use template to construct sentences from count of events for required combinations.

Second approach might be using XML structure to store and retrieve your data.

Title: Appropriate data structure for deeply nested data?

Body:
I can't figure out what would be an appropriate data structure for my problem. I need to write a script that will count some events. Input is a list of events (thousands of them). Each event is an object with following attributes:

```<code>class Event
  company
  city
  office
  department
</code>```

You can look at it like this: „Each event is related to one company in a particular town in one office and in one department of that office“.

My script needs to output the total number of events  for company, town office and department. Basically it needs to output sentences like this:

```<code>Total events in company X in town Y in office Z in department T : 15
Total events in company X in town Y in office Z in department R: 36
...
Total events in company N in town Y in office G in department T: 89
...
</code>```

How should I store these counts and how should I count them. I was thinking of using nested dictionaries (in python) or in-memory SQL database. Is there any other way?


答:
It seems you can't split your service interface into different classes / services, to maintain backwards compatibility.

What you should do though, is split the functionality into classes according to SRP, and then (best-case) have interfaces to those classes as dependencies in the constructor of your service class or (worse-case) instatiate them all in the constructor.

Each method in the service class then becomes a single line of wrapping goodness, and the rest of your application can be sanely thought out without changing the public API.

Example:

```<code>public class Service : IUserService
{
    private IUserRepository userRepo;
    private IMemberStuff memStuff;

    public Service(IUserRepository userRepo, IMemberStuff memStuff)
    {
       this.userRepo = userRepo;
       this.memStuff = memStuff;
    }

    public void addUser(...)
    {
        userRepo.addUser(...);
    }

    public void deleteUser(...)
    {
    }

    public void updateUser(...)
    {
    }

    public void addMember(...)
    {
    }

    public void deleteMember(...)
    {
    }

    public void updateMember(...)
    {
    }

    public void registerMember(...)
    {
    }

    public void deactivateMember(...)
    {
    }

    public Member getExpiringMember(...)
    {
    }

    public void nominateMember(...)
    {
    }
}
</code>```

Title: Handling fast growing multi-function services

Body:
My team has been developing a web business application for more than a year. It started quite small, but now it is growing bigger and bigger. I think it's time for refactoring.

Looking at the code, I see the below situation:

IUserService

addUser

deleteUser

updateUser

addMember

deleteMember

updateMember

registerMember

deactivateMember

....

getExpiringMember

nominateMember

Generally saying, there are about 50 functions for more than 2500 lines of business logic. I once read "Clean code", it states that there should be no more than 200 lines for a normal class. Our code violates this requirement seriously, and I'm beginning to feel the hardship of code management.

The simple solution might be spliting this service into many other services, but it is not feasible/reasonable:

This service class serves as an API point for mobile client, so that every change on Interface (even renaming) requires change for the client as well. I don't want to spend the precious time of our team if not for good reason.

I already split a part of this service into another classes, but that class (RegistrationService) also grow quite fast and reach 500 lines of code recently.

More and more business logic request recently, and these services are going to grow even more.

I'm afraid that at some point we will lose the tracks if a team member who manage a specified service got retired.

Is there any way I can make this service more manageable? Any Design Pattern, Refactoring technique that I can apply? I'm still not experienced enough in this field... any suggestions or directions are welcome.

Body:
It seems you can't split your service interface into different classes / services, to maintain backwards compatibility.

What you should do though, is split the functionality into classes according to SRP, and then (best-case) have interfaces to those classes as dependencies in the constructor of your service class or (worse-case) instatiate them all in the constructor.

Each method in the service class then becomes a single line of wrapping goodness, and the rest of your application can be sanely thought out without changing the public API.

Example:

public class Service : IUserService
{
    private IUserRepository userRepo;
    private IMemberStuff memStuff;

    public Service(IUserRepository userRepo, IMemberStuff memStuff)
    {
       this.userRepo = userRepo;
       this.memStuff = memStuff;
    }

    public void addUser(...)
    {
        userRepo.addUser(...);
    }

    public void deleteUser(...)
    {
    }

    public void updateUser(...)
    {
    }

    public void addMember(...)
    {
    }

    public void deleteMember(...)
    {
    }

    public void updateMember(...)
    {
    }

    public void registerMember(...)
    {
    }

    public void deactivateMember(...)
    {
    }

    public Member getExpiringMember(...)
    {
    }

    public void nominateMember(...)
    {
    }
}


问:
Why all classes in .NET globally inherits from Object class?
Its very interesting for me which advantages gives "global root class" approach for framework.
In simple words what reasons resulted the .NET framework was designed to have one root object class with general functionality suitable for all classes.

Nowadays we are designing new framework for internal use (the framework under SAP platform) and  we all divided into two camps - first who thinks that framework should have global root, and the second - who thinks opposite.

I am at "global root" camp. And my reasons what such approach would yields good flexibility and development costs reduction cause we will not develop general functionality any more.

So, I'm very interested to know what reasons really push .NET architects to design framework in such way.

答:
Seems to me you have three questions here: one is why a common root was introduced to .NET, the second is what are the advantages and disadvantages of that, and the third is whether it's a good idea for a framework element to have a global root.

Why does .NET have a common root?

In the most technical sense, having a common root is essential for reflection and for pre-generics containers.

In addition, to my knowledge, having a common root with base methods such as equals() and hashCode() was received very positively in Java, and C# was influenced by (among others) Java, so they wanted to have that feature as well.

What are the advantages and disadvantages of having a common root in a language?

The advantage of having a common root:

You can allow all objects to have a certain functionality you consider important, such as equals() and hashCode(). That means, for example, that every object in Java or C# can be used in a hash map - compare that situation with C++.

You can refer to objects of unknown types - e.g. if you just transfer information around, as pre-generic containers did.

You can refer to objects of unknowable type - e.g. when using reflection.

It can be used in the rare cases when you want to be able to accept an object that can be of different and otherwise unrelated types - e.g. as a parameter of a printf-like method.

It gives you the flexibility of changing the behavior of all objects by changing just one class. For example, if you want to add a method to all objects in your C# program, you can add an extension method to object. Not very common, perhaps, but without a common root it would not be possible.

The disadvantage of having a common root:

It can be abused to refer to an object of some value even if you could have used a more accurate type for it.

Should you go with a common root in your framework project?

Very subjective, of course, but when I look at the above pro-con list I'd definitely answer yes.  Specifically, the last bullet in the pro list - flexibility of later changing the behavior of all objects by changing the root - becomes very useful in a platform, in which changes to the root are more likely to be accepted by clients than changes to an entire language.

Besides - though this is even more subjective - I find  the concept of a common root very elegant and appealing. It also makes some tool usage easier, for example it's now easy to ask a tool to show all the descendants of that common root and receive a quick, good overview of the framework's types.

Of course, the types do have to be at least slightly related for that, and in particular, I'd never sacrifice the "is-a" rule just to have a common root.

OwnerDisplayName: Anton Semenov


答:
Make a table with all companies, a table with all towns and a table with all department types.

Then make a Table with all offices, where town and company are properties.
Then make a Table with all departments where office and department type are properties.

Finally Make a Table with all events linked to the according department.


答:
If I have a single if condition I wouldnt spend too much time ruminating about the style. But if I have multiple guard conditions I would prefer style2

Picuture this. Assume that the tests are complex and you really dont want to tie them into a single if-ORed condition to avoid complexity:

```<code>//Style1
if (this1 != Right)
{
    return;
}
else if(this2 != right2)
{
    return;
}
else if(this3 != right2)
{
    return;
}
else
{
    //everything is right
    //do something
    return;
}
</code>```

versus

```<code>//Style 2
if (this1 != Right)
{
   return;
}
if(this2 != right2)
{
    return;
}
if(this3 != right2)
{
    return;
}

//everything is right
//do something
return;
</code>```

Here there are two main advantages

You are separating the code in a single function into two
visually logcal blocks : an upper block of validations(guard
conditions) and a lower block of runnable code.

If you have to add/remove one condition , you reduce your chances
of messing up the entire if-elseif-else ladder.

Another minor advantage is you have one fewer set of braces to care for.

Title: Best practice on if/return

Body:
If I have a single if condition I wouldnt spend too much time ruminating about the style. But if I have multiple guard conditions I would prefer style2

Picuture this. Assume that the tests are complex and you really dont want to tie them into a single if-ORed condition to avoid complexity:

//Style1
if (this1 != Right)
{
    return;
}
else if(this2 != right2)
{
    return;
}
else if(this3 != right2)
{
    return;
}
else
{
    //everything is right
    //do something
    return;
}

versus

//Style 2
if (this1 != Right)
{
   return;
}
if(this2 != right2)
{
    return;
}
if(this3 != right2)
{
    return;
}

//everything is right
//do something
return;

Here there are two main advantages

You are separating the code in a single function into two
visually logcal blocks : an upper block of validations(guard
conditions) and a lower block of runnable code.

If you have to add/remove one condition , you reduce your chances
of messing up the entire if-elseif-else ladder.

Another minor advantage is you have one fewer set of braces to care for.


答: If your data is hierarchical (company can exist in multiple towns, each town can have multiple offices, each office can have multiple departments) then I'd use a bunch of nested dictionaries/hash maps.  You'll have one at the top level containing all companies, the value will be the dictionary of towns that company has offices in, the values in that will be a dictionary of offices in that town, and the value of that will be a dictionary of departments in that office.  The departments dictionary can contain either a simple event count or you can store other information in there (event timestamp, event type/severity/response, whatever).


问:
In a 4 hour Powershell 101 class should I skip for/while/do and just teach ForEach-Object
I'm making a syllabus to teach non-programmer co-workers PowerShell. The first non-pilot group I will run the course with will be a team that deploys and configures one of our software products. They are bright intelligent motivated IT workers, but not programmers.

I intend to cover the basics (variables, arrays, functions, and loops), and then move onto examples that are close to their problem domain. I'm not married to a 4 hour class, if necessary I can expand it to two four hour classes.

I'm toying with the idea of skipping for and while loops and simply teaching ForEach-Object. I've personally used traditional for and while loops in powershell scripts, but they can always be rewritten  as ForEach-Object loops with a bit of creativity. Part of me feels the good old for ($i=0 $i < foo; $i++) is a necessary fundamental before moving onto foreach, but the other part of me thinks that might be me clinging to my Model M and my K&R Bible.

To draw an analogy to SQL, I'd never teach a CURSORs or other loops in a 4 hour class there because you're supposed to be able to do everything in SQL as a SET operation. In theory you should stick to the pipeline in PowerShell. I use for and while loops in PowerShell more often than I do do cursors and while loops in SQL. However, PowerShell is a scripting language and conventions are less strictly enforced and I also push the boundaries of powershell with inline C# and excessive dependencies on calling native .NET APIs. My audience will not be ding this.

For those not adept at powershell, I'm pretty sure you don't actually need a for or while loop. I use them, but that's because I have experience with other languages. For example if you only want the first 10 members of an array of 20 members:

```<code>1..20 | Select-Object -First 10 | ForEach-Object { Write-Host $_ }
</code>```

答:
I find myself using the for and while loops a lot in powershell. When I have a boolean I just write while($bool). I think that it is important to atleast touch on these concepts, considering they are found in a lot of other programming languages.

A better example that you may not be able to do with a foreach loop (effeciently atleast) is take every other object out of an array:

```<code>for($i=0; $i -le $arr.length-1; $i=$i+2) {$newArr += $arr[$i]}
</code>```

I find myself using this one alot after a -split

Body:
I find myself using the for and while loops a lot in powershell. When I have a boolean I just write while($bool). I think that it is important to atleast touch on these concepts, considering they are found in a lot of other programming languages.

A better example that you may not be able to do with a foreach loop (effeciently atleast) is take every other object out of an array:

for($i=0; $i -le $arr.length-1; $i=$i+2) {$newArr += $arr[$i]}

I find myself using this one alot after a -split


问:
.NET silverlight development tools
What tools are necessary when developing efficiently with Silverlight 4? VS 2010 is a gimme, but what version? Is Pro enough? Premium? What about Expression Blend/Web/Both?

When considering VS 2010, premium comes with an MSDN subscription but it's at the high end of the budget. It makes sense if Expression comes with it though.

It's for a one man development show, making an LOB app that will integrate video/audo and mic/webcam equipment.

答:
I would go for Microsoft Expression Blend. I remember that earlier version had a buggy source code editor, but I hope this one is fixed.

http://www.microsoft.com/expression/products/blend_overview.aspx

Title: .NET silverlight development tools


答:
By API, what exactly do you mean?

On many platforms you could link to a DLL or similar construction, but would having to be re-compiled for a particular native target (Intel/ARM) or endianness still qualify?  A particular binary interface might still have difficulties with certain languages because of datatype issues or constructs (pointers trying to be returned to languages which don't support them well), so you would also have to consider the design of the API itself so as not to exclude some languages or make its use from those languages cumbersome.

Something portable like C and an interface based on binary endpoints in a DLL might be fine and generally callable on most platforms and from most languages, but it might need to be compiled differently and/or offered in different flavors or linked to different static libraries.

It seems to me that the choice of language you write your library or service or whatever is, by definition, not intrinsic to the question until you've given more about the platform/service the API exposes.  If you can assume a network stack is available and direct-linked function-call-level performance is not a requirement, the API could easily be HTTP-based with some kind of shim for the client language to make the requests transparent.

I think in general this question is overly broad to be useful in the real world, because you haven't given indication about what kind of API might be suitable given the type of service which is being offered.


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

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

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

答:
Kinda surprised no one has said this yet, but there are distributed bug tracking solutions which act as part of your distributed source control i.e. the bugs database lives with your code in your revision control. Well known implementations include "Bugs Everywhere", Fossil and Ditz.

See https://stackoverflow.com/questions/773818/distributed-projectmanagement-bug-tracking and https://stackoverflow.com/questions/1851221/distributed-bug-tracker-to-go-with-dvc?rq=1 for a discussion.


答: Traditional for and while loops I don't think add much value to a 4 hour course.  Ideally they are taking your course so they can write scripts and get stuff done.  A ForEach loop is easier and sufficient to get the job done most of the time.   If they need the traditional loop construct then they can always learn it when they need it.  Same thing with objects, they don't need a deep understanding, just enough to know how to use methods.</p>

Title: In a 4 hour Powershell 101 class should I skip for/while/do and just teach ForEach-Object

Body:
I'm making a syllabus to teach non-programmer co-workers PowerShell. The first non-pilot group I will run the course with will be a team that deploys and configures one of our software products. They are bright intelligent motivated IT workers, but not programmers.

I intend to cover the basics (variables, arrays, functions, and loops), and then move onto examples that are close to their problem domain. I'm not married to a 4 hour class, if necessary I can expand it to two four hour classes.

I'm toying with the idea of skipping for and while loops and simply teaching ForEach-Object. I've personally used traditional for and while loops in powershell scripts, but they can always be rewritten  as ForEach-Object loops with a bit of creativity. Part of me feels the good old for ($i=0 $i < foo; $i++) is a necessary fundamental before moving onto foreach, but the other part of me thinks that might be me clinging to my Model M and my K&R Bible.

To draw an analogy to SQL, I'd never teach a CURSORs or other loops in a 4 hour class there because you're supposed to be able to do everything in SQL as a SET operation. In theory you should stick to the pipeline in PowerShell. I use for and while loops in PowerShell more often than I do do cursors and while loops in SQL. However, PowerShell is a scripting language and conventions are less strictly enforced and I also push the boundaries of powershell with inline C# and excessive dependencies on calling native .NET APIs. My audience will not be ding this.

For those not adept at powershell, I'm pretty sure you don't actually need a for or while loop. I use them, but that's because I have experience with other languages. For example if you only want the first 10 members of an array of 20 members:

```<code>1..20 | Select-Object -First 10 | ForEach-Object { Write-Host $_ }
</code>```


答:
The GPL FAQ answers all your questions (and more!).

The short answer version - Yes, you can shorten the copyright, copying permission, warranty, and license statement.  (And yes, that's a flip-flop from my previous answer).

But you (still) may not want to.

From the GPL License under
"How to Apply These Terms to Your New Programs"
 emphasis mine.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.

Translated:

You do not have to insert that block of text at the beginning of every source file.  FSF highly recommends it since they called that the safest course of action.  Either they envision or have dealt with problems where the full block wasn't included in every source file.  FSF is pretty conservative in their legal stance, so I take heed when they make a strong statement like that.

If you were looking to shrink things down, then at a minimum you would want your copyright statement and the exclusion of warranty claims.

It's distinctly possible that you could run into problems later on as your project grows and is shared by others.  Developers are lazy efficient.  When they pull only the sections they need from your project, they may or may not remember to update the correct places where the copyright, permissions, warranty, and license statement are now supposed to exist based upon the reduced form you started using with your project.  If the block is already there, then the only thing that might be missing is their addition of their copyright statement.

IMO, it's easiest and safest to include the block in each source file.  That best covers all of the what-if scenarios that you can fall into.  Most IDEs provide a way to fold comment blocks so you don't have to see it every time.  Comments aren't included with source, so it won't bloat your program.  If you honestly don't care about losing control over the code, then don't worry about it.  For that matter, then you should consider licensing as public domain instead of GPL.

FAQ sections of relevance

Omitting the preamble

```
The preamble and instructions are integral parts of the GNU GPL and may not be omitted.
In fact, the GPL is copyrighted, and its license permits only verbatim copying of the
entire GPL.
```

Including the license

```
Including a copy of the license with the work is vital so that everyone who gets a
copy of the program can know what his rights are.
```

Which extends to developers looking at your code, and in part that's why you have to have the preamble in place.

However, you're still free to add additional disclaimers, if need be.

Summary of the paragraphs

"This is free.  Here's how you can use it."

"No Warranties.  Hope you find it useful anyway."

"Got License?  No?  Here's where you can find it."

Title: What is the significance of each paragraph of the GPL "copying permission statement"?

Body:
Part of the FSF's instructions for placing a program under the GPL is including the following "copying permission statement" at the top of your file, under the copyright notice:

```<code>This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
</code>```

I am wondering what is the significance of each paragraph in this statement. In particular, for a program that I am about to release under the GPL, I am considering omitting the second and third paragraphs to reduce the length of the statement, and I'm wondering what would be the negative consequences (if any) of doing so.

Body:
The GPL FAQ answers all your questions (and more!).

The short answer version - Yes, you can shorten the copyright, copying permission, warranty, and license statement.  (And yes, that's a flip-flop from my previous answer).

But you (still) may not want to.

From the GPL License under
"How to Apply These Terms to Your New Programs"
 emphasis mine.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.

Translated:

You do not have to insert that block of text at the beginning of every source file.  FSF highly recommends it since they called that the safest course of action.  Either they envision or have dealt with problems where the full block wasn't included in every source file.  FSF is pretty conservative in their legal stance, so I take heed when they make a strong statement like that.

If you were looking to shrink things down, then at a minimum you would want your copyright statement and the exclusion of warranty claims.

It's distinctly possible that you could run into problems later on as your project grows and is shared by others.  Developers are lazy efficient.  When they pull only the sections they need from your project, they may or may not remember to update the correct places where the copyright, permissions, warranty, and license statement are now supposed to exist based upon the reduced form you started using with your project.  If the block is already there, then the only thing that might be missing is their addition of their copyright statement.

IMO, it's easiest and safest to include the block in each source file.  That best covers all of the what-if scenarios that you can fall into.  Most IDEs provide a way to fold comment blocks so you don't have to see it every time.  Comments aren't included with source, so it won't bloat your program.  If you honestly don't care about losing control over the code, then don't worry about it.  For that matter, then you should consider licensing as public domain instead of GPL.

FAQ sections of relevance

Omitting the preamble

The preamble and instructions are integral parts of the GNU GPL and may not be omitted.
In fact, the GPL is copyrighted, and its license permits only verbatim copying of the
entire GPL.

Including the license

Including a copy of the license with the work is vital so that everyone who gets a
copy of the program can know what his rights are.

Which extends to developers looking at your code, and in part that's why you have to have the preamble in place.

However, you're still free to add additional disclaimers, if need be.

Summary of the paragraphs

"This is free.  Here's how you can use it."

"No Warranties.  Hope you find it useful anyway."

"Got License?  No?  Here's where you can find it."


答:
I think there are a lot of pitfalls to Example 2, that down the road could lead to unintended code. 1st off the focus here is based on logic surrounding the 'myString' variable. Therefore to be explicit, all testing of conditions should happen in a code block accounting for known and default/unknown logic.

What if later on code was introduced unintentionally to example 2 that altered the ouput significantly:

```<code>   if (myString == null)
   {
      return false;
   }

   //add some v1 update code here...
   myString = "And the winner is: ";
   //add some v2 update code here...
   //buried in v2 updates the following line was added
   myString = null;
   //add some v3 update code here...
   //Well technically this should not be hit because myString = null
   //but we already passed that logic
   myString = "Name " + myString;
   // Do something more here...
   return true;
</code>```

I think with the else block immediately following the check for a null would have made programmers that added the enhancements to the future versions add all the logic together because now we have a string of logic that was unintended for the original rule (returning if the value is null).

I lend my belief in this heavily to some of the C# guidlines on Codeplex (link to that here: http://csharpguidelines.codeplex.com/) that state the following:

"Add a descriptive comment if the default block (else) is supposed to be empty. Moreover, if that block is not supposed to be reached throw an InvalidOperationException to detect future changes that may fall through the existing cases. This ensures better code, because all paths the code can travel has been thought about."

I think it is good programming practice when using logic blocks like this to always have a default block added (if-else, case:default) to account for all code paths explicitly and not to leave code open to unintended logic consequences.

Title: Best practice on if/return

Body:
I think there are a lot of pitfalls to Example 2, that down the road could lead to unintended code. 1st off the focus here is based on logic surrounding the 'myString' variable. Therefore to be explicit, all testing of conditions should happen in a code block accounting for known and default/unknown logic.

What if later on code was introduced unintentionally to example 2 that altered the ouput significantly:

   if (myString == null)
   {
      return false;
   }

   //add some v1 update code here...
   myString = "And the winner is: ";
   //add some v2 update code here...
   //buried in v2 updates the following line was added
   myString = null;
   //add some v3 update code here...
   //Well technically this should not be hit because myString = null
   //but we already passed that logic
   myString = "Name " + myString;
   // Do something more here...
   return true;

I think with the else block immediately following the check for a null would have made programmers that added the enhancements to the future versions add all the logic together because now we have a string of logic that was unintended for the original rule (returning if the value is null).

I lend my belief in this heavily to some of the C# guidlines on Codeplex (link to that here: http://csharpguidelines.codeplex.com/) that state the following:

"Add a descriptive comment if the default block (else) is supposed to be empty. Moreover, if that block is not supposed to be reached throw an InvalidOperationException to detect future changes that may fall through the existing cases. This ensures better code, because all paths the code can travel has been thought about."

I think it is good programming practice when using logic blocks like this to always have a default block added (if-else, case:default) to account for all code paths explicitly and not to leave code open to unintended logic consequences.


问:
Why is it preferred to write a commit message in present tense/imperative mood?
I often read/overhear that good commit messages should be written in present tense or to use imperative mood when describing the change eg. Fix xyz instead of Fixed xyz.

What are the advantages of doing so? Are there differences between the various VCS (I mostly read these about git but that maybe because I mainly work with git)?

答: As I understand it, the present tense means that the commit itself fixes the issue, not the developer which could be implied by using the past tense -"the developer fixed the issue".


问:
Adapting parts of an open-source project for my own use
I'm in the process of coding a game and almost done with the game mechanics to the point where it's pretty playable. I later discovered an open source version of the kind of game I'm making with the same mechanics, whereas I coded mine from scratch.

However, in the interest of optimizing later on, I may want to adapt a small part of the open source project's code. The project is under the GNU GPL 2, and it's coded in a different language for a different framework (Android/Java versus mine on C#/XNA). What are my options as to copying functions / routines from a GPL open source project, if I would have to port the code anyways, for the language I'm using?

These are not patented algorithms I'm talking about, just code I found that could possibly make my program more efficient or stamp out a bug.

答:
In practical terms, if you read the java source code and then re-create it yourself, no-one will ever know. If you take the java source code and simply modify it so it compiles in C# then the owner of the original would have cause against you if its so obvious that this is what you've done (and therefore your game would become licensed under the GPL too)

Ethically, you should recognise you're taking someone's work - work that they want you to have, but with obligations. You could contact them and ask to use the pieces of code for a closed-source game, a lot of OSS people will happily allow that, or you could contact them and offer to licence their work for a small fee.


答:
Have any language write out a text file with function to call with params to pass in.  Have your "I get along with anybody" app watching a directory and once it sees a process-call.txt have it go to work.  No servers or network protocols; even a non-computer language method can init the functions.  Even a person could just create the text file. </p>

<p>Content could look like: </p>

```<code>Call-method:  fdisk()
Params:  (string) "/root", (string) "write-back-file-expected.txt"
</code>```

<p>;) you might wait forever to get an answer though.  You just need to push a few bytes to the other process, but I'm sure that's not the whole spec. </p>

Body:
Have any language write out a text file with function to call with params to pass in.  Have your "I get along with anybody" app watching a directory and once it sees a process-call.txt have it go to work.  No servers or network protocols; even a non-computer language method can init the functions.  Even a person could just create the text file.

Content could look like:

Call-method:  fdisk()
Params:  (string) "/root", (string) "write-back-file-expected.txt"

;) you might wait forever to get an answer though.  You just need to push a few bytes to the other process, but I'm sure that's not the whole spec.


答:
When you use "Fixed XYZ" you can import it straight to your changelog. For example PHP Changelog.

18-Jul-2013

Core:

Fixed bug #65254 (Exception not catchable when exception thrown in autoload with a namespace).

Fixed bug #65088 (Generated configure script is malformed on OpenBSD).

Fixed bug #65108 (is_callable() triggers Fatal Error).

Fixed bug #65035 (yield / exit segfault).

Fixed bug #65161 (Generator + autoload + syntax error = segfault).

Fixed bug #65226 (chroot() does not get enabled).

hex2bin() raises E_WARNING for invalid hex string.

OPcache:

Fixed bug #64827 (Segfault in zval_mark_grey (zend_gc.c))...

Title: Why is it preferred to write a commit message in present tense/imperative mood?

Body:
I often read/overhear that good commit messages should be written in present tense or to use imperative mood when describing the change eg. Fix xyz instead of Fixed xyz.

What are the advantages of doing so? Are there differences between the various VCS (I mostly read these about git but that maybe because I mainly work with git)?


问:
How to indicate the word is method name in Objective-C?
You can indicate that XXX is method name by writing XXX().

But in Objective-C, you can not write XXX() for XXX method.

If you write XXX, you can't tell if XXX is method name or other type of identifier.

How can you indicate that XXX is method name of Objective-C class?

EDIT

Method call of Objective-C is different from other language.

in Objective-C, method call is:

```<code>[self XXX];
</code>```

in other language, method call is:

```<code>self->XXX();
</code>```

In other language, for example, we can write in stackoverflow:

```<code>XXX() doesn't work
</code>```

And we can know XXX is method thanks to ().

But in Objective-C, we can't say:

```<code>XXX doesn't work
</code>```

Instead, to make it clear that XXX is method, we have to say:

```<code>XXX method doesn't work
</code>```

答:
Terminology: It's not a method name, it's a message name, aka selector.

To your question: it's obvious from the syntax, message sends always take the form [receiver message_with_parameters], where receiver is an expression (it may be another [...]), so anything after receiver is a selector (that is, what you call method name). In case of selector without params, it is just its name (like is the case with [[Class alloc] init], in case of of selector with params, it looks like [3 between: 1 and: 5].

Or is your problem somewhere else? The question was a bit unclear.


答:
If you're talking about using init in documentation or some other place where you're describing the method, you can prefix it with a - if it's an instance method or a + if it's a class method. If the method takes parameters, leave them out and just concatenate the different parts of the method name, like: -initWithNibName:bundle: or +colorWithRed:green:blue:alpha:. Don't leave the colons out, though -- they're part of the selector. For example, you might write:

One way to create a color is by calling UIColor's +colorWithRed:green:blue:alpha: method.

Sometimes people include both the class name and method name, prefixed with the appropriate character and wrapped in square brackets:

One way to initialize a view controller is with -[UIViewController initWithNibName:bundle:].

That's not really a correct use of Objective-C syntax -- you'd never actually call a method like that -- but it conveys three important pieces of information: type of method (class or instance), class, and selector.

In code, of course, you don't need to do anything special to indicate what kind of identifier it is. Just use the method name in an appropriate context and the compiler will figure it out:

```<code>UIColor *color = [UIColor colorWithRed:0.5 green:0.5 blue:0.9 alpha:1.0];

NSMutableArray *array = [[NSMutableArray alloc] init];
</code>```

Title: How to indicate the word is method name in Objective-C?

Body:
You can indicate that XXX is method name by writing XXX().

But in Objective-C, you can not write XXX() for XXX method.

If you write XXX, you can't tell if XXX is method name or other type of identifier.

How can you indicate that XXX is method name of Objective-C class?

EDIT

Method call of Objective-C is different from other language.

in Objective-C, method call is:

```<code>[self XXX];
</code>```

in other language, method call is:

```<code>self->XXX();
</code>```

In other language, for example, we can write in stackoverflow:

```<code>XXX() doesn't work
</code>```

And we can know XXX is method thanks to ().

But in Objective-C, we can't say:

```<code>XXX doesn't work
</code>```

Instead, to make it clear that XXX is method, we have to say:

```<code>XXX method doesn't work
</code>```

Body:
If you're talking about using init in documentation or some other place where you're describing the method, you can prefix it with a - if it's an instance method or a + if it's a class method. If the method takes parameters, leave them out and just concatenate the different parts of the method name, like: -initWithNibName:bundle: or +colorWithRed:green:blue:alpha:. Don't leave the colons out, though -- they're part of the selector. For example, you might write:

One way to create a color is by calling UIColor's +colorWithRed:green:blue:alpha: method.

Sometimes people include both the class name and method name, prefixed with the appropriate character and wrapped in square brackets:

One way to initialize a view controller is with -[UIViewController initWithNibName:bundle:].

That's not really a correct use of Objective-C syntax -- you'd never actually call a method like that -- but it conveys three important pieces of information: type of method (class or instance), class, and selector.

In code, of course, you don't need to do anything special to indicate what kind of identifier it is. Just use the method name in an appropriate context and the compiler will figure it out:

UIColor *color = [UIColor colorWithRed:0.5 green:0.5 blue:0.9 alpha:1.0];

NSMutableArray *array = [[NSMutableArray alloc] init];


问:
How much Code Coverage is "enough"?
We are starting a push for code coverage here at my work, and it has got me to thinking.... How much code coverage is enough?

When do you get to the point of diminishing returns on code coverage?  What is the sweet spot between good coverage and not enough?  Does it vary by the type of project your are making (ie WPF, WCF, Mobile, ASP.NET)  (These are C# classes we are writing.)

答: We aim for at least 70%.  On things that are more easily testable (functional data structures, for example), we aim for 90% and most individuals aim for as near to 100% as possible.  On WPF-related things and other frameworks that are very difficult to test, we get much lower coverage (barely 70%).

Title: How much Code Coverage is "enough"?


答: I will typically use +[NSString stringWithString:] and  -[NSString initWithString:], unless there is enough context to omit the + or - and class (then I would reduce it to stringWithString: and initWithString:).


问:
Convention on model names in ruby on rails
I was doing my ER diagram for a rails application I'm about to begin with and there I have an entity called Class News so I'd have a model ClassNew but I don't know if I will have problems in the future with the New part or what would be the right way to do this o how should I call the model? since the right thing would be ClassNews and the table should be class_news...

What's the best thing to do when working with News at the time of creating models for ActiveRecord in Ruby on Rails.

Thanks.

答: Why would the model be called "ClassNew" ?  "News" is an uncountable noun.  If RAILS doesn't already have "News" marked as uncountable, you can change the rules.</p>


问:
How can I write a set of functions that can be invoked from (almost) any programming language?
I'd like to find a way to write an API that can be accessed from any other programming language via language bindings (or some other framework). Is it possible to do this? If so, which programming language would be the most suitable for writing a "cross-language" API? My goal is to create a single set of functions that I can access from any programming language that I'm working with, so that I won't need to manually re-write the entire API in each language.</p>

答:
There are pretty much 2 ways:

a C API. Practically ever language there ever was will load a C library and call its functions. How you do this depends on the source language.

a RPC mechanism of some sort. This can be a REST API running over HTTP, or a binary interface running over a socket. Unless you go for the lowest common denominator mechanism (eg a socket) you run the risk of not having client access routines (eg some languages do not have the right SOAP clients to call an API implemented using SOAP, or there are interoperability issues). Stick to the simplest, either a HTTP/REST interface, or a socket. Sockets have the advantage that they do not need a HTTP server to expose the interface to the clients, and can more easily run on the same server as the client with better performance.

The work required for this changes depending on the system used, for example, a socket interface will work, but client-side libraries tend to be more low-level compared to http libraries.

You could try finding a networking library that supports all the languages you want to use, and implement the API in terms of that library - eg, using ZeroMQ gives you a lot of flexibility, so you'd write your API using ZeroMQ interfaces, and then any language that wants to call your API must use the ZeroMQ client library to do so. Choose a library that supports a broad range of languages, and allows you to in-process as well as out-of-process communication for best performance.


问:
Why a static main method in Java and C#, rather than a constructor?
I’m Looking for a definitive answer from a primary or secondary source for why (notably) Java and C# decided to have a static method as their entry point, rather than representing an application instance by an instance of an Application class (with the entry point being an appropriate constructor).

Background and details of my prior research

This has been asked before. Unfortunately, the existing answers are merely begging the question. In particular, the following answers don’t satisfy me, as I deem them incorrect:

There would be ambiguity if the constructor were overloaded. – In fact, C# (as well as C and C++) allows different signatures for Main so the same potential ambiguity exists, and is dealt with.

A static method means no objects can be instantiated before so order of initialisation is clear. – This is just factually wrong, some objects are instantiated before (e.g. in a static constructor).

So they can be invoked by the runtime without having to instantiate a parent object. – This is no answer at all.

Just to justify further why I think this is a valid and interesting question:

Many frameworks do use classes to represent applications, and constructors as entry points. For instance, the VB.NET application framework uses a dedicated main dialog (and its constructor) as the entry point1.

Neither Java nor C# technically need a main method. Well, C# needs one to compile, but Java not even that. And in neither case is it needed for execution. So this doesn’t appear to be a technical restriction. And, as I mentioned in the first paragraph, for a mere convention it seems oddly unfitting with the general design principle of Java and C#.

To be clear, there isn’t a specific disadvantage to having a static main method, it’s just distinctly odd, which made me wonder if there was some technical rationale behind it.

I’m interested in a definitive answer from a primary or secondary source, not mere speculations.

1 Although there is a callback (Startup) which may intercept this.

答:
TL;DR

In Java, the reason of public static void main(String[] args) is that

Gosling wanted

the code written by someone experienced in C (not in Java)

to be executed by someone used to running PostScript on NeWS

For C#, the reasoning is transitively similar so to speak. Language designers kept the program entry point syntax familiar for programmers coming from Java. As C# architect Anders Hejlsberg puts it,

...our approach with C# has simply been to offer an alternative... to Java programmers...

Long version

expanding above and backed up with boring references.

java Terminator Hasta la vista Baby!

VM Spec, 2.17.1 Virtual Machine Start-up

...The manner in which the initial class is specified to the Java virtual machine is beyond the scope of this specification, but it is typical, in host environments that use command lines, for the fully qualified name of the class to be specified as a command-line argument and for subsequent command-line arguments to be used as strings to be provided as the argument to the method main. For example, using Sun's Java 2 SDK for Solaris, the command line

java Terminator Hasta la vista Baby!

will start a Java virtual machine by invoking the method main of class Terminator (a class in an unnamed package) and passing it an array containing the four strings "Hasta", "la", "vista", and "Baby!"...

...see also: Appendix: I need your clothes, your boots and your motorcycle

My interpretation:

execution targeted for use like typical scripts in command line interface.

important sidestep

...that helps avoid a couple of false traces in our investigation.

VM Spec, 1.2 The Java Virtual Machine

The Java virtual machine knows nothing of the Java programming language...

I noticed above when studying prior chapter - 1.1 History which I thought could be helpful (but turned out useless).

My interpretation:

execution is governed by VM spec alone, which

explicitly declares that it has nothing to do with Java language

=> OK to ignore JLS and anything Java language related at all

Gosling: a compromise between C and scripting language...

Based on above, I began searching the web for JVM history. Didn't help, too much garbage in results.

Then, I recalled legends about Gosling and narrowed down my search to Gosling JVM history.

Eureka! How The JVM Spec Came To Be

In this keynote from the JVM Languages Summit 2008, James Gosling discusses... Java's creation,... a compromise between C and scripting language...

My interpretation:

explicit declaration that at the moment of creation,

C and scripting have been considered most important influences.

Already seen nod to scripting in VM Spec 2.17.1,

command line arguments sufficiently explain String[] args

but static and main aren't there yet, need to dig further...

Note while typing this - connecting C, scripting and VM Spec 1.2 with its nothing-of-Java - I feel like something familiar, something... object oriented is slowly passing away. Take my hand and keep movin' Don't slow down we're nearly there now

Keynote slides are available online: 20_Gosling_keynote.pdf, quite convenient for copying key points.

```
    page 3

        The Prehistory of Java
        * What shaped my thinking

    page 9

        NeWS
        * Networked Extensible Window System
        * A window system based on scripting....
          PostScript (!!)

    page 16

        A Big (but quiet) Goal:
          How close could I get to a
          "scripting" feel...

    page 19

        The original concept
        * Was all about building
          networks of things,
          orchestrated by a scripting
          language
        * (Unix shells, AppleScript, ...)

    page 20

        A Wolf in Sheeps Clothing
        * C syntax to make developers
          comfortable
```

A-ha! Let's look closer at C syntax.

The "hello, world" example...

```<code>main()
{
    printf("hello, world\n");
}
</code>```

...a function named main is being defined. The main function serves a special purpose in C programs; the run-time environment calls the main function to begin program execution.

...The main function actually has two arguments, int argc and char *argv[], respectively, which can be used to handle command line arguments...

Are we getting closer? you bet. It is also worth following "main" link from above quote:

the main function is where a program starts execution. It is responsible for the high-level organization of the program's functionality, and typically has access to the command arguments given to the program when it was executed.

My interpretation:

To be comfortable for C developer, program entry point has to be main.

Also, since Java requires any method to be in class, Class.main is

as close as it gets: static invocation, just class name and dot,

no constructors please - C knows nothing like that.

This also transitively applies to C#, taking into account

the idea of easy migration to it from Java.

Readers thinking that familiar program entry point doesn't matter are kindly invited to search and check Stack Overflow questions where guys coming from Java SE are trying to write Hello World for Java ME MIDP. Note MIDP entry point has no main nor static.

Conclusion

Based on above I would say that static, main and String[] args were at the moments of Java and C# creation most reasonable choices to define program entry point.

Appendix: I need your clothes, your boots and your motorcycle

Have to admit, reading VM Spec 2.17.1 was enormous fun.

...the command line

java Terminator Hasta la vista Baby!

will start a Java virtual machine by invoking the method main of class Terminator (a class in an unnamed package) and passing it an array containing the four strings "Hasta", "la", "vista", and "Baby!".

We now outline the steps the virtual machine may take to execute Terminator, as an example of the loading, linking, and initialization processes that are described further in later sections.

The initial attempt... discovers that the class Terminator is not loaded...

After Terminator is loaded, it must be initialized before main can be invoked, and a type (class or interface) must always be linked before it is initialized. Linking (§2.17.3) involves verification, preparation, and (optionally) resolution...

Verification (§2.17.3) checks that the loaded representation of Terminator is well formed...

Resolution (§2.17.3) is the process of checking symbolic references from class Terminator...

Symbolic references from Terminator oh yeah.

OwnerDisplayName: Konrad Rudolph

Body:
TL;DR

In Java, the reason of public static void main(String[] args) is that

Gosling wanted

the code written by someone experienced in C (not in Java)

to be executed by someone used to running PostScript on NeWS

For C#, the reasoning is transitively similar so to speak. Language designers kept the program entry point syntax familiar for programmers coming from Java. As C# architect Anders Hejlsberg puts it,

...our approach with C# has simply been to offer an alternative... to Java programmers...

Long version

expanding above and backed up with boring references.

java Terminator Hasta la vista Baby!

VM Spec, 2.17.1 Virtual Machine Start-up

...The manner in which the initial class is specified to the Java virtual machine is beyond the scope of this specification, but it is typical, in host environments that use command lines, for the fully qualified name of the class to be specified as a command-line argument and for subsequent command-line arguments to be used as strings to be provided as the argument to the method main. For example, using Sun's Java 2 SDK for Solaris, the command line

java Terminator Hasta la vista Baby!

will start a Java virtual machine by invoking the method main of class Terminator (a class in an unnamed package) and passing it an array containing the four strings "Hasta", "la", "vista", and "Baby!"...

...see also: Appendix: I need your clothes, your boots and your motorcycle

My interpretation:

execution targeted for use like typical scripts in command line interface.

important sidestep

...that helps avoid a couple of false traces in our investigation.

VM Spec, 1.2 The Java Virtual Machine

The Java virtual machine knows nothing of the Java programming language...

I noticed above when studying prior chapter - 1.1 History which I thought could be helpful (but turned out useless).

My interpretation:

execution is governed by VM spec alone, which

explicitly declares that it has nothing to do with Java language

=> OK to ignore JLS and anything Java language related at all

Gosling: a compromise between C and scripting language...

Based on above, I began searching the web for JVM history. Didn't help, too much garbage in results.

Then, I recalled legends about Gosling and narrowed down my search to Gosling JVM history.

Eureka! How The JVM Spec Came To Be

In this keynote from the JVM Languages Summit 2008, James Gosling discusses... Java's creation,... a compromise between C and scripting language...

My interpretation:

explicit declaration that at the moment of creation,

C and scripting have been considered most important influences.

Already seen nod to scripting in VM Spec 2.17.1,

command line arguments sufficiently explain String[] args

but static and main aren't there yet, need to dig further...

Note while typing this - connecting C, scripting and VM Spec 1.2 with its nothing-of-Java - I feel like something familiar, something... object oriented is slowly passing away. Take my hand and keep movin' Don't slow down we're nearly there now

Keynote slides are available online: 20_Gosling_keynote.pdf, quite convenient for copying key points.

    page 3

        The Prehistory of Java
        * What shaped my thinking

    page 9

        NeWS
        * Networked Extensible Window System
        * A window system based on scripting....
          PostScript (!!)

    page 16

        A Big (but quiet) Goal:
          How close could I get to a
          "scripting" feel...

    page 19

        The original concept
        * Was all about building
          networks of things,
          orchestrated by a scripting
          language
        * (Unix shells, AppleScript, ...)

    page 20

        A Wolf in Sheeps Clothing
        * C syntax to make developers
          comfortable

A-ha! Let's look closer at C syntax.

The "hello, world" example...

main()
{
    printf("hello, world\n");
}

...a function named main is being defined. The main function serves a special purpose in C programs; the run-time environment calls the main function to begin program execution.

...The main function actually has two arguments, int argc and char *argv[], respectively, which can be used to handle command line arguments...

Are we getting closer? you bet. It is also worth following "main" link from above quote:

the main function is where a program starts execution. It is responsible for the high-level organization of the program's functionality, and typically has access to the command arguments given to the program when it was executed.

My interpretation:

To be comfortable for C developer, program entry point has to be main.

Also, since Java requires any method to be in class, Class.main is

as close as it gets: static invocation, just class name and dot,

no constructors please - C knows nothing like that.

This also transitively applies to C#, taking into account

the idea of easy migration to it from Java.

Readers thinking that familiar program entry point doesn't matter are kindly invited to search and check Stack Overflow questions where guys coming from Java SE are trying to write Hello World for Java ME MIDP. Note MIDP entry point has no main nor static.

Conclusion

Based on above I would say that static, main and String[] args were at the moments of Java and C# creation most reasonable choices to define program entry point.

Appendix: I need your clothes, your boots and your motorcycle

Have to admit, reading VM Spec 2.17.1 was enormous fun.

...the command line

java Terminator Hasta la vista Baby!

will start a Java virtual machine by invoking the method main of class Terminator (a class in an unnamed package) and passing it an array containing the four strings "Hasta", "la", "vista", and "Baby!".

We now outline the steps the virtual machine may take to execute Terminator, as an example of the loading, linking, and initialization processes that are described further in later sections.

The initial attempt... discovers that the class Terminator is not loaded...

After Terminator is loaded, it must be initialized before main can be invoked, and a type (class or interface) must always be linked before it is initialized. Linking (§2.17.3) involves verification, preparation, and (optionally) resolution...

Verification (§2.17.3) checks that the loaded representation of Terminator is well formed...

Resolution (§2.17.3) is the process of checking symbolic references from class Terminator...

Symbolic references from Terminator oh yeah.