答:
As noted, svn log will get you this answer. But this really isn't suitable for time tracking -- just about all accounting systems need a hole for restatement, editing a svn commit description can be tricky if not impossible due to post-commit hooks.

You might want to look at something like redmine which integrates with SVN and has a time tracking feature built-in.

Title: using source control to create release notes?

Body:
Lets say i have an off the shelf eccomerce cart. I put all the code inside subversion. I start to make changes and check the code changes back in.

is it possible to then display each "check in" with the developer messages so that i can make release notes?

I would like to use this for actual quoted time.


问:
.Net Application & Database Modularity/Reuse
I'm looking for some guidance on how to architect an app with regards to modularity, separation of concerns and re-usability.

I'm working on an application (ASP.Net, C#) that has distinctly generic chunks of functionality, that I'd love to be able to lift out, all layers, into re-usable components. This means the module handles the database schema, data access, API, everything so that the next time I want to use it I can just register the module and hook into it.

Developing modules of re-usable functionality is a no-brainer, but what is really confusing me is what to do when it comes to handling a core re-usable database schema that serves the module's functionality.

In an ideal world, I would register a module and it would ensure that the associated database schema exists in the DB, by creating the schema if it didn't already. I would code my dependent functionality on the assumption that the tables exist calling the module's functionality through the DLL, agnostic of the database layer. Kind of like Enterprise Library's Caching/Logging Application Block, which can create a DB schema in the target DB to use as a data store.

My Questions is: What do you think is the best way to achieve this, firstly, in terms design architecture, and secondly solution structure. What patterns/frameworks do you know that exist & support this kind of thing?

My thoughts so far:

I mostly use Entity Framework and SQL Server DB Projects. I thought about a 'black box' approach to modules of functionality. I could use use a code-first approach in EF4, and use the ObjectContext to create a database when the module is initialized. However this means that all of the entities that my module encapsulates would be disconnected from the rest of the application because they belonged to an abstracted ObjectContext. Further - Creating appropriate indexes and references between domain entities and the module's entities would be impossible to do practically.

I've thought of adopting Enterprise Library and creating my own Application Blocks. I'm not sure how this would play nice with Entity Framework (if at all) though. I like the idea of building on proven patterns & practices to encapsulate established, reusable functionality.

I thought of abandoning Entity Framework for the Module, and just creating a separate DB schema for the module with its own set of stored procedures & ADO.Net. Then deploying the script at run-time if interrogation shows that it doesn't exist. But once again, for developing functionality outside of the module, I would want to use Entity Framework and I would have to use the module separately, disconnected from the domain ObjectContext.

Has anyone had experience developing these sorts of full-stack modules? What advice can you offer? Am I biting off more than I can chew?

答: I have tried a few times. My advice is "don't" -- trying to be everything to everyone means you are nothing to nobody. The best possible result is you end up recreating sharepoint after half a decade of hard work.</p>

OwnerDisplayName: Martaver

ContentLicense: CC BY-SA 3.0


问:
Benefits of classic OOP over Go-like language
I've been thinking a lot about language design and what elements would be necessary for an "ideal" programming language, and studying Google's Go has led me to question a lot of otherwise common knowledge.

Specifically, Go seems to have all of the interesting benefits from object oriented programming without actually having any of the structure of an object oriented language. There are no classes, only structures; there is no class/structure inheritance -- only structure embedding. There aren't any hierarchies, no parent classes, no explicit interface implementations. Instead, type casting rules are based on a loose system similar to duck-typing, such that if a struct implements the necessary elements of a "Reader" or a "Request" or an "Encoding", then you can cast it and use it as one.

Is there something about OOP as implemented in C++ and Java and C# that is inherently more capable, more maintainable, somehow more powerful that you have to give up when moving to a language like Go? What benefit do you have to give up to gain the simplicity that this new paradigm represents?

EDIT

Removed the "obsolete" question that readers seemed to get excessively hung up on and infuriated by.

The question is, what does the traditional object oriented paradigm (with hierarchies and such) as frequently seen in common language implementations have to offer that can't be done as easily in this simpler model? Or, in other words, if you were to design a language today, is there a reason you would want to include the concept of class hierarchies?

答:
I think your idea about OOP is quite a bit off:

I invented the term 'Object Oriented Programming' and this {Java and
  C++} is not what I had in mind.

  - Alan Kay.

The choice of typing (nominative subtyping, structural subtyping or duck typing - or a combination of those) is largely orthogonal to OOP. Inheritance and classes are entirely orthogonal to OOP. If you take some time to play with io you will come to see that.

Now you can ask which kind of type systems are "better", and which means of code reuse and combination are. And try to determine the advantages and drawbacks between the choices made in Simula (and later carried on in C++, Java and C#) and those made in Go. But these are all different and distinct questions.

Ultimately, OOP is a very vague concept and all attempts to implement it come in a huge variety of flavors. But to really simplify things, I'd say the core idea of OOP is to compose systems of SOLID subsystems. Now this absolutely blurs the line to other paradigms, but I'd speculate that that's the reason why multi-paradigm languages have risen in popularity recently and why Google has taken it's own shot at that with Go.


问:
How to handle estimates for programmers joining the team?
Iteration has already started, new programmer joins the team, task X has already been estimated to be 30 hours by a different developer.

What is the best practice in this situation?

new developer runs with the given estimate (the idea being that any discrepancy will be corrected for when velocity is calculated?)

new developer re-estimates task? (if so, what if it's significantly higher and no longer fits in the iteration?)

throw our hands up and go back to waterfall?

something else entirely?

答:
I would not add this person to this individual sprint. Instead give him another task to work on to get up to speed on the codebase (low-hanging bugfixes perhaps?).

Adding a new person to the team will likely slow down your progress on this particular goal since he will have to get used to your environment and learn how things work there. Incorporate him into the next sprint, with proper estimates based on the new team.


答:
What I say is:

New developer re-estimates the task. If it has to be moved out of the iteration then it gets moved out.

You don't know if the new developer is going to be able or not to do it in the time the original developer though it will take. And with agile methodologies is the developer that does the work the one that should say how long it will take.

Furthermore, I would apply a multiplier (how big depending on the developer), as the developer has to fit into the team/project/company.

Title: How to handle estimates for programmers joining the team?

Body:
Iteration has already started, new programmer joins the team, task X has already been estimated to be 30 hours by a different developer.

What is the best practice in this situation?

new developer runs with the given estimate (the idea being that any discrepancy will be corrected for when velocity is calculated?)

new developer re-estimates task? (if so, what if it's significantly higher and no longer fits in the iteration?)

throw our hands up and go back to waterfall?

something else entirely?


问:
Changes in licence in forked project what are my rights?
Hi I'm intrested in using the apparently now defunct app-mdi libray in a flex application for a paying customer. http://sourceforge.net/projects/appmdi/

It appears that the app-mdi project has been forked from flex-mdi and indeed the code has so much in common it would appear almost identical to the origional code.

Now in the original source flex-mdi the following licence appears in the source code

/* Copyright (c) 2007 FlexMDI Contributors.  See:

  http://code.google.com/p/flexmdi/wiki/ProjectContributors  Permission
  is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to
  deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute,
  sublicense, and/or sell copies of the Software, and to permit persons
  to whom the Software is furnished to do so, subject to the following
  conditions:  The above copyright notice and this permission notice
  shall be included in all copies or substantial portions of the
  Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

However in the app-mdi library on the same file the following licence appears.

Copyright (c) 2010, TRUEAGILE All rights reserved.

Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

Neither the name of the TRUEAGILE nor the names of its contributors may be used to endorse or promote products derived from this software
  without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */

Now I've no problem with the licence except for the line.

Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

The copyright notice in its entireity makes no sense in binary material. Specifically talking about redistobutions in the binary form.

Finally the question is what exactly has to be shown on web clients who access softare that utilises this library?

Also is changing the licence in this manner actually allowed?

答:
It says notice has to be produced in the documentation, not embedded in the binaries - though you must retain them in the source code. Nor is there anything to suggest that you must display it (though you may think displaying the disclaimer makes sense for other reasons).

As we have no idea as to what discussions took place between the copyright holder and TRUEAGILE or if TRUEAGILE bought the previous company etc, we cannot answer the question about changing the licence. But essentially the point is that if you are the copyright holder or have permission of the copyright holder you can change the licence to whatever you like.

You cannot retrospectively change the terms for previous licensees (unless the licence allowed that), but for the future you can do what you like.


答:
First off, I hear "Agile Task" and I think one to two days' work, not a week's. Tasks are what you break stories into when the story itself fits in the iteration, and it's a real rarity to have a story that cannot be broken down into smaller pieces.

Second, you're basically asking this new developer to hit the ground running. If he can be reasonably expected to jump right in and keep up the pace of the rest of the team, then the original estimate should hold. If he can't, he probably shouldn't be held to this estimate, at least not by himself.

Third, what's the situation? I'm pretty sure the situation was not that the team estimated their work, then someone walked out and you replaced him the next day. So, I'm thinking X guys on the team estimated this sprint's work and took in what they thought they could handle, and then you introduced the new guy and now there are X+1 guys to do the work originally committed to by X guys. Unless the team didn't pick their workload, and instead had the backlog crammed in by management, I would not be giving the new guy much to do this week. If the schedule was set by management, it's not Agile.

Personally, I would set this guy up to pair with a more experienced programmer for his first sprint (if your programmers don't pair all the time, which I'm inferring they don't from the fact that you're considering giving one task to one guy). By looking over his shoulder and asking questions, he'll start to learn the codebase, and if his general programming skill is up to snuff he'll be an effective code reviewer almost immediately, spotting bugs, inefficient code, etc etc.


问:
When to write an explicit return statement in Groovy?
At the moment I am working on a Groovy/Grails project (which I'm quite new in) and I wonder whether it is good practice to omit the return keyword in Groovy methods. As far as I know you have to explicitly insert the keyword i.e. for guard clauses, so should one use it also everywhere else? In my opinion the additional return keyword increases readability. Or is it something you just have to get used to? What is your experience with that topic?

Some examples:

```<code>def foo(boolean bar) {
    // Not consistent
    if (bar) {
        return positiveBar()
    }
    negativeBar()
}

def foo2() {
    // Special Grails example
    def entitiy = new Entity(foo: 'Foo', bar: 'Bar')
    entity.save flush: true
    // Looks strange to me this way
    entity
}
</code>```

答:
I certain would add the return, as it makes the intention clearer to any person (including yourself) who may come and update/maintain the code later on.

Otherwise it might look like a typing error.

The other thing is to remember to declare functions/closures that are expected to return a void as 'void' - again to make it clearer to future maintainers what you are trying to do.


问:
What are the design principles that promote testable code? (designing testable code vs driving design through tests)
Most of the projects that I work on consider development and unit testing in isolation which makes writing unit tests at a later instance a nightmare. My objective is to keep testing in mind during the high level and low level design phases itself.

I want to know if there are any well defined design principles that promote testable code. One such principle that I have come to understand recently is Dependency Inversion through Dependency injection and Inversion of Control.

I have read that there is something known as SOLID. I want to understand if following the SOLID principles indirectly results in code that is easily testable? If not, are there any well-defined design principles that promote testable code?

I am aware that there is something known as Test Driven Development. Although, I am more interested in designing code with testing in mind during the design phase itself rather than driving design through tests. I hope this makes sense.

One more question related to this topic is whether it's alright to re-factor an existing product/project and make changes to code and design for the purpose of being able to write a unit test case for each module?

答:
SOLID is an excellent start, in my experience, four of the aspects of SOLID really work well with unit testing.

Single Responsibility Principle - each class does one thing and one thing only.  Calculating a value, opening a file, parsing a string, whatever.  The amount of inputs and outputs, as well as decision points should therefore be very minimal.  Which makes it easy to write tests.

Liskov substitution principle - you should be able to substitute in stubs and mocks without altering the desirable properties (the expected results) of your code.

Interface segregation principle - separating contact points by interfaces makes it very easy to use a mocking framework such as Moq to create stubs and mocks.  Instead of having to rely on the concrete classes you are simply relying on something that implements the interface.

Dependency Injection Principle - This is what allows you to inject those stubs and mocks into your code either through a constructor, a property or a parameter in the method you want to test.

I would also look into different patterns, especially the factory pattern.  Let's say you have a concrete class that implements an interface.  You would create a factory to instantiate the concrete class, but return the interface instead.

```<code>public interface ISomeInterface
{
    int GetValue();
}

public class SomeClass : ISomeInterface
{
    public int GetValue()
    {
         return 1;
    }
}

public interface ISomeOtherInterface
{
    bool IsSuccess();
}

public class SomeOtherClass : ISomeOtherInterface
{
     private ISomeInterface m_SomeInterface;

     public SomeOtherClass(ISomeInterface someInterface)
     {
          m_SomeInterface = someInterface;
     }

     public bool IsSuccess()
     {
          return m_SomeInterface.GetValue() == 1;
     }
}

public class SomeFactory
{
     public virtual ISomeInterface GetSomeInterface()
     {
          return new SomeClass();
     }

     public virtual ISomeOtherInterface GetSomeOtherInterface()
     {
          ISomeInterface someInterface = GetSomeInterface();

          return new SomeOtherClass(someInterface);
     }
}
</code>```

In your tests you can Moq or some other mocking framework to override that virtual method and return an interface of your design.  But as far as the implementing code is concerned the factory has not changed.  You can also hide a lot of your implementation details this way, your implementing code doesn't care how the interface is built, all it cares about is getting an interface back.

If you want to expand on this a bit, I highly recommend reading The Art of Unit Testing.  It gives some great examples on how to use this principles, and it is a pretty quick read.

OwnerDisplayName: bot

Body:
SOLID is an excellent start, in my experience, four of the aspects of SOLID really work well with unit testing.

Single Responsibility Principle - each class does one thing and one thing only.  Calculating a value, opening a file, parsing a string, whatever.  The amount of inputs and outputs, as well as decision points should therefore be very minimal.  Which makes it easy to write tests.

Liskov substitution principle - you should be able to substitute in stubs and mocks without altering the desirable properties (the expected results) of your code.

Interface segregation principle - separating contact points by interfaces makes it very easy to use a mocking framework such as Moq to create stubs and mocks.  Instead of having to rely on the concrete classes you are simply relying on something that implements the interface.

Dependency Injection Principle - This is what allows you to inject those stubs and mocks into your code either through a constructor, a property or a parameter in the method you want to test.

I would also look into different patterns, especially the factory pattern.  Let's say you have a concrete class that implements an interface.  You would create a factory to instantiate the concrete class, but return the interface instead.

public interface ISomeInterface
{
    int GetValue();
}

public class SomeClass : ISomeInterface
{
    public int GetValue()
    {
         return 1;
    }
}

public interface ISomeOtherInterface
{
    bool IsSuccess();
}

public class SomeOtherClass : ISomeOtherInterface
{
     private ISomeInterface m_SomeInterface;

     public SomeOtherClass(ISomeInterface someInterface)
     {
          m_SomeInterface = someInterface;
     }

     public bool IsSuccess()
     {
          return m_SomeInterface.GetValue() == 1;
     }
}

public class SomeFactory
{
     public virtual ISomeInterface GetSomeInterface()
     {
          return new SomeClass();
     }

     public virtual ISomeOtherInterface GetSomeOtherInterface()
     {
          ISomeInterface someInterface = GetSomeInterface();

          return new SomeOtherClass(someInterface);
     }
}

In your tests you can Moq or some other mocking framework to override that virtual method and return an interface of your design.  But as far as the implementing code is concerned the factory has not changed.  You can also hide a lot of your implementation details this way, your implementing code doesn't care how the interface is built, all it cares about is getting an interface back.

If you want to expand on this a bit, I highly recommend reading The Art of Unit Testing.  It gives some great examples on how to use this principles, and it is a pretty quick read.


问:
function works fine without return value in c++
I forgot to write return 'a'; in the show function and return 0; in main function but it works fine in Code::Blocks.

```<code>#include <iostream>

using namespace std;

char show()
{
  cout<<"this is show function"<<endl;
}

int main()
{
  show();
}
</code>```

I am using Code::Blocks 10.05 in Ubuntu 12.04.
Why does this code work fine in Code::Blocks but not in Turbo C++?

答:
The compiler should have issued at least a warning for not including a return statement in show(). I would expect the compiler to issue a message if the warning level of the compiler is increased. As other's have indicated, not returning a value is undefined behavior according to the standard.

This program will also not have a run time error, primarily because the results of show() are never used. If you used the results of show(), you will likely get some unexpected result, including what you expected.

ContentLicense: CC BY-SA 4.0


问:
Factors to be Considered for Software Risk Management
What are the risk factors that we need to consider while planning for a software project.</p>

答:
Do you have the right mix of people? Are all your developers application developers in a data-centric project? Do you need a database designer, a QA person or a UI specialist  instead of only hiring people with the same skill mix?

Do you have adequate hardware to support the project? This is especially true if you are creating a high volume system or if you are too cheap to buy development servers in addition to production servers.

Have you set up backups of your databases? Just having the code to recreate a database is not enough, you need to be keeping the data as well even on dev.

Are your developers working with a small data set instead of one the size that production will be? This almost guarantees production performance issues because queries that work well on a small data set often do not on a large set. I've seen a lot of failed production updates that had to be immediately rolled back due to this particular problem.

Are you defining what to do in edge cases and are you testing them? For instance, I've seen projects where nobody ever defined what happens what an approval is required and the approver says no.

Will you be forced into making bad design choices in order to meet unreasonable deadlines?

In your planning for the project did you consider that people take vacation and sick days, get jury duty, take bereavement leave etc? You need to plan not just for people leaving the project but for the day-to-day time off people get.

ContentLicense: CC BY-SA 2.5


问:
How to make Ninject inject an MVC view model?
How do I configure Ninject so it injects an instance in a view model?

PS. It is an abstracted service to help with validation, so I am not trying to burden the model with too much responsibilities.

答:
Refer to this SO question - https://stackoverflow.com/questions/8176654/di-ninject-working-for-controllers-but-not-view-model, which points to this link - http://bradwilson.typepad.com/blog/2010/10/service-location-pt5-idependencyresolver.html.

I also had the same issue. For that I extended my NinjectControllerFactory class to provide me with an instance of the required dependency. I blogged about this here - http://blog.thekfactor.info/posts/dependency-injection/.

I may have to look in to the link from the SO post too and see if that's a better alternative.


答:
With regards to your statement

"In an ideal world, I would register a module and it would ensure that the associated database schema exists in the DB."

If I get the meaning correctly, then I don't think that this requirement is a common practice in most business application. A piece of code has to make assumptions otherwise the options are too many. For example, I don't think that it is practical to check if the "Customer" table exists in the database and it has the correct key, and if the "Invoice" table exists and if there is a relationship exits between them then do action1...and so on. What most of the systems do is fix the schema and re-use the dlls (and/or stored procedures).

Title: .Net Application & Database Modularity/Reuse

Body:
I'm looking for some guidance on how to architect an app with regards to modularity, separation of concerns and re-usability.

I'm working on an application (ASP.Net, C#) that has distinctly generic chunks of functionality, that I'd love to be able to lift out, all layers, into re-usable components. This means the module handles the database schema, data access, API, everything so that the next time I want to use it I can just register the module and hook into it.

Developing modules of re-usable functionality is a no-brainer, but what is really confusing me is what to do when it comes to handling a core re-usable database schema that serves the module's functionality.

In an ideal world, I would register a module and it would ensure that the associated database schema exists in the DB, by creating the schema if it didn't already. I would code my dependent functionality on the assumption that the tables exist calling the module's functionality through the DLL, agnostic of the database layer. Kind of like Enterprise Library's Caching/Logging Application Block, which can create a DB schema in the target DB to use as a data store.

My Questions is: What do you think is the best way to achieve this, firstly, in terms design architecture, and secondly solution structure. What patterns/frameworks do you know that exist & support this kind of thing?

My thoughts so far:

I mostly use Entity Framework and SQL Server DB Projects. I thought about a 'black box' approach to modules of functionality. I could use use a code-first approach in EF4, and use the ObjectContext to create a database when the module is initialized. However this means that all of the entities that my module encapsulates would be disconnected from the rest of the application because they belonged to an abstracted ObjectContext. Further - Creating appropriate indexes and references between domain entities and the module's entities would be impossible to do practically.

I've thought of adopting Enterprise Library and creating my own Application Blocks. I'm not sure how this would play nice with Entity Framework (if at all) though. I like the idea of building on proven patterns & practices to encapsulate established, reusable functionality.

I thought of abandoning Entity Framework for the Module, and just creating a separate DB schema for the module with its own set of stored procedures & ADO.Net. Then deploying the script at run-time if interrogation shows that it doesn't exist. But once again, for developing functionality outside of the module, I would want to use Entity Framework and I would have to use the module separately, disconnected from the domain ObjectContext.

Has anyone had experience developing these sorts of full-stack modules? What advice can you offer? Am I biting off more than I can chew?


问:
Recognizing text fields according to their label value
I have an application who has text fields (not select, not checkbox or other types) where an user can enter some value, like this:

ISBN and E-Mail are the label of each input.

Now I have to automatically test these inputs according to their label. The question is: how to recognize that, for example, the first input requires an ISBN code? I programmed something like this:

turn the label value to lowercase

check if the label value contains isbn

if so set the field value to a random ISBN code (i.e.: 1234567890), else set it to a random value (default)

For the email field:

turn the label value to lowercase

check if the label value contains e-mail or email or mail

if so set the field value to a random email (i.e.: abcd@abcd.com), else set it to a random value (default)

And so on for each text field I encounter.

Is that reliable? How can I improve the "recognizing part"? I know only the label value and the field value (what is already written in the field by default) for each text input.

答:
I'm guessing that you've given the text fields useful names (other than just textfield1 or whatever)

NOTE: I'm coming at this from a winforms point of view. Since you didn't say what framework and/or language you're using to develop this, I'm going to assume that you can name the textfields. I also note that you haven't said which framework you are using to test with, so most answers will be vague and generic

How about just adding none values into the text fields?

If it where me, I'd have named the textfields tfISBN and tfEMail, and would just inject known values directly into their text value.

For instance

```<code>tfISBN.text = "1157061346" //KnR C - ISBN10
tfEmail.text = "user@domain.com"
//a different set of data
tfISNB.text = "978-0321751041" //Art of Computer Programming - ISBN13
tfEMail = "donald.knuth@doesnt-have-email.goaway"
</code>```

Or, of course, since you're testing, you could also check to see if you can populate these text fields with invalid data. Just move down the form/UI (simulate tab stops) and place text into each field and see if the back-end code can handle erroneous values.

Body:
I'm guessing that you've given the text fields useful names (other than just textfield1 or whatever)

NOTE: I'm coming at this from a winforms point of view. Since you didn't say what framework and/or language you're using to develop this, I'm going to assume that you can name the textfields. I also note that you haven't said which framework you are using to test with, so most answers will be vague and generic

How about just adding none values into the text fields?

If it where me, I'd have named the textfields tfISBN and tfEMail, and would just inject known values directly into their text value.

For instance

tfISBN.text = "1157061346" //KnR C - ISBN10
tfEmail.text = "user@domain.com"
//a different set of data
tfISNB.text = "978-0321751041" //Art of Computer Programming - ISBN13
tfEMail = "donald.knuth@doesnt-have-email.goaway"

Or, of course, since you're testing, you could also check to see if you can populate these text fields with invalid data. Just move down the form/UI (simulate tab stops) and place text into each field and see if the back-end code can handle erroneous values.


问:
Writing selenium tests, should I just get it done or get it right?
I'm attempting to drive my user interface (heavy on javascript) through selenium.  I've already tested the rest of my ajax interaction with selenium successfully.  However, this one particular method seems to be eluding me because I can't seem to fake the correct click event.  I could solve this problem by simply waiting in the test for the user to click a point and then continuing with the test but this seems like a cop out.  But I'm really running out of time on my deadline to have this done and working.  Should I just get this done and move on or should I spend the extra (unknown) amount of time to fix this problem and be able to have my selenium tests 100% automated?</p>

答:
If the tests aren't 100% automated, they lose a tremendous amount of value. They won't be run reliably, and are a lot more error prone because of the human interaction. If you can't get it 100% automated, remove that test completely, even if it means not testing that piece of functionality for now.

As an aside, have you asked for help on stackoverflow? They may be able to give you a fairly quick solution.


答:
Yes, SOLID is a very good way to design code that can be easily tested. As a short primer:

S - Single Responsibility Principle: An object should do exactly one thing, and should be the only object in the codebase that does that one thing. For instance, take a domain class, say an Invoice. The Invoice class should represent the data structure and business rules of an invoice as used in the system. It should be the only class that represents an invoice in the codebase. This can be further broken down to say that a method should have one purpose and should be the only method in the codebase that meets this need.

By following this principle, you increase the testability of your design by decreasing the number of tests you have to write that test the same functionality on different objects, and you also typically end up with smaller pieces of functionality that are easier to test in isolation.

O - Open/Closed Principle: A class should be open to extension, but closed to change. Once an object exists and works correctly, ideally there should be no need to go back into that object to make changes that add new functionality. Instead, the object should be extended, either by deriving it or by plugging new or different dependency implementations into it, to provide that new functionality. This avoids regression; you can introduce the new functionality when and where it is needed, without changing the behavior of the object as it is already used elsewhere.

By adhering to this principle, you generally increase the code's ability to tolerate "mocks", and you also avoid having to rewrite tests to anticipate new behavior; all existing tests for an object should still work on the un-extended implementation, while new tests for new functionality using the extended implementation should also work.

L - Liskov Substitution Principle: A class A, dependent upon class B, should be able to use any X:B without knowing the difference. This basically means that anything you use as a dependency should have similar behavior as seen by the dependent class. As a short example, say you have an IWriter interface that exposes Write(string), which is implemented by ConsoleWriter. Now you have to write to a file instead, so you create FileWriter. In doing so, you must make sure that FileWriter can be used the same way ConsoleWriter did (meaning that the only way the dependent can interact with it is by calling Write(string)), and so additional information that FileWriter may need to do that job (like the path and file to write to) must be provided from somewhere else than the dependent.

This is huge for writing testable code, because a design that conforms to the LSP can have a "mocked" object substituted for the real thing at any point without changing expected behavior, allowing for small pieces of code to be tested in isolation with the confidence that the system will then work with the real objects plugged in.

I - Interface Segregation Principle: An interface should have as few methods as is feasible to provide the functionality of the role defined by the interface. Simply put, more smaller interfaces are better than fewer larger interfaces. This is because a large interface has more reasons to change, and causes more changes elsewhere in the codebase that may not be necessary.

Adherence to ISP improves testability by reducing the complexity of systems under test and of dependencies of those SUTs. If the object you are testing depends on an interface IDoThreeThings which exposes DoOne(), DoTwo() and DoThree(), you must mock an object that implements all three methods even if the object only uses the DoTwo method. But, if the object depends only on IDoTwo (which exposes only DoTwo), you can more easily mock an object that has that one method.

D - Dependency Inversion Principle: Concretions and abstractions should never depend on other concretions, but on abstractions. This principle directly enforces the tenet of loose coupling. An object should never have to know what an object IS; it should instead care what an object DOES. So, the use of interfaces and/or abstract base classes is always to be preferred over the use of concrete implementations when defining properties and parameters of an object or method. That allows you to swap one implementation for another without having to change the usage (if you also follow LSP, which goes hand in hand with DIP).

Again, this is huge for testability, as it allows you, once again, to inject a mock implementation of a dependency instead of a "production" implementation into your object being tested, while still testing the object in the exact form it will have while in production. This is key to unit testing "in isolation".

Title: What are the design principles that promote testable code? (designing testable code vs driving design through tests)

Body:
Most of the projects that I work on consider development and unit testing in isolation which makes writing unit tests at a later instance a nightmare. My objective is to keep testing in mind during the high level and low level design phases itself.

I want to know if there are any well defined design principles that promote testable code. One such principle that I have come to understand recently is Dependency Inversion through Dependency injection and Inversion of Control.

I have read that there is something known as SOLID. I want to understand if following the SOLID principles indirectly results in code that is easily testable? If not, are there any well-defined design principles that promote testable code?

I am aware that there is something known as Test Driven Development. Although, I am more interested in designing code with testing in mind during the design phase itself rather than driving design through tests. I hope this makes sense.

One more question related to this topic is whether it's alright to re-factor an existing product/project and make changes to code and design for the purpose of being able to write a unit test case for each module?


问:
Why is x=x++ undefined?
It's undefined because the it modifies x twice between sequence points. The standard says it's undefined, therefore it's undefined.

That much I know.

But why?

My understanding is that forbidding this allows compilers to optimize better. This could have made sense when C was invented, but now seems like a weak argument.

If we were to reinvent C today, would we do it this way, or can it be done better?

Or maybe there's a deeper problem, that makes it hard to define consistent rules for such expressions, so it's best to forbid them?

So suppose we were to reinvent C today. I'd like to suggest simple rules for expressions such as x=x++, which seem to me to work better than the existing rules.

I'd like to get your opinion on the suggested rules compared to the existing ones, or other suggestions.

Suggested Rules:

Between sequence points, order of evaluation is unspecified.

Side effects take place immediately.

There's no undefined behavior involved. Expressions evaluate to this value or that, but surely won't format your hard disk (strangely, I've never seen an implementation where x=x++ formats the hard disk).

Example Expressions

x=x++ - Well defined, doesn't change x.

First, x is incremented (immediately when x++ is evaluated), then it's old value is stored in x.

x++ + ++x - Increments x twice, evaluates to 2*x+2.

Though either side may be evaluated first, the result is either x + (x+2) (left side first) or (x+1) + (x+1) (right side first).

x = x + (x=3) - Unspecified, x set to either x+3 or 6.

If the right side is evaluated first, it's x+3. It's also possible that x=3 is evaluated first, so it's 3+3. In either case, the x=3 assignment happens immediately when x=3 is evaluated, so the value stored is overwritten by the other assignment.

x+=(x=3) - Well defined, sets x to 6.

You could argue that this is just shorthand for the expression above.

But I'd say that += must be executed after x=3, and not in two parts (read x, evaluate x=3, add and store new value).

What's the Advantage?

Some comments raised this good point.

I certainly don't think expressions such as x=x++ should be used in any normal code.

Actually, I'm much more strict than that - I think the only good usage for x++ in as x++; alone.

However, I think the language rules must be as simple as possible. Otherwise programmers just don't understand them. the rule forbidding changing a variable twice between sequence points is certainly a rule most programmers don't understand.

A very basic rule is this:

If A is valid, and B is valid, and they're combined in a valid way, the result is valid.

x is a valid L-value, x++ is a valid expression, and = is a valid way to combine an L-value and an expression, so how come x=x++ isn't legal?

The C standard makes an exception here, and this exception complicates the rules. You can search stackoverflow.com and see how much this exception confuses people.

So I say - get rid of this confusion.

=== Summary of Answers ===

Why do that?

I tried to explain in the section above - I want C rules to be simple.

Potential for optimization:

This does take some freedom from the compiler, but I didn't see anything that convinced me that it might be significant.

Most optimizations can still be done. For example, a=3;b=5; can be reordered, even though the standard specifies the order. Expressions such as a=b[i++] can still be optimized similarly.

You can't change the existing standard.

I admit, I can't. I never thought I can actually go ahead and change standards and compilers. I only wanted to think if things could have been done differently.

答:
First, let's take a look at the definition of undefined behavior:

3.4.3

1 undeﬁned behavior

behavior, upon use of a nonportable or erroneous program construct or of erroneous data,
for which this International Standard imposes no requirements

2 NOTE Possible undeﬁned behavior ranges from ignoring the situation completely with unpredictable
results, to behaving during translation or program execution in a documented manner characteristic of the
environment (with or without the issuance of a diagnostic message), to terminating a translation or
execution (with the issuance of a diagnostic message).

3 EXAMPLE An example of undeﬁned behavior is the behavior on integer overﬂow

So in other words, "undefined behavior" simply means that the compiler is free to handle the situation any way it wants to, and any such action is considered "correct".

The root of the issue under discussion is the following clause:

6.5 Expressions

...

3 The grouping of operators and operands is indicated by the syntax.
74)
Except as speciﬁed
later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation
of subexpressions and the order in which side effects take place are both unspeciﬁed.

Emphasis added.

Given an expression like

```<code>x = a++ * --b / (c + ++d);
</code>```

the subexpressions a++, --b, c, and ++d may be evaluated in any order.  Furthermore, the side effects of a++, --b, and ++d may be applied at any point before the next sequence point (IOW, even if a++ is evaluated before --b, it's not guaranteed that a will be updated  before --b is evaluated).  Like others have said, the rationale for this behavior is to give the implementation the freedom to reorder operations in an optimal manner.

Because of this, however, expressions like

```<code>x = x++
y = i++ * i++
a[i] = i++
*p++ = -*p    // this one bit me just yesterday
</code>```

etc., will yield different results for different implementations (or for the same implementation with different optimization settings, or based on the surrounding code, etc.).

The behavior is left undefined so that the compiler is under no obligation to "do the right thing", whatever that may be.  The cases above are easy enough to catch, but there a non-trivial number of cases that would be difficult to impossible to catch at compile time.

Obviously, you can design a language such that order of evaluation and the order in which side effects are applied are strictly defined, and both Java and C# do so, largely to avoid the issues that the C and C++ definitions lead to.

So, why hasn't this change been made to C after 3 standard revisions?  First of all, there's 40 years' worth of legacy C code out there, and it's not guaranteed that such a change won't break that code.  It puts a bit of a burden on compiler writers, as such a change would immediately make all existing compilers non-conforming; everybody'd have to make significant rewrites.  And even on fast, modern CPUs, it's still possible to realize real performance gains by tweaking order of evaluation.

Title: Why is x=x++ undefined?

Body:
First, let's take a look at the definition of undefined behavior:

3.4.3

1 undeﬁned behavior

behavior, upon use of a nonportable or erroneous program construct or of erroneous data,
for which this International Standard imposes no requirements

2 NOTE Possible undeﬁned behavior ranges from ignoring the situation completely with unpredictable
results, to behaving during translation or program execution in a documented manner characteristic of the
environment (with or without the issuance of a diagnostic message), to terminating a translation or
execution (with the issuance of a diagnostic message).

3 EXAMPLE An example of undeﬁned behavior is the behavior on integer overﬂow

So in other words, "undefined behavior" simply means that the compiler is free to handle the situation any way it wants to, and any such action is considered "correct".

The root of the issue under discussion is the following clause:

6.5 Expressions

...

3 The grouping of operators and operands is indicated by the syntax.
74)
Except as speciﬁed
later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation
of subexpressions and the order in which side effects take place are both unspeciﬁed.

Emphasis added.

Given an expression like

x = a++ * --b / (c + ++d);

the subexpressions a++, --b, c, and ++d may be evaluated in any order.  Furthermore, the side effects of a++, --b, and ++d may be applied at any point before the next sequence point (IOW, even if a++ is evaluated before --b, it's not guaranteed that a will be updated  before --b is evaluated).  Like others have said, the rationale for this behavior is to give the implementation the freedom to reorder operations in an optimal manner.

Because of this, however, expressions like

x = x++
y = i++ * i++
a[i] = i++
*p++ = -*p    // this one bit me just yesterday

etc., will yield different results for different implementations (or for the same implementation with different optimization settings, or based on the surrounding code, etc.).

The behavior is left undefined so that the compiler is under no obligation to "do the right thing", whatever that may be.  The cases above are easy enough to catch, but there a non-trivial number of cases that would be difficult to impossible to catch at compile time.

Obviously, you can design a language such that order of evaluation and the order in which side effects are applied are strictly defined, and both Java and C# do so, largely to avoid the issues that the C and C++ definitions lead to.

So, why hasn't this change been made to C after 3 standard revisions?  First of all, there's 40 years' worth of legacy C code out there, and it's not guaranteed that such a change won't break that code.  It puts a bit of a burden on compiler writers, as such a change would immediately make all existing compilers non-conforming; everybody'd have to make significant rewrites.  And even on fast, modern CPUs, it's still possible to realize real performance gains by tweaking order of evaluation.


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答: Always the design. With the code it's worth going through the developer setup steps (checking out the source, getting the project built, making any configuration changes required) but there's no point trying to learn an application's structure from its code. That only tells you what the structure is, not why the structure is or what the other developers think the highlights and bad points are of the architecture. Those you learn from whiteboard diagrams and chats with the developers.


问:
Is WCF a good fit for this problem?
I'm working to implement a data service solution that has 2 request functions but can respond with one of 3 transmission types:

x12 EDI

HTTP MIME multipart

SOAP/XML + WSDL

I would also need to include logging and username/password authentication to the services. I'm in the very early learning stages of WCF. Is WCF a good fit for this?

答:
You might want to check out FubuMVC too - at my previous job we implemented something pretty similar over that stack; it has really powerful composability, which means that you can conditionally add behaviors like logging/auditing/authentication and adding a formatter to format the output correctly is simply a matter of putting the behavior into the behavior chain. It's also convention driven, so it's very flexible.

All of that said, I can say that WCF Data Services specifically isn't the right solution (one of your tags) but WCF would probably meet your needs and comes with a better support agreement than FubuMVC.

Title: Is WCF a good fit for this problem?


问:
const vs. readonly for a singleton
I have a singleton that anchors together some different data structures.  Part of what I expose through that singleton are some lists and other objects, which represent the necessary keys or columns in order to connect the linked data structures.  I doubt that anyone would try to change these objects through a different module, but I want to explicitly protect them from that risk.  So I'm currently using a "readonly" modifier on those objects*.

I'm using readonly instead of const with the lists as I read that using const will embed those items in the referencing assemblies and will therefore trigger a rebuild of those referencing assemblies if / when the list(s) is/are modified.  This seems like a tighter coupling than I would want between the modules, but I wonder if I'm obsessing over a moot point. (This is question #2 below)

The alternative I see to using "readonly" is to make the variables private and then wrap them with a public get.  I'm struggling to see the advantage of this approach as it seems like wrapper code that doesn't provide much additional benefit.  (This is question #1 below)

It's highly unlikely that we'll change the contents or format of the lists - they're a compilation of things to avoid using magic strings all over the place.  Unfortunately, not all the code has converted over to using this singleton's presentation of those strings.

Likewise, I don't know that we'd change the containers / classes for the lists.  So while I normally argue for the encapsulations advantages a get wrapper provides, I'm just not feeling it in this case.

A representative sample of my singleton

```<code>public sealed class mySingl
{
    private static volatile mySingl sngl;
    private static object lockObject = new Object();

    public readonly Dictionary<string, string> myDict = new Dictionary<string, string>()
    {
        {"I", "index"},
        {"D", "display"},
    };

    public enum parms
    {
        ABC = 10,
        DEF = 20,
        FGH = 30
    };

    public readonly List<parms> specParms = new List<parms>()
    {
        parms.ABC,
        parms.FGH
    };

    public static mySingl Instance
    {
        get
        {
            if(sngl == null)
            {
                lock(lockObject)
                {
                    if(sngl == null)
                        sngl = new mySingl();
                }
            }
            return sngl;
        }
    }

    private mySingl()
    {
        doSomething();
    }
}
</code>```

Questions:

Am I taking the most reasonable approach in this case?

Should I be worrying about const vs. readonly?

is there a better way of providing this information?

To address some additional concerns:

First off, I understand there are folk who oppose the use of singletons. I think it's an appropriate use in this case as it's constant state information, but I'm open to differing opinions / solutions. (See The singleton pattern and When should the singleton pattern not be used?)

Second, for a broader audience:  C++/CLI has a similar keyword to readonly with initonly, so this isn't strictly a C# type question.
(Literal field versus constant variable in C++/CLI)

Sidenote: A discussion of some of the nuances on using const or readonly.

答:
Given your code, I have two concerns.

First, readonly references to mutable child objects (like collections) do not make the properties of the child immutable.

```<code>public class Foo
{
   public readonly List<int> Bar = new List<int>{1,2,3};
}

...

var foo = new Foo();

//You may enumerate Bar and read its indices
foreach(int baz in foo.Bar) Console.WriteLine(baz.ToString());

var bob = foo.Bar[1];

//this is illegal because the reference is readonly
foo.Bar = new List<int>{4,5,6};

//but the properties of the immutable reference are still mutable, so this is fine:
foo.Bar.Clear();
foo.Bar.Add(4);
foo.Bar.Add(5);
foo.Bar.Add(6);
</code>```

If you want a truly immutable child object, you have to make the reference immutable AND make sure the object itself is immutable. For that, you typically want to create or use a read-only version of your child and return that instead:

```<code>public class Foo
{
   private readonly List<int> bar = new List<int>{1,2,3};

   public ReadOnlyCollection<int> Bar { get { return bar.AsReadOnly(); } }
}

...

var foo = new Foo();

//You may still enumerate and index Bar
foreach(int baz in foo.Bar) Console.WriteLine(baz.ToString());

var bob = foo.Bar[1];

//this is illegal because there's no setter
foo.Bar = new List<int>{4,5,6};

//And these are also illegal because ReadOnlyCollection doesn't expose any such methods:
foo.Bar.Clear();
foo.Bar.Add(4);
foo.Bar.Add(5);
foo.Bar.Add(6);
</code>```

Second, the locked, double-checked instantiation of the singleton is (much) better than nothing for making it thread-safe, but there are still some cases where this can fail to prevent double-instantiation. Microsoft instead recommends use of a static readonly field with instantiation defined:

```<code>public sealed class MySingl
{
   public static readonly MySingl Instance = new MySingl();

   private MySingl() { ... }
}
</code>```

Microsoft guarantees an implementation like this to be thread-safe in the Microsoft CLR; statics are instantiated just-in-time and the CLR has internal mechanisms to block other threads that need this reference while it's being created.

Title: const vs. readonly for a singleton

Body:
Given your code, I have two concerns.

First, readonly references to mutable child objects (like collections) do not make the properties of the child immutable.

public class Foo
{
   public readonly List<int> Bar = new List<int>{1,2,3};
}

...

var foo = new Foo();

//You may enumerate Bar and read its indices
foreach(int baz in foo.Bar) Console.WriteLine(baz.ToString());

var bob = foo.Bar[1];

//this is illegal because the reference is readonly
foo.Bar = new List<int>{4,5,6};

//but the properties of the immutable reference are still mutable, so this is fine:
foo.Bar.Clear();
foo.Bar.Add(4);
foo.Bar.Add(5);
foo.Bar.Add(6);

If you want a truly immutable child object, you have to make the reference immutable AND make sure the object itself is immutable. For that, you typically want to create or use a read-only version of your child and return that instead:

public class Foo
{
   private readonly List<int> bar = new List<int>{1,2,3};

   public ReadOnlyCollection<int> Bar { get { return bar.AsReadOnly(); } }
}

...

var foo = new Foo();

//You may still enumerate and index Bar
foreach(int baz in foo.Bar) Console.WriteLine(baz.ToString());

var bob = foo.Bar[1];

//this is illegal because there's no setter
foo.Bar = new List<int>{4,5,6};

//And these are also illegal because ReadOnlyCollection doesn't expose any such methods:
foo.Bar.Clear();
foo.Bar.Add(4);
foo.Bar.Add(5);
foo.Bar.Add(6);

Second, the locked, double-checked instantiation of the singleton is (much) better than nothing for making it thread-safe, but there are still some cases where this can fail to prevent double-instantiation. Microsoft instead recommends use of a static readonly field with instantiation defined:

public sealed class MySingl
{
   public static readonly MySingl Instance = new MySingl();

   private MySingl() { ... }
}

Microsoft guarantees an implementation like this to be thread-safe in the Microsoft CLR; statics are instantiated just-in-time and the CLR has internal mechanisms to block other threads that need this reference while it's being created.


问:
Caching strategies for entities and collections
We currently have an application framework in which we automatically cache both entities and collections of entities at the business layer (using .NET cache). So the method GetWidget(int id) checks the cache using a key Widget_Id_{0} before hitting the database, and the method GetWidgetsByStatusId(int statusId) checks the cache using Widgets_Collections_ByStatusId_{0}. If the objects are not in the cache they are retrieved from the database and added to the cache.

This approach is obviously quick for read scenarios, and as a blanket approach is quick for us to implement, but requires large numbers of cache keys to be purged when CRUD operations are carried out on entities. Obviously as additional methods are added this impacts performance and the benefits of caching diminish.

I'm interested in alternative approaches to handling caching of collections. I know that NHibernate caches a list of the identifiers in the collection rather than the actual entities. Is this an approach other people have tried - what are the pros and cons?

In particular I am looking for options that optimise performance and can be implemented automatically through boilerplate generated code (we have our own code generation tool). I know some people will say that caching needs to be done by hand each time to meet the needs of the specific situation but I am looking for something that will get us most of the way automatically.

答:
I have experimented with different approaches to object caching, and I see advantages to an approach where collections are cached as references rather than actual objects.

An example:

```<code>User GetUser(int ID);
ICollection<User> GetRecentUsers(int amount);
ICollection<User> GetActiveUsers(int amount);
void Update(User user);
</code>```

In this example, if all three "Get"-methods load, cache and return actual user data, the data will go stale whenever an update is made to an object contained in one of the collections.

Delegating cache responsibility

Flushing everything every time you do an update however will result in a pretty useless cache. So you need some way of knowing what has gone stale. Unfortunately, keeping track of this is no easy task.

Rather than trying to keep track on what data is located where, you could create a scheme where you delegate handling of data and keep cache logic in i single place.

In the example above GetUser(int ID) could be the only method allowed to actually load and cache user objects.

GetRecentUsers() and GetActiveUsers() would then be responsible for loading only a list of user IDs and call GetUser() to actually populate a collection of users before returning the result.

In this way, when you update a user object, you only have to invalidate exactly one cached object.

The list of IDs held by GetRecentUsers will be invalidated only when a new user joins the site etc.

This gives you a more clean approach to keeping your cache tidy. It does however introduce its own set up problems.

Pitfalls

If you start with a cold cache and load the 10 most recent users you will have a N+1 problem on your hands. Basically running a query to fetch the list of users, and 10 additional queries to populate the cache.

This can be a big problem depending on your data and setup. You can however take measures against these problems by doing pre-warming of the cache, or allowing for batch operations (which again introduces complexity).

There is no silver bullet. But I find the delegation approach useful when implemented with care.

Body:
I have experimented with different approaches to object caching, and I see advantages to an approach where collections are cached as references rather than actual objects.

An example:

User GetUser(int ID);
ICollection<User> GetRecentUsers(int amount);
ICollection<User> GetActiveUsers(int amount);
void Update(User user);

In this example, if all three "Get"-methods load, cache and return actual user data, the data will go stale whenever an update is made to an object contained in one of the collections.

Delegating cache responsibility

Flushing everything every time you do an update however will result in a pretty useless cache. So you need some way of knowing what has gone stale. Unfortunately, keeping track of this is no easy task.

Rather than trying to keep track on what data is located where, you could create a scheme where you delegate handling of data and keep cache logic in i single place.

In the example above GetUser(int ID) could be the only method allowed to actually load and cache user objects.

GetRecentUsers() and GetActiveUsers() would then be responsible for loading only a list of user IDs and call GetUser() to actually populate a collection of users before returning the result.

In this way, when you update a user object, you only have to invalidate exactly one cached object.

The list of IDs held by GetRecentUsers will be invalidated only when a new user joins the site etc.

This gives you a more clean approach to keeping your cache tidy. It does however introduce its own set up problems.

Pitfalls

If you start with a cold cache and load the 10 most recent users you will have a N+1 problem on your hands. Basically running a query to fetch the list of users, and 10 additional queries to populate the cache.

This can be a big problem depending on your data and setup. You can however take measures against these problems by doing pre-warming of the cache, or allowing for batch operations (which again introduces complexity).

There is no silver bullet. But I find the delegation approach useful when implemented with care.


问:
how to create java zip archives with a max file size limit
I need to write an algorithm in java (for an android app) to read a folder containing more folders and each of those containing images and audio files so the structure is this: mainDir/subfolders/myFile1.jpg

It must be in java, something like perl script is not an option. It would preferably be for the compressed archive in order to squeeze as many files as possible before mailing the zip. Just a normal zip (no jar).

My problem is that I need to limit the size of the archive to 16mb and at runtime, create as many archives as needed to contain all my files from my main mainDir folder. I tried several examples from the net, I read the java documentation, but I can't manage to understand and put it all together the way I need it.

Has someone done this before or has a link or an example for me? I resolved the reading of the files with a recursive method but I can't figure the logic for the zip creation.

EDIT: FileNotFoundException (no such file or directory) this was my initial post at Stack Overflow. I've got an answer to it, but I can't set the size of the ZipEntry and the logic doesn't work and also when extracting the my files from the zip I get the compression method not supported error.

答:
Are you using Java 7? If so then it has native support for Zip archives in the new NIO.2 APIs

The zip file system provider introduced in the Java SE 7 release is an implementation of a custom file system provider. The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider creates multiple file systems — one file system for each zip or JAR file.

The demo/nio/zipfs/src.zip file in your Java SE 7 installation contains the source code for the zip file system provider. It also contains the Demo.java class that shows how to use the zip file system provider...

You can use the factory methods of the java.nio.file.FileSystems class to create a new zip file system or to obtain a reference to an existing zip file system...


答:
In addition to the other answers, which focus on achieving a loose coupling, I'd like to say a word about testing complicated logic.

I once had to unit-test a class whose logic was intricate, with lots of conditionals, and where it was hard to understand the role of the fields.

I replaced this code with many small classes that represent a state machine. The logic became much simpler to follow, since the different states of the former class became explicit. Each state class were independent of the others, and so they were easily testable.

The fact that the states were explicit made it easier to enumerate all the possible paths of the code (the state transitions), and thus to write a unit-test for each one.

Of course, not every complex logic can be modeled as a state machine.


问:
amount of code in code review
In my experience, most teams in the company review the code of team member with a small amount
of code, always less than hundreds of lines.  Is it appropriate to review large amount of code, for example a module,  when the code is complete and ready to get reviewed once for all?</p>

答:
It's appropriate if it helps your team create a better product.

Some reasons that code reviews often focus on smaller chunks:

Properly reviewing a large amount of code requires each participant to spend quite a long time preparing, and that can be expensive.

The longer a review meeting goes (any meeting, really), the less people pay attention. Two hours is about as much as most people can stand, and keeping meetings shorter than that (say, an hour or 90 minutes tops) goes a long way toward making sure that everyone is at their best.

It's often not necessary to review every line. One reason to review code is to make sure that everyone is sticking to basically the same set of coding guidelines. A detailed review of a smaller amount of code works better for that purpose than a less detailed review of more code.

That said, if you find that reviewing more code is helpful, and if your team can stand it, then by all means give it a try. It'll help to make sure that there are some ground rules and someone acting as a facilitator to keep the meeting moving along. Also, consider having reviewers submit their comments beforehand so that you spend less time on nitpicky things like improper use of white space and more time discussing important and interesting issues.

Title: amount of code in code review


答:
The reason for the small code reviews is to maximize effectiveness.

Studies involving the Personal Software Process have found that reviewers are most effective, with respect to maximizing defects identified in the review, when they review no more than 150-200 source lines of code per hour. Given that empirical data, it becomes a matter of determining how long people can stay attentive. I don't have any empirical data, but I know my mind begins to wander after about 1 hour of reading something. To me, that indicates that code reviews should review less than 150 lines of code at a time.

Title: amount of code in code review

Body:
In my experience, most teams in the company review the code of team member with a small amount
of code, always less than hundreds of lines.  Is it appropriate to review large amount of code, for example a module,  when the code is complete and ready to get reviewed once for all?</p>


答:
The size limit (16 mb or whatever) does not enforce you to have archive size as close to it as possible.

Assuming that you are allowed to create archives of smaller size, here is the "first iteration" solution - dead simple, but meets your requirements: just zip every file into separate archive.

myFile1 -> archive1.zip

myFile2 -> archive2.zip

etc

Now, if you want it a bit less dumb, use the sum of current archive size (Deflater.getBytesWritten()) and next uncompressed file size to decide if it's time to switch to creating new archive.

myFile1 -> archive1.zip

size of archive1.zip plus myFile2 within limit -> add myFile2 to archive1

size of archive1.zip plus myFile3 exceeds limit -> add myFile3 to new zip, archive2

Yeah there is a chance that adding compressed myFile3 to archive1 will remain within limit, but why bother?

etc

Title: how to create java zip archives with a max file size limit

Body:
I need to write an algorithm in java (for an android app) to read a folder containing more folders and each of those containing images and audio files so the structure is this: mainDir/subfolders/myFile1.jpg

It must be in java, something like perl script is not an option. It would preferably be for the compressed archive in order to squeeze as many files as possible before mailing the zip. Just a normal zip (no jar).

My problem is that I need to limit the size of the archive to 16mb and at runtime, create as many archives as needed to contain all my files from my main mainDir folder. I tried several examples from the net, I read the java documentation, but I can't manage to understand and put it all together the way I need it.

Has someone done this before or has a link or an example for me? I resolved the reading of the files with a recursive method but I can't figure the logic for the zip creation.

EDIT: FileNotFoundException (no such file or directory) this was my initial post at Stack Overflow. I've got an answer to it, but I can't set the size of the ZipEntry and the logic doesn't work and also when extracting the my files from the zip I get the compression method not supported error.


答:
First you have to understand that it's not just x=x++ that is undefined. Nobody cares about x=x++, since no matter what you would define it to there's no point to it. What's undefined is more like "a=b++ where a and b happen to be the same" - i.e.

```<code>void f(int *a, int *b) {
    *a = (*b)++;
}
int i;
f(&i, &i);
</code>```

There several different ways the function might be implemented, depending on what is most efficient for the processor architecture (and for the surrounding statements, in case this is a more complex function than the example). For example, two obvious ones:

```<code>load r1 = *b
copy r2 = r1
increment r1
store *b = r1
store *a = r2
</code>```

or

```<code>load r1 = *b
store *a = r1
increment r1
store *b = r1
</code>```

Note that the first one listed above, the one that uses more instructions and more registers, is the one that you would require to be used in all cases where a and b cannot be proven to be different.

Title: Why is x=x++ undefined?

Body:
It's undefined because the it modifies x twice between sequence points. The standard says it's undefined, therefore it's undefined.

That much I know.

But why?

My understanding is that forbidding this allows compilers to optimize better. This could have made sense when C was invented, but now seems like a weak argument.

If we were to reinvent C today, would we do it this way, or can it be done better?

Or maybe there's a deeper problem, that makes it hard to define consistent rules for such expressions, so it's best to forbid them?

So suppose we were to reinvent C today. I'd like to suggest simple rules for expressions such as x=x++, which seem to me to work better than the existing rules.

I'd like to get your opinion on the suggested rules compared to the existing ones, or other suggestions.

Suggested Rules:

Between sequence points, order of evaluation is unspecified.

Side effects take place immediately.

There's no undefined behavior involved. Expressions evaluate to this value or that, but surely won't format your hard disk (strangely, I've never seen an implementation where x=x++ formats the hard disk).

Example Expressions

x=x++ - Well defined, doesn't change x.

First, x is incremented (immediately when x++ is evaluated), then it's old value is stored in x.

x++ + ++x - Increments x twice, evaluates to 2*x+2.

Though either side may be evaluated first, the result is either x + (x+2) (left side first) or (x+1) + (x+1) (right side first).

x = x + (x=3) - Unspecified, x set to either x+3 or 6.

If the right side is evaluated first, it's x+3. It's also possible that x=3 is evaluated first, so it's 3+3. In either case, the x=3 assignment happens immediately when x=3 is evaluated, so the value stored is overwritten by the other assignment.

x+=(x=3) - Well defined, sets x to 6.

You could argue that this is just shorthand for the expression above.

But I'd say that += must be executed after x=3, and not in two parts (read x, evaluate x=3, add and store new value).

What's the Advantage?

Some comments raised this good point.

I certainly don't think expressions such as x=x++ should be used in any normal code.

Actually, I'm much more strict than that - I think the only good usage for x++ in as x++; alone.

However, I think the language rules must be as simple as possible. Otherwise programmers just don't understand them. the rule forbidding changing a variable twice between sequence points is certainly a rule most programmers don't understand.

A very basic rule is this:

If A is valid, and B is valid, and they're combined in a valid way, the result is valid.

x is a valid L-value, x++ is a valid expression, and = is a valid way to combine an L-value and an expression, so how come x=x++ isn't legal?

The C standard makes an exception here, and this exception complicates the rules. You can search stackoverflow.com and see how much this exception confuses people.

So I say - get rid of this confusion.

=== Summary of Answers ===

Why do that?

I tried to explain in the section above - I want C rules to be simple.

Potential for optimization:

This does take some freedom from the compiler, but I didn't see anything that convinced me that it might be significant.

Most optimizations can still be done. For example, a=3;b=5; can be reordered, even though the standard specifies the order. Expressions such as a=b[i++] can still be optimized similarly.

You can't change the existing standard.

I admit, I can't. I never thought I can actually go ahead and change standards and compilers. I only wanted to think if things could have been done differently.

Body:
First you have to understand that it's not just x=x++ that is undefined. Nobody cares about x=x++, since no matter what you would define it to there's no point to it. What's undefined is more like "a=b++ where a and b happen to be the same" - i.e.

void f(int *a, int *b) {
    *a = (*b)++;
}
int i;
f(&i, &i);

There several different ways the function might be implemented, depending on what is most efficient for the processor architecture (and for the surrounding statements, in case this is a more complex function than the example). For example, two obvious ones:

load r1 = *b
copy r2 = r1
increment r1
store *b = r1
store *a = r2

or

load r1 = *b
store *a = r1
increment r1
store *b = r1

Note that the first one listed above, the one that uses more instructions and more registers, is the one that you would require to be used in all cases where a and b cannot be proven to be different.


答:
If you review a large amount of code once it's already complete (and presumably functional), this is going to turn more into a session of "we should have done..." than "let's fix/change this to do..."

So, if the primary purpose of the activity is as a post-mortem learning exercise, then the large code review makes sense.  If it's to try to catch defects, it probably won't work very well.  Small defects are likely to be missed as everyone in the review gets bored and tired, and large, structural defects are likely to be skipped since, well, "too late now -- code's written and customer wants it yesterday."

Title: amount of code in code review


问:
Google Maps-based desktop application
I want to build a desktop application which has google maps embedded to it. This app should have a thread to read coordinate data online a usb microphone to use. This application will move the google map markers to their new locations based on the data retrieved from online connections on each refresh.

As far as I know gmaps has a javascript API so the first idea in my mind was to embed this mapview into a java applet. So the application will run on a browser. I'm not sure if this will work.

Do you guys have any idea about this or any other advices you might have?

答:
As far as I know, usage of Google Maps for desktop apps is forbidden.

(Scratch that, it's now OK, so long as it's a publicly available and downloadable app - will rewrite this answer.)

If you want this to run within a native desktop application - and not in a normal brower connecting to a web-app, though that could also be one way of doing it - you'll need to integrate an in-app browser component.

If you are planning on building this into a Java program, have a look at JDIC and or at integrating a rendering engine (like WebKit).

You can also look at:

WebKit in a Java Application

Rendering Web Pages with WebKit in Java

Your question does confuse me a bit though, as you mention using an applet (so, a Java application embedded in a WebPage, to display a map that could directly be displayed in a webpage? "Why, god why?", would be my first reaction). You could use an Applet though, and communicate with it via Javascript, if you want to display the map in the page and do other things in your applet, but that sounds a bit clunky.

Otherwise, as mentioned earlier, you could simply implement your project as a web-app and give access to it from any any platform with a browser supporting JavaScript.

Title: Google Maps-based desktop application


问:
Visualizing a CUP grammar
I am implementing a grammar in CUP, and it would often be helpful to see everything at a glance. This could also be useful in finding errors quickly.

Are there any programs out there that will visualize grammar in the CUP syntax? Or can you think of a very easy way of doing it (for instance, convert the grammar to another format that program X can read).

答:
You might need to convert it to another format first.

You could generate a graph of the grammar by using a combination of ANTLRWorks and GraphViz.

Someone did something similar here to generate graphs for the Ruby, JavaScript, and Java 1.5 grammars.

Title: Visualizing a CUP grammar


问:
Legality of collaborative reverse-engineering
I have been disassembling a large software project on my own, as a hobby. It is an educational exercise and I have learned a lot in the process. That said, I feel that my progress would be considerably quicker if I was to collaborate on the project with other like-minded individuals.

Herein lies the problem -- maybe. I am reversing this software for personal interest and potentially (but unlikely; given the magnitude of the codebase in question) implementing an interoperable service to interact with this software, replacing the vendor's own service. My (very limited) understanding is that this particular use-case is protected under copyright law.

However, my wish is to collaborate with others freely on the Internet, in a similar system employed by open source projects: version control repositories of assembly files, wikis to coordinate and share knowledge, public mailing lists, et cetera. I have a feeling this may be iffy at best.

Is what I want to do blatantly illegal, a gray area or even legally defensible? Would the situation be any different if the collaboration was in private rather than public? If it has any bearing on the answer, I am located in Australia and the software vendor in located in the USA.

答: If you are not making money off of it, you are unlikely to be sued right away.  The most likely result, if Big Corp find out about it and cares, is a cease and desist letter.  Basically, telling you to stop what you are doing.  At that point, you can decide if it is worth fighting to continue, or just stop (or go underground).  If you ever get to the point where you want to start selling something, then you need legal advice to figure out what your options are.


问:
Forking project on Github process
There is a project on Github that I mostly like and want to use. There are a few things I want to do differently/remove that doesn't make sense for what I want/need. Also I want to add a few things as well.

As I understand it, I should fork the project and I can make whatever changes I want and push back to my fork. From there, I also want to occasionally pull into my fork the changes from the original project so I get the latest bug fixes/features.

Am I off-base of how I think it should work? How would bring in the changes from the original project?

答:
You basically have it: once you create a fork, it's your own little sandbox.

I think the main thing that you need to do is immediately create a branch after you fork, in order to keep the original line of development separate from your own. Whether you develop in this branch or in master is largely a matter of personal taste. The one thing that would keep me from developing in master is that it's too easy to do a "git pull" and get the wrong thing.

Title: Forking project on Github process


答:
Have you had the chance to take a look at GreatMaps?

It's a .NET control that can be used/embedded in .NET apps. It's compatible with all framework versions and supports many map providers and Google Maps is between them.

Title: Google Maps-based desktop application

Body:
I want to build a desktop application which has google maps embedded to it. This app should have a thread to read coordinate data online a usb microphone to use. This application will move the google map markers to their new locations based on the data retrieved from online connections on each refresh.

As far as I know gmaps has a javascript API so the first idea in my mind was to embed this mapview into a java applet. So the application will run on a browser. I'm not sure if this will work.

Do you guys have any idea about this or any other advices you might have?


问:
What operating systems are used in airplanes, and what programming languages are they developed in?
I was wondering if anyone knows what is the operating system used in commercial airplanes (say Boeing or Airbus).

Also, what is the (preferred) real-time programing language? I heard that Ada is used in Boeing, so my question is - why Ada? what are the criteria the Boeing-guys had to choose this language? (I guess Java wouldn't be a great choice if exactly on lift-off the garbage collector wakes up).

答: Also worth noting that the control systems are often developed using model-based-design using Simulink. The design is then converted into C code automatically. Humans still read and validate the code.</p>


问:
Why are so many languages passed by value?
Even languages where you have explicit pointer manipulation like C it's always passed by value (you can pass them by reference but that's not the default behavior).

What is the benefit of this, why are so many languages passed by values and why are others passed by reference ? (I understand Haskell is passed by reference though I'm not sure).

答:
Pass by value is often safer than pass by reference, because you cannot accidentally modify the parameters to your method/function. This makes the language simpler to use, since you don't have to worry about the variables you give to a function. You know they won't be changed, and this is often what you expect.

However, if you want to modify the parameters, you need to have some explicit operation to make this clear (pass in a pointer). This will force all your callers to make the call slightly differently (&variable, in C) and this makes it explicit that the variable parameter may be changed.

So now you can assume that a function will not change your variable parameter, unless it is explicitly marked to do so (by requiring you to pass in a pointer). This is a safer and cleaner solution than the alternative: Assume everything can change your parameters, unless they specifically say they can't.


答:
Pass by reference allows for very subtle unintended side effects that are very difficult to next to impossible to trace down when they start causing the unintended behavior.

Pass by value, especially final, static or const input parameters makes this entire class of bugs disappear.

Immutable languages are even more deterministic and easier to reason about and understand what is going in and what is expected to be coming out of a function.

Title: Why are so many languages passed by value?

Body:
Even languages where you have explicit pointer manipulation like C it's always passed by value (you can pass them by reference but that's not the default behavior).

What is the benefit of this, why are so many languages passed by values and why are others passed by reference ? (I understand Haskell is passed by reference though I'm not sure).


问:
Rewriting GPL code to change license
I have found a GPL library (no dual license), which does exactly what I need. Unfortunately, the GPL license on the library is incompatible with the license of a different library I use. I have therefore decided to rewrite the GPL library, so the license can be changed.

My question is: How extensive do the changes need to be to the library in order to be able to change the license? In other words, what is the cheapest way to do this?

答:
IANAL and, in any case, this may mean nothing legally, but, I believe that in Steven Levy's book "Hackers", he describe how, at one point, RMS wrote *nix code for money during the day and at night wrote the same stuff at home so that it could be part of... GNU?... this was before Linux... some free Unix type system.  I believe that he had to make the home-code different than the day-code, but he was basically doing exactly what you are suggesting.

This probably doesn't matter legally, either but...  I am not sure whether Apple and/or Microsoft got permission/license or something, but didn't bell labs invent the desktop/icon/mouse interface, which was used for Macs (or Lisa?) which was then used by Microsoft.

Title: Rewriting GPL code to change license


答:
Design first, then code, top-down if you wish, so I understand the context at every level I have to work.

But if I have to do a very specific change, like fixing a report or a calculation, I just go and look at the code.

More specifically, my "design first" approach is this one:

I start with de domain model if there is one, if there is none I build al least a basic one (a good starting point is the data model). It defines the "glosary" of the application and the relation between the objects (classes).

It pictures "which objects are handled" by the aplication.

Then I look for the use case model to find out "what processes are done" by the application, although I prefer a process map if the is one, that shows sequences of processes.

After that I should have a nice picture of the application and then I can go about designing the change.

By the way, the above answer is in the context of business applications.

Title: What do you look at first: the code or the design?

Body:
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?


答:
If you pass by reference, then you are effectively always working with global values, with all of the problems of globals (namely scope and unintended side effects).

References, just like globals, are sometimes beneficial, but they shouldn't be your first choice.


问:
arrays format (Javascript)
I have a list of users, with minions, something like this:

```<code>User52:
       minion10
       minion12
User32:
      minion13
      minion11
</code>```

I've been keeping in an array where the "location" is the id, like this:

```<code>Users:
       [52]User
               minions:
                       [10]minion
                       [12]minion
       [32]User
               minions:
                       [13]minion
                       [11]minion
</code>```

so I can access them easily like this: user[UserID].minions[MinionID] (ex: user[32].minions[11]).

But when I print it or send it by json I get something like this:

```<code>{,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,minion,,,,,,,,,,,,,,minion}
</code>```

But should I keep using like this or should I change to something like this:

```<code>User = function(){
   this.minions = ...;
   this.getMinion = function(value){
     for(var m in this.minions){
      if(this.minions[m].id == value){
         return this.minions[m];
         break;
      }
     }
   }
}
</code>```

and get it like this:

```<code>user.getMinion(MinionID);
</code>```

Question: I get better performance using a "short" array but using loops every time I need a minion, or using "long" arrays, but no need for loop and getting values directly from the id "name"?

答:
Good question.  This is a common confusion early on.

What you are seeing is a different syntax of two things that behave the same because they are both objects. I will get to exactly why this is but will first clarify what is what:

In JavaScript,

This is an Array:

```<code>var arrayExample[];
</code>```

This is an Object Literal:

```<code>var jsObject = {};
</code>```

To answer your question, you should use Array definition and access syntax, when your intent is to use an Array.

```<code>user[15] = USER;
for (var i in user){
  if(user[i].id == ID){
    user[i];
}
</code>```

That said, there are better Array operations frameworks out there. One is underscore.js. But only consider it if you are conducting a large number of array operations that could be optimized. Another optimization is the jQuery foreach(), which is worth looking into.

Because an array is an object, and because objects have a naming lookup [] syntax, they have similar behavior. Both are very powerful constructs, but you should use them as they are intended so that subsequent developers can easily interpret your intentions.

The behavior overlap between object and array, is actually a very powerful flexibility of the language that is commonly misunderstood.

Here is a good link, but I'll try to make it simple.

An Object can access its' members through this name look up syntax:

//Looks like an array, but is an object accessing a member value, not an index value.
var memberValue = jsObject['member-name']

Essentially arrays are then doing the same thing, just with a number instead of a string.

Again, use an Array - when you need an Array, and Object - when you need an Object.

Title: arrays format (Javascript)

Body:
Good question.  This is a common confusion early on.

What you are seeing is a different syntax of two things that behave the same because they are both objects. I will get to exactly why this is but will first clarify what is what:

In JavaScript,

This is an Array:

var arrayExample[];

This is an Object Literal:

var jsObject = {};

To answer your question, you should use Array definition and access syntax, when your intent is to use an Array.

user[15] = USER;
for (var i in user){
  if(user[i].id == ID){
    user[i];
}

That said, there are better Array operations frameworks out there. One is underscore.js. But only consider it if you are conducting a large number of array operations that could be optimized. Another optimization is the jQuery foreach(), which is worth looking into.

Because an array is an object, and because objects have a naming lookup [] syntax, they have similar behavior. Both are very powerful constructs, but you should use them as they are intended so that subsequent developers can easily interpret your intentions.

The behavior overlap between object and array, is actually a very powerful flexibility of the language that is commonly misunderstood.

Here is a good link, but I'll try to make it simple.

An Object can access its' members through this name look up syntax:

//Looks like an array, but is an object accessing a member value, not an index value.
var memberValue = jsObject['member-name']

Essentially arrays are then doing the same thing, just with a number instead of a string.

Again, use an Array - when you need an Array, and Object - when you need an Object.


答: You can pass an expression by value, it's natural. Passing expression by (temporary) reference is... weird.</p>


问:
The Apache License, v2.0: Copyright License vs Patent License

The Apache License, v2.0

[..]

2. Grant of Copyright License

Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense and distribute the Work and such Derivative Works in Source or Object form.

[..]

3. Grant of Patent License

Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including cross-claim or counterclaim in lawsuit) alleging that the Work or a Contribution incorporated within theWork constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

While the meaning of the Copyright License provision is rather clear, I did not get the meaning of the Patent License provision.

Which advantages does the "Grant of Patent License" provision further give to Contributors? Why are they useful?

Is the "Grant of Patent License" provision useful only in case of patent litigation?

答:
I'm not a lawyer, but it looks to me like a plain English reading of section 3 is:

You can freely use the technology in this product, even if any of it is covered by patents owned by the contributors, without having to worry about patent issues.  But if you try and sue anyone over patent issues related to this product, then you lose the rights of this patent license and you're not protected anymore, so play nice.

The idea is not "to be useful in patent litigation" so much as "to prevent patent litigation from happening in the first place."