答:
Other answers have highlighted important points (more unit tests, feature teams, clean interfaces to the core components), but there is one point I find missing, which is versioning.

If you freeze the behavior of your core by doing a release1 and you put that release into a private artifact management system2, then any customer project can declare its dependency on core version X, and it will not be broken by the next release X + 1.

The "announcement policy" then just reduces to having a CHANGES file along with each release, or having a team meeting to announce all features of each new core release.

Also, I think you need to better define what is "core", and what subset of that is "key".  You seem to (correctly) avoid making many changes to "key components", but you allow frequent changes to "core".  In order to rely on something, you have to keep it stable; if something is not stable, do not call it core. Maybe I could suggest calling it "helper" components?

EDIT: If you follow the conventions in the Semantic Versioning system, then any incompatible change in the core's API must be marked by a major version change.  That is, when you change the previously existing core's behavior, or remove something, not just add something new.  With that convention, developers know that updating from version '1.1' to  '1.2' is safe, but going from '1.X' to '2.0' is risky and has to be carefully reviewed.

1: I think this is called a gem, in the world of Ruby

2: The equivalent to Nexus in Java or PyPI in Python


问:
How to name a method that both performs a task and returns a boolean as a status?
If there is a method

```<code>bool DoStuff() {
    try {
        // doing stuff...
        return true;
    }
    catch (SomeSpecificException ex) {
        return false;
    }
}
</code>```

should it rather be called IsStuffDone()?

Both names could be misinterpreted by the user:
If the name is DoStuff() why does it return a boolean?
If the name is IsStuffDone() it is not clear whether the method performs a task or only checks its result.

Is there a convention for this case? Or an alternative approach, as this one is considered flawed? For example in languages that have output parameters, like C#, a boolean status variable could be passed to the method as one and the method's return type would be void.

EDIT: In my particular problem exception handling cannot be directly delegated to the caller, because the method is a part of an interface implementation. Therefore, the caller can't be charged with dealing with all the exceptions of different implementations. It is not familiar with those exceptions. However, the caller can deal with a custom exception like StuffHasNotBeenDoneForSomeReasonException as was suggested in npinti's answer and comment.

答: I usually have methods return an OperationResult (or OperationResult<T>) and set the IsSuccess property on the OperationResult appropriately. If the 'usual' method is void then return OperationResult, if the 'usual' method returns an object then return OperationResult<T> and set the Item property on the OperationResult appropriately. I'd also suggest having methods on OperationResult such as .Failed(string reason) and .Succeeded(T item). OperationResult quickly becomes a familiar type in your systems and developers get to know how to handle it.

ContentLicense: CC BY-SA 3.0


问:
How can my team avoid frequent errors after refactoring?
To give you a little background: I work for a company with roughly twelve Ruby on Rails developers (+/- interns). Remote work is common. Our product is made out of two parts: a rather fat core, and thin up to big customer projects built upon it. Customer projects usually expand the core. Overwriting of key features does not happen. I might add that the core has some rather bad parts that are in urgent need of refactorings. There are specs, but mostly for the customer projects. The worst part of the core are untested (not as it should be...).

The developers are split into two teams, working with one or two PO for each sprint. Usually, one customer project is strictly associated with one of the teams and POs.

Now our problem: Rather frequently, we break each other's stuff. Someone from Team A expands or refactors the core feature Y, causing unexpected errors for one of Team B's customer projects. Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected.  Team B, including the PO, thought about feature Y to be stable and did not test it before releasing, unaware of the changes.

How to get rid of those problems? What kind of 'announcement technique' can you recommend me?

答:
Like other people said, a good suite of unit tests wont resolve your problem : you will have problem while merging changes, even if each team test suite passes.

Same for TDD. I dont see how it can solve this.

Your solution is non technical. You need to clearly define the "core" boundaries and assign a "watch dog" role to someone, be it the lead dev or architect. Any changes to the core must pass through this watchdog. He is responsible to make sure every output from all teams will merge without too much collateral damages.


问:
Fixing a spelling mistake in a method name
One of the methods that I commonly use in our codebase is misspelled (and it predated me).

This really irritates me not simply because it is mispelled but more importantly it makes me ALWAYS get the name wrong the first time I type it (and then I have to remember "Oh, right, it should be mispelled to this...")

I'm making a few changes around the original method. Should I take the opportunity to just rename the freaking method?

答:
A good way to not break any existing code would be to chain the new method name to the old
in a such as

```<code>private void MyNewMethodName()
{
    TheOldMethodName();
}
</code>```

and then mark the old method as obsolete (if your language support this). This way any existing code will still work and you can gradually take out all the old spelling mistake out of your code base. Eventually you could even copy/paste the method body into the new method and delete the old one.

/Edit As ivo said in the comment : An even better thing to do would be to move the code from TheOldMethodName into the MyNewMethodName and call the new method from the old one. This one would also have the advantage to help the dev to get their head around where the code belong to.

Body:
A good way to not break any existing code would be to chain the new method name to the old
in a such as

private void MyNewMethodName()
{
    TheOldMethodName();
}

and then mark the old method as obsolete (if your language support this). This way any existing code will still work and you can gradually take out all the old spelling mistake out of your code base. Eventually you could even copy/paste the method body into the new method and delete the old one.

/Edit As ivo said in the comment : An even better thing to do would be to move the code from TheOldMethodName into the MyNewMethodName and call the new method from the old one. This one would also have the advantage to help the dev to get their head around where the code belong to.


问:
High-level description of how experimental C++ features are developed?
Herb Sutter in a video answers a question about the concepts proposal considered for C++11 and from his remarks it sounds like multiple groups offered prototype implementations but all of them left concerns about slow compile times. The comment surprised me because it suggests that, at least in some cases, the prototypes being developed are not just proofs of concept -- they're even expected to perform. All the work that must take has me curious.

For mature languages, especially C++, how are experimental language features developed? Is it much different from developing a compiler that implements a standard? Does a developer have a sense of if it will work and perform or even if it ever could? What are the most time consuming parts and are any parts surprisingly easier than one might expect?

The question is not what does the C++ standards committee do, but rather the part that comes before. When an experimental implementation for a proposal is being put together and there aren't any completely solidified rules, how is the sausage made?

I'm not a professional compiler developer nor do I expect answers with step by step accounts. I'd like a high-level idea of how this would be done or if there are any general patterns at all. I don't know what to expect from the answers but even if there are no rules to the process and the small number of people who do this just cowboy it and then, for stuff that worked out, write up the "official version" as a proposal, that answer would still be informative.

答:
Principally it is sufficient to have a prototype implementation, or even just to "prove" that a feature is implementable.
So the process is not much different than it would be to implement any feature into the compiler, but since it is a prototype you can cut some corners.
Nobody expects production quality speed or results from these prototypes.

The problem with the pre-C++11 Concepts was not that the prototypes were slow, but that nobody was sure if and how the performance could be significantly improved, given the involved algorithms and the extend of data they required.

The work of getting a feature (even small ones) into the standard is significant.
You basically have to

motivate why you want the feature (by showing a problem which cannot
be solved / is more difficult to solve without it )

proof that the feature really solves the problem (implementation experience helps here)

proof that the problem is real and relevantly prevalent (having different solutions which are used in real projects help here)

proof that it will improve the language more than the additional complexity costs (often very contentious)

proof that it is (efficiently) implementable (prototype helps enormously)

proof that there is no easier solution (i.e. a throughoutly researched design rationale )

proof that there is no more general solution


问:
Reconciling the Boy Scout Rule and Opportunistic Refactoring with code reviews
I am a great believer in the Boy Scout Rule:

Always check a module in cleaner than when you checked it out." No
  matter who the original author was, what if we always made some
  effort, no matter how small, to improve the module. What would be the
  result? I think if we all followed that simple rule, we'd see the end
  of the relentless deterioration of our software systems. Instead, our
  systems would gradually get better and better as they evolved. We'd
  also see teams caring for the system as a whole, rather than just
  individuals caring for their own small little part.

I am also a great believer in the related idea of Opportunistic Refactoring:

Although there are places for some scheduled refactoring efforts, I
  prefer to encourage refactoring as an opportunistic activity, done
  whenever and wherever code needs to cleaned up - by whoever.
  What this means is that at any time someone sees some code that isn't
  as clear as it should be, they should take the opportunity to fix it
  right there and then - or at least within a few minutes

Particularly note the following excerpt from the refactoring article:

I'm wary of any development practices that cause friction for
  opportunistic refactoring ... My sense is that most teams don't do
  enough refactoring, so it's important to pay attention to anything
  that is discouraging people from doing it. To help flush this out be
  aware of any time you feel discouraged from doing a small refactoring,
  one that you're sure will only take a minute or two. Any such barrier
  is a smell that should prompt a conversation. So make a note of the
  discouragement and bring it up with the team. At the very least it
  should be discussed during your next retrospective.

Where I work, there is one development practice that causes heavy friction - Code Review (CR). Whenever I change anything that's not in the scope of my "assignment" I'm being rebuked by my reviewers that I'm making the change harder to review. This is especially true when refactoring is involved, since it makes "line by line" diff comparison difficult. This approach is the standard here, which means opportunistic refactoring is seldom done, and only "planned" refactoring (which is usually too little, too late) takes place, if at all.

I claim that the benefits are worth it, and that 3 reviewers will work a little harder (to actually understand the code before and after, rather than look at the narrow scope of which lines changed - the review itself would be better due to that alone) so that the next 100 developers reading and maintaining the code will benefit. When I present this argument my reviewers, they say they have no problem with my refactoring, as long as it's not in the same CR. However I claim this is a myth:

(1) Most of the times you only realize what and how you want to refactor when you're in the midst of your assignment. As Martin Fowler puts it:

As you add the functionality, you realize that some code you're adding
  contains some duplication with some existing code, so you need to
  refactor the existing code to clean things up... You may get something
  working, but realize that it would be better if the interaction with
  existing classes was changed. Take that opportunity to do that before
  you consider yourself done.

(2) Nobody is going to look favorably at you releasing "refactoring" CRs you were not supposed to do. A CR has a certain overhead and your manager doesn't want you to "waste your time" on refactoring. When it's bundled with the change you're supposed to do, this issue is minimized.

The issue is exacerbated by Resharper, as each new file I add to the change (and I can't know in advance exactly which files would end up changed) is usually littered with errors and suggestions - most of which are spot on and totally deserve fixing.

The end result is that I see horrible code, and I just leave it there. Ironically, I feel that fixing such code not only will not improve my standings, but actually lower them and paint me as the "unfocused" guy who wastes time fixing things nobody cares about instead of doing his job. I feel bad about it because I truly despise bad code and can't stand watching it, let alone call it from my methods!

Any thoughts on how I can remedy this situation ?

答:
Why don't you do both, but with separate commits?

Your peers have a point.  A code review should evaluate the code that was changed by someone else.  You shouldn't touch the code that you are reviewing for someone else as that biases your role as a reviewer.

But if you see a number of glaring issues, there are two options you can follow.

If the code review was otherwise fine, the allow the portion you reviewed to be committed and then refactor the code under a second check-in.

If the code review had issues that needed correction, request the developer to refactor based upon the Resharper recommendations.


问:
What is the concept behind writing a cancel operation in c++?
I'm attempting to write a cancel operation for a software download application. This application will first transfer the software to the device and then install the software on it. (These are givens I'm not allowed to change).

What should the cancel operation do? When a user presses 'cancel', the application should stop transferring/installing the software immediately.

Question: Since I've never written a "cancel" function, I'm wondering what are the types of things to consider when writing the code, and what are the common bugs I should expect and how to deal with them?

Couldn't find anything in google so if you have some links that would be good reads I'd really appreciate it since I'm not looking for answers I'm just looking for guidelines/macro/concept help

答:
What should the cancel operation do? When a user presses 'cancel', the application should stop transferring/installing the software immediately.

Conceptually, you should consider your installation operation transactionally: each operation is either done or not done (no side effects for a failed operation, no side effects for a partially performed operation).

To do this, isolate as much as possible a change to the system, until it succeeds or fails, and consider committing changes as a transactional step:

Naive approach:

download software

install downloaded software

there is no step 3

Realistic approach:

split your performed operations as such:

operations that cannot fail (commits)

operations that can fail (staging)

operations that can be undone (rollbacks)

define the transactional states of your system: connecting to server, downloading, preparing system settings, installing

each operation should be performed in the following steps:

check preconditions (does not alter system state)

stage operation (perform all operations that can fail to get to the next state)

commit (set system state based on staged data and state) and set rollback state

repeat steps for next operation

implement each operation to take you from a transactional step to the next, or previous.

Ideally getting to the previous state should not be able to fail, but this is not so in practice. As such, memento is a good pattern to use: enqueue transactional states, and in case you need to rollback, simply state the system to one of the stored states.


答:
I'm going to assume that Change Requests are big and formal at your company. If not, just make the changes (where possible) into many small commits (like you're supposed to).

Any thoughts on how I can remedy this situation?

Continue doing what you're doing?

I mean, all of your thoughts and deductions are entirely correct. You should fix things you see. People don't do planned refactoring enough. And that benefit to the whole group is more important than inconveniencing a few.

What may help is to be less combative. Code reviews shouldn't be combative "Why did you do that?", they should be collaborative "Hey guys, while I was here I fixed up all this stuff!". Working (with your lead/manager if possible) to change that culture is tough, but pretty vital to create a high functioning development team.

You can also work (with your lead/manager if possible) to advance the importance of these ideas with your colleagues. Make it into you asking "why don't you guys care about quality?" instead of them asking "why are you always doing these useless things?".

Title: Reconciling the Boy Scout Rule and Opportunistic Refactoring with code reviews

Body:
I am a great believer in the Boy Scout Rule:

Always check a module in cleaner than when you checked it out." No
  matter who the original author was, what if we always made some
  effort, no matter how small, to improve the module. What would be the
  result? I think if we all followed that simple rule, we'd see the end
  of the relentless deterioration of our software systems. Instead, our
  systems would gradually get better and better as they evolved. We'd
  also see teams caring for the system as a whole, rather than just
  individuals caring for their own small little part.

I am also a great believer in the related idea of Opportunistic Refactoring:

Although there are places for some scheduled refactoring efforts, I
  prefer to encourage refactoring as an opportunistic activity, done
  whenever and wherever code needs to cleaned up - by whoever.
  What this means is that at any time someone sees some code that isn't
  as clear as it should be, they should take the opportunity to fix it
  right there and then - or at least within a few minutes

Particularly note the following excerpt from the refactoring article:

I'm wary of any development practices that cause friction for
  opportunistic refactoring ... My sense is that most teams don't do
  enough refactoring, so it's important to pay attention to anything
  that is discouraging people from doing it. To help flush this out be
  aware of any time you feel discouraged from doing a small refactoring,
  one that you're sure will only take a minute or two. Any such barrier
  is a smell that should prompt a conversation. So make a note of the
  discouragement and bring it up with the team. At the very least it
  should be discussed during your next retrospective.

Where I work, there is one development practice that causes heavy friction - Code Review (CR). Whenever I change anything that's not in the scope of my "assignment" I'm being rebuked by my reviewers that I'm making the change harder to review. This is especially true when refactoring is involved, since it makes "line by line" diff comparison difficult. This approach is the standard here, which means opportunistic refactoring is seldom done, and only "planned" refactoring (which is usually too little, too late) takes place, if at all.

I claim that the benefits are worth it, and that 3 reviewers will work a little harder (to actually understand the code before and after, rather than look at the narrow scope of which lines changed - the review itself would be better due to that alone) so that the next 100 developers reading and maintaining the code will benefit. When I present this argument my reviewers, they say they have no problem with my refactoring, as long as it's not in the same CR. However I claim this is a myth:

(1) Most of the times you only realize what and how you want to refactor when you're in the midst of your assignment. As Martin Fowler puts it:

As you add the functionality, you realize that some code you're adding
  contains some duplication with some existing code, so you need to
  refactor the existing code to clean things up... You may get something
  working, but realize that it would be better if the interaction with
  existing classes was changed. Take that opportunity to do that before
  you consider yourself done.

(2) Nobody is going to look favorably at you releasing "refactoring" CRs you were not supposed to do. A CR has a certain overhead and your manager doesn't want you to "waste your time" on refactoring. When it's bundled with the change you're supposed to do, this issue is minimized.

The issue is exacerbated by Resharper, as each new file I add to the change (and I can't know in advance exactly which files would end up changed) is usually littered with errors and suggestions - most of which are spot on and totally deserve fixing.

The end result is that I see horrible code, and I just leave it there. Ironically, I feel that fixing such code not only will not improve my standings, but actually lower them and paint me as the "unfocused" guy who wastes time fixing things nobody cares about instead of doing his job. I feel bad about it because I truly despise bad code and can't stand watching it, let alone call it from my methods!

Any thoughts on how I can remedy this situation ?


答:
If you can split the requested change and the unrequested refactor into two separate change requests, as noted by @GlenH7, then that is the best you can do.  You are then not "the guy who wastes time" but "the guy who works twice as hard".

If you often find yourself in the situation that you cannot split them, because the requested work now needs the unrequested refactor to compile, I would suggest that you insist on having tools to check automatically for coding standards, using the arguments outlined here (the Resharper warnings on their own may be a good candidate, I am not familiar with it).  Those arguments are all valid, but there is one extra that you can use to your advantage: having those tests now make it your duty to pass the tests on each commit.

If your company does not want to "waste time on refactoring" (a poor sign on their part), then they should provide to you a "warning suppression" file (each tool has its own mechanism) so that you are not annoyed anymore with such warnings.  I say this in order to provide you with options for different scenarios, even worst case.  It is also better to have clearly stated agreements between you and your company, also on the expected code quality, rather than implicit assumptions on each side.


答:
This question now has two distinct issues - ease of reviewing changes in code reviews, and time spent on refactoring.

Where I work, there is one development practice that causes heavy friction - Code Review (CR). Whenever I change anything that's not in the scope of my "assignment" I'm being rebuked by my reviewers that I'm making the change harder to review.

As other answers have said - can you separate the refactoring checkins from the code change checkins (not necessarily as separate reviews)? Depending on the tool you're using to do code review you should be able to view the diffs between specific revisions only (Atlassian's Crucible definitely does this).

(2) Nobody is going to look favorably at you releasing "refactoring" CRs you were not supposed to do. A CR has a certain overhead and your manager doesn't want you to "waste your time" on refactoring. When it's bundled with the change you're supposed to do, this issue is minimized.

If the refactoring is straightforward and makes the code easier to comprehend (which is all you should be doing if it is just refactoring) then the code review shouldn't take long to complete and should be minimal overhead which is won back in spades when someone has to come and look at the code again in the future. If your bosses aren't able to grok this then you might need to gently nudge them towards some resources which discuss why the Boy Scout Rule leads to a more productive relationship with your code. If you can convince them that the "waste [of] your time" now will save two, five or ten times as much later on when you/someone else comes back to do more work on that code then your problem should go away.

The issue is exacerbated by Resharper, as each new file I add to the change (and I can't know in advance exactly which files would end up changed) is usually littered with errors and suggestions - most of which are spot on and totally deserve fixing.

Have you tried bringing these issues to the attention of your colleagues and discussing why they are worth fixing? And can any of them be fixed automatically (assuming you have sufficient test coverage to confirm you haven't broken stuff with the automated refactoring)? Sometimes it isn't "worth your time" to perform a refactoring if it is really nit-picky stuff. Does your entire team use ReSharper? If they do, do you have a shared policy on what warnings/rules are being enforced? If they don't, again perhaps you should be demonstrating where the tool is helping you to identify areas of the code which are possible sources of future pain.


问:
Count unique visitors by group of visited places
I'm facing the problem of counting the unique visitors of groups of places.

Here is the situation:

I have visitors that can visit places. For example, that can be internet users visiting web pages, or customers going to restaurants. A visitor can visit as much places as he wishes, and a place can be visited by several visitors. A visitor can come to the same place several times.

The places belong to groups. A group can obviously contain several places, and places can belong to several groups.

Given that, for each visitor, we can have a list of visited places, how can I have the number of unique visitors per group of places?

Example: I have visitors A, B, C and D; and I have places x, y and z.

I have these visiting lists:

```<code>[
 A -> [x,x,y,x],
 B -> [],
 C -> [z,z],
 D -> [y,x,x,z]
]
</code>```

Having these number of unique visitors per place is quite easy:

```<code>[
 x -> 2, // A and D visited x
 y -> 2, // A and D visited y
 z -> 2  // C and D visited z
]
</code>```

But if I have these groups:

```<code>[
 G1 -> [x,y,z],
 G2 -> [x,z],
 G3 -> [x,y]
]
</code>```

How can I have this information?

```<code>[
 G1 -> 3, // A, C and D visited x or y or z
 G2 -> 3, // A, C and D visited x or z
 G3 -> 2  // A and D visited x or y
]
</code>```

Additional notes :

There are so many places that it is not possible to store information about every possible group;

It's not a problem if approximation are made. I don't need 100% precision. Having a fast algorithm that tells me that there were 12345 visits in a group instead of 12543 is better than a slow algorithm telling the exact number. Let's say there can be ~5% deviation.

I have a finite number of visitors and a finite number of places. I don't have so much places (approximately 60 for now, but it can grow to 200) but I have quite many visitors (estimated to 50 millions and this number could grow to 200 millions in the next months).

Is there an algorithm or class of algorithms that addresses this type of problem?

答:
Appears you have finite visitors and finite places to visit just in multiple combinations.  If so, then you can know who visited.  How?  I recommend using a queue for each place to be visited.

When visitors visit, enqueue them (place them into the queue).  If visitors visit multiple times, they will be in the queue multiple times.

Since you are only interested in knowing whether visitors have visited, perform a dequeue (remove them from the queue) and record who visited.

With this method, you should be able to accurately record who visited what, how many times, and in what order.


问:
Best Practices: Database app programming patterns
I have written many database (MySQL) web apps so far but I always think my structure is kinda clumsy. I want to improve the programming/design pattern I use, hoping for some advice here. Particularly, I cannot find a structure that complements an OOP approach that encapsulates the implementation of the database (schema). I

Think my question can be best explained by example. There are 2 approaches I use now say I have an Invoice object/class:

first is to use static member functions

```<code>class Invoice
{
   int id;
   string ref;
   int customer_id;
   date created;
   date due;

   static id create();
   static bool update(id, field1, field2, ...);
   static bool delete(id);
   static bool get(id);
};
</code>```

The second approach is to put every thing in a database object:

```<code>class Database extends ProprietaryDBConnecter, Singleton
{
   id createInvoice();
   bool updateInvoice(id, field1, field2, ...);
   bool deleteInvoice(id);
   bool getInvoice(id);

   id createCustomer();
   bool updateCustomer(id, field1, field2, ...);
   bool deleteCustomer(id);
   bool getCustomer(id);

   // etc...
}
</code>```

I find that both ways the (SQL) member functions are very much unseparable from the "view", in that the "view" determines what the classes needs to have and hence seems to break the document/view architecture.

Also, it seems kind of inefficient for example a SELECT statement should only select what is needed, but the presence of member variables in Invoice seems to imply "guaranteed data".

Don't know if I explained the question clearly, What are some other best approaches to this architecture/design pattern/what-it-is-known-as?

Thanks for advices

答:
If you don't want to use an ORM wrapper, use a database that supports OOP style storage like MongoDB.

MongoDB (from "humongous") is a cross-platform document-oriented database system. Classified as a "NoSQL" database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster...

ContentLicense: CC BY-SA 2.5


答:
I personally hate the idea of of post commit code reviews. Code review should happen, as you make the code changes. What I am of course talking about here is pair programming. When you pair, you get the review for free and you get a better code review. Now, I am expressing my opinion here, I know others share this, there are probably studies that prove this.

If you can get your code reviewers to pair with you, the combative element of code review should evaporate. When you start making a change that isn't understood, the question can be raised at the point of change, discussed and alternatives explored which may lead to better refactorings. You will get a higher quality code review as the pair will be able to understand the wider scope of the change, and not focus so much on line by line changes which is what you get with side by side code compare.

Of course this isn't a direct answer to the problem of refactorings being outside the scope of the change being worked on but I would expect that your peers would better understand the reasoning behind the changes if they where there when you made the change.

As an aside, assuming you are doing TDD or some form of red green refactor, one way to ensure that you get engagement from your peer is to use the ping pong pairing technique. Simply explained as the driver is rotated for each step of the RGR cycle, i.e. pair 1 writes a failing test, pair 2 fixes it, pair 1 refactors, pair 2 write a failing test.... and so on.


答:
Probably this problem reflect a much bigger problem with the organization culture. People seems more interested in do "his work" right than in make the product better, probably this company has a "blame" culture instead of a colaborative culture and the people seems more interested in cover itself than in have a whole product/company vision.

In my opinion, you are completly right, the people who review your code are completely wrong if they have complains because you "touch" things outside "your assignment", try to convince those people but never be against your principles, for me this is the most important quality of a true professional.

And if do the right thing give you bad numbers in some stupid corporation way to evaluate your work, what the problem?, who want to "win" this evaluation game in a insane company?, try to change it!, and if imposible or you are tired, find another place, but never, never be against your principles, is the best you have.


问:
Why did the team at LMAX use Java and design the architecture to avoid GC at all cost?
Why did the team at LMAX design the LMAX Disruptor in Java but all their design points to minimizing GC use? If one does not want to have GC run then why use a garbage collected language?

Their optimizations, the level of hardware knowledge and the thought they put are just awesome but why Java?

I'm not against Java or anything, but why a GC language? Why not use something like D or any other language without GC but allows efficient code? Is it that the team is most familiar with Java or does Java possess some unique advantage that I am not seeing?

Say they develop it using D with manual memory management, what would be the difference? They would have to think low level (which they already are), but they can squeeze the best performance out of the system as it's native.

答:
If you use Java as a syntax language and avoid its JDK libraries it can be as fast as a compiled non-GC language. GC is not suitable for real-time systems, but it is possible to develop systems in Java that do not leave any garbage behind. As a result the GC never triggers.

We believe that the Java language and platform have many advantages over C/C++ and we have developed and benchmarked some ultra-low-latency Java components to prove it. We talk about the techniques to do so in this article: Java Development without GC.


问:
Genetic Algorithm new generation exponentially increasing
I'm programming Genetic Algorithm in C++ and after searching all kind of ways of doing GA'a operators (selection, crossover, mutation) I came up with a doubt.

Let's say I have an initial population of 500. My selection will consist in getting the top 20% of 500(based on best fitness). So I get 100 individuals to mate. When I do the crossover I'll get 2 children where both together have 50% of surviving. So far so good. I start the mutation, and everything's ok.. Now when I start choosing the Next generation, I see that I have a big number of children (in this case, 4950 if you wanna know). Now the thing is, every time I run GA, if I send all the children to the next generation, the number of individuals per generation will increase exponentially.

So there must be a way of choosing the children to fulfill a new generation without getting out of this range of the initial population.

What I'm asking here is if there is anyway of choosing the children to fill the new generations OR should I choose somehow (and maybe reduce) the parents to mate so I don't get so many children in the end.

答:
Choosing the children that are fit for the next generation of mating is the same fitness calculation that made their parents fit.  Also, at the end of the current generation, you should not have more children than the initial population.  Remember, this is not a free-for-all but survival of the fittest.

You are picking a highly selected group that are fit to mate from; essentially discarding up to 75 - 80% or more of your initial population (search space) or however much you need to ensure only the fittest mate.

A genetic algorithm should be run until you have exhausted the search space or, in other words, until there are no more mating pairs and, hopefully, that last offspring or very small group of offspring yield the answer you want.

This will require you to tune the fitness, crossover, and mutation factors.  I recall when I wrote a GA to solve how the arithmetic operators (*, /, +. -) and the numeric values (0-9) are combined to form a randomly generated value such as 45.  I represented my chromosomes as x-bit binary values that contained every operator and the number 0-9.  They were heavily randomized through a heuristic to ensure as much variation as possible.

I had to tweak selection, crossover, and mutation just to solve the problem but it could be solved.  If you see populations going out of control, something is not right in your algorithm.  I recall, from an initial population of 100,000 I lost between 50 - 75k that were not fit to mate.

Play with it some more; you understand how it should work and I am sure you will get it.


答:
OK, so there are now more things here than are suitable for a comment.

tl;dr

Your intuition about what you ought to do (refactoring as you go) is correct.

Your difficulty implementing this - given that you have to work around a poor code review system - comes down to your difficulty manipulating your source code and VCS. Multiple people have said that you can and should split your changes (yes, even within files) into multiple commits, but you seem to have difficulty believing this.

You really can do this. That really is what we're suggesting. You really should learn to get the most out of your editing, source manipulation and version control tools. If you invest the time in learning how to use them well, it makes life much easier.

Workflow/office politics issues

I'd make essentially the same recommendation as GlenH7 that you create two commits - one with only refactorings and (demonstrably or obviously) no functional changes, and one with the functional changes in question.

It may be useful though, if you're finding lots of errors, to pick a single category of error to fix within a single CR. Then you have one commit with a comment like "dedupe code", "fix type-X errors", or whatever. Because this makes a single type of change, presumably in multiple places, it should be trivial to review. It does mean you can't fix every error you find, but may make it less painful to smuggle through.

VCS issues

Splitting the changes made to your working source into multiple commits shouldn't be a challenge.
You haven't said what you're using, but possible workflows are:

if you're using git, you have excellent tools for this

you can use git add -i for interactive staging from the command line

you can use git gui and select individual hunks and lines to stage (this is one of the few VCS related GUI tools I actually prefer to the command line, the other being a good 3-way merge editor)

you can make lots of tiny commits (individual changes, or fixing the same class of bug in multiple places) and then reorder them, merge them or split them with rebase -i

if you're not using git, your VCS may still have tooling for this sort of thing, but I can't advise without knowing what system you use

You mentioned you're using TFS - which I believe is compatible with git since TFS2013. It may be worth experimenting with using a local git clone of the repo to work in. If this is disabled or doesn't work for you, you can still import the source into a local git repo, work in there, and use it to export your final commits.

you can do it manually in any VCS if you have access to basic tools like diff and patch. It's more painful, but certainly possible. The basic workflow would be:

make all your changes, test, etc.

use diff to make a (context or unified) patch file with all changes since the last commit

partition that into two files: you'll end up with one patch file containing refactorings, and one with functional changes

this isn't entirely trivial - tools such as emacs diff mode may help

back everything up

revert to the last commit, use patch to replay one of the patch files, commit those changes

NB. if the patch didn't apply cleanly, you may need to fix up the failed hunks manually

repeat 5 for the second patch file

Now you have two commits, with your changes partitioned appropriately.

Note there are probably tools to make this patch management easier - I just don't use them since git does it for me.


问:
Circular dependency and object creation when attempting DDD
I have a domain where an Organization has People.

Organization Entity

```<code>public class Organization {
    private readonly List<Person> _people = new List<Person>();

    public Person CreatePerson(string name) {
        var person = new Person(organization, name);
        _people.Add(person);
        return person;
    }

    public IEnumerable<Person> People {
        get { return _people; }
    }
}
</code>```

Person Entity

```<code>public class Person
{
    public Person(Organization organization, string name) {
        if (organization == null) {
            throw new ArgumentNullException("organization");
        }

        Organization = organization;
        Name = name;
    }

    public Organization { get; private set; }
    public Name { get; private set; }
}
</code>```

The rule for this relationship is that a Person must belong to exactly one Organization.

The invariants I want to guarantee are:

A person must have an organization

this is enforced via the Person's constuctor

An organization must know of its people

this is why the Organization has a CreatePerson method

A person must belong to only one organization

this is why the organization's people list is not publicly mutable (ignoring the casting to List, maybe ToEnumerable can enforce that, not too concerned about it though)

What I want out of this is that if a person is created, that the organization knows about its creation.

However, the problem with the model currently is that you are able to create a person without ever adding it to the organizations collection.

Here's a failing unit-test to describe my problem

```<code>[Test]
public void AnOrganizationMustKnowOfItsPeople()
{
    var organization = new Organization();
    var person = new Person(organization, "Steve McQueen");

    CollectionAssert.Contains(organization.People, person);
}
</code>```

What is the most idiomatic way to enforce the invariants and the circular relationship?

答:
Multiple points:

When I was reading DDD, I remembered one thing: You want to avoid double-sided relationships if possible. You should only define one direction and have the other direction be accessible through query in repository. In your case, you could have Organization as attribute of Person, but not have list of Person as part of Organization. And make it so repository contains GetPeopleOfOrganization method to query for that information.

Next thing to note is that it is often acceptable to have the data in invalid state for short period of time. The point is that system doesn't allow you to persist this state and the invalid state is not visible to any other part of the system. This is the case with transactions. It is possible to have invalid state during transaction, but transaction will fail when you try to commit it with the invalid state. And system doesn't allow different transactions to see what is happening inside other transactions.

And related to above: The entity is not really part of the model until it is added to the list/repository of all entities. It is fine to try having the data valid before that, but it might cause problems, that might easily be solved when the integrity check is done in repository when data is saved.

And last thing. I agree that being able to enforce invariants and integrity with just code and during compilation is great. But C# simply doesn't have type and language facilities to allow for that. It is no shame to rely on run-time checking and exceptions. As long as you ensure that the code crashes in development, instead of production, everything should be fine.


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Don't do anything.

Just let it slide, and learn the lesson.

Also, don't let your personal feelings of fairness get in the way.

Title: How to get money from reluctant client?


问:
Can someone explain in simple terms what is the disruptor pattern?
I would like if you could explain to me in a simple way how does the disruptor patter work. This concept has been elusive to me as of know.

Perhaps with your help I could comprehend it.

答:
The Fowler Article providers a good primer, and this explanation:

At a crude level you can think of a Disruptor as a multicast graph of
queues where producers put objects on it that are sent to all the
consumers for parallel consumption through separate downstream queues.
When you look inside you see that this network of queues is really a
single data structure - a ring buffer.

Each producer and consumer has
a sequence counter to indicate which slot in the buffer it's currently
working on. Each producer/consumer writes its own sequence counter but
can read the others' sequence counters. This way the producer can read
the consumers' counters to ensure the slot it wants to write in is
available without any locks on the counters. Similarly a consumer can
ensure it only processes messages once another consumer is done with
it by watching the counters.

A more conventional approach might use a Producer Queue and a Consumer Queue, each using locks as concurrency mechanisms.  In practice, what happens with producer and consumer queues is that the queues are either completely empty or completely full most of the time, which causes lock contention and wasted clock cycles.  The disruptor alleviates this, in part, by having all of the producers and consumers use the same queue mechanism, coordinating with each other by watching the sequence counters rather than using locking mechanisms.


问:
Securely sending data from shared hosted PHP script to local MSSQL
I'm trying to add data from a webhook (from a web cart) to a local Microsoft SQL Server. It seems like the best route for me is to use a PHP script to listen for new data (POST as json), parse it, then query to add to MSSQL.

I'm not familiar with security concerning the connection between the PHP script (which would sit on a shared-host website) and the local MSSQL database. I would just keep the PHP script running on the same localhost (have Apache running on Windows), but the URI for the webhook needs to be publicly accessible.

Alternately, I assume that I could just schedule a script from the localhost to check periodically for updates through the web carts API, though the webhooks seem to be more fool-proof for an amateur programmer like myself.

What steps can I take to ensure security when using a PHP on a remote, shared-host to connect to MSSQL on my local machine?

答:
I disagree with the comments for your question, especially about security. Your approach with a PHP script is valid, but you'll need a tunnel to do it right.

In regards to security, do you really want to open up your data packets to people sniffing? With the NSA out there and most routers able to intercept, I would be cautious.

I would go with openVPN, easy enough to setup, then have your local instance always connected with an openVPN connection and so your data will be secure. This may or may-not be available on your 'shared' server, so that is a consideration.

Honestly, you can get a micro centos instance up on Amazon with turn-key software and do the openVPN install yourself. Not too hard, but you'll need to learn some system management.


问:
Multiple sites with the same codebase in Python
I am trying to run a large amount of sites which share about 90% of their code. They are simply designed to query an API and return the results. They will have a common userbase / database but will be configured slightly different and will have different CSS (perhaps even different templating).

My initial idea was to run them as separate applications with a common library but I have read about the sites framework which would allow them to run from a single instance of Django which may help to reduce memory usage.

https://docs.djangoproject.com/en/dev/ref/contrib/sites/

Is the site framework the right approach to a problem like this, and does it have real benefits over running separate applications?

Initially I thought it was, but now I think otherwise. I have heard the following:

Your SITE_ID is set in settings.py, so in order to have multiple
  sites, you need multiple settings.py configurations, which means
  multiple distinct processes/instances. You can of course share the
  code base between them, but each site will need a dedicated worker /
  WSGIDaemon to serve the site.

This effectively removes  any benefit of running multiple sites under one hood, if each site needs a UWSGI instance running.

Alternative ideas of systems:

https://github.com/iivvoo/django_layers

https://github.com/shestera/django-multisite

I don't know what route to be taking with this.

答:
I suggest putting your code into git, then using submodules to load your 'library' of shared code.

If you read up on it, this sounds like exactly what you need:

http://git-scm.com/book/en/Git-Tools-Submodules

It often happens that while working on one project, you need to use another project from within it. Perhaps it’s a library that a third party developed or that you’re developing separately and using in multiple parent projects.

We use this extensively and has worked well for our organization that does hundreds of deployments weekly of the same code with very minor changes to each version that gets deployed.

My 2 cents.


答:
From this article about CoralQueue:

The disruptor pattern is a batching queue backed up by a circular
  array (i.e. the ring buffer) filled with pre-allocated transfer objects which uses
  memory-barriers to synchronize producers and consumers through
  sequences.

So producers and consumers do not step on each other inside the circular array by checking their corresponding sequences. And to communicate their sequences back and forth to each other they use memory-barriers instead of locks. That's the fastest lock-free way that they can communicate.

Fortunately you don't need to get down to the internal details of the disruptor pattern to use it. Besides the LMAX implementation there is CoralQueue developed by Coral Blocks, with which I am affiliated. Some people find it easier to understand a concept by reading code, so below is a simple example of a single producer sending messages to a single consumer. You can also check this question for a demultiplexer (one producer to many consumers) example.

```<code>package com.coralblocks.coralqueue.sample.queue;

import com.coralblocks.coralqueue.AtomicQueue;
import com.coralblocks.coralqueue.Queue;
import com.coralblocks.coralqueue.util.Builder;

public class Basics {

    public static void main(String[] args) {

        final Queue<StringBuilder> queue = new AtomicQueue<StringBuilder>(1024, new Builder<StringBuilder>() {
            @Override
            public StringBuilder newInstance() {
                return new StringBuilder(1024);
            }
        });

        Thread producer = new Thread(new Runnable() {

            private final StringBuilder getStringBuilder() {
                StringBuilder sb;
                while((sb = queue.nextToDispatch()) == null) {
                    // queue can be full if the size of the queue
                    // is small and/or the consumer is too slow

                    // busy spin (you can also use a wait strategy instead)
                }
                return sb;
            }

            @Override
            public void run() {

                StringBuilder sb;

                while(true) { // the main loop of the thread

                    // (...) do whatever you have to do here...

                    // and whenever you want to send a message to
                    // the other thread you can just do:
                    sb = getStringBuilder();
                    sb.setLength(0);
                    sb.append("Hello!");
                    queue.flush();

                    // you can also send in batches to increase throughput:
                    sb = getStringBuilder();
                    sb.setLength(0);
                    sb.append("Hi!");

                    sb = getStringBuilder();
                    sb.setLength(0);
                    sb.append("Hi again!");

                    queue.flush(); // dispatch the two messages above...
                }
            }
        }, "Producer");

        Thread consumer = new Thread(new Runnable() {

            @Override
            public void run() {

                while (true) { // the main loop of the thread

                    // (...) do whatever you have to do here...

                    // and whenever you want to check if the producer
                    // has sent a message you just do:

                    long avail;
                    while((avail = queue.availableToPoll()) == 0) {
                        // queue can be empty!
                        // busy spin (you can also use a wait strategy instead)
                    }

                    for(int i = 0; i < avail; i++) {
                        StringBuilder sb = queue.poll();
                        // (...) do whatever you want to do with the data
                        // just don't call toString() to create garbage...
                        // copy byte-by-byte instead...
                    }
                    queue.donePolling();
                }
            }
        }, "Consumer");

        consumer.start();
        producer.start();
    }
}
</code>```

Disclaimer: I am one of the developers of CoralQueue.

Title: Can someone explain in simple terms what is the disruptor pattern?

Body:
I would like if you could explain to me in a simple way how does the disruptor patter work. This concept has been elusive to me as of know.

Perhaps with your help I could comprehend it.

Body:
From this article about CoralQueue:

The disruptor pattern is a batching queue backed up by a circular
  array (i.e. the ring buffer) filled with pre-allocated transfer objects which uses
  memory-barriers to synchronize producers and consumers through
  sequences.

So producers and consumers do not step on each other inside the circular array by checking their corresponding sequences. And to communicate their sequences back and forth to each other they use memory-barriers instead of locks. That's the fastest lock-free way that they can communicate.

Fortunately you don't need to get down to the internal details of the disruptor pattern to use it. Besides the LMAX implementation there is CoralQueue developed by Coral Blocks, with which I am affiliated. Some people find it easier to understand a concept by reading code, so below is a simple example of a single producer sending messages to a single consumer. You can also check this question for a demultiplexer (one producer to many consumers) example.

package com.coralblocks.coralqueue.sample.queue;

import com.coralblocks.coralqueue.AtomicQueue;
import com.coralblocks.coralqueue.Queue;
import com.coralblocks.coralqueue.util.Builder;

public class Basics {

    public static void main(String[] args) {

        final Queue<StringBuilder> queue = new AtomicQueue<StringBuilder>(1024, new Builder<StringBuilder>() {
            @Override
            public StringBuilder newInstance() {
                return new StringBuilder(1024);
            }
        });

        Thread producer = new Thread(new Runnable() {

            private final StringBuilder getStringBuilder() {
                StringBuilder sb;
                while((sb = queue.nextToDispatch()) == null) {
                    // queue can be full if the size of the queue
                    // is small and/or the consumer is too slow

                    // busy spin (you can also use a wait strategy instead)
                }
                return sb;
            }

            @Override
            public void run() {

                StringBuilder sb;

                while(true) { // the main loop of the thread

                    // (...) do whatever you have to do here...

                    // and whenever you want to send a message to
                    // the other thread you can just do:
                    sb = getStringBuilder();
                    sb.setLength(0);
                    sb.append("Hello!");
                    queue.flush();

                    // you can also send in batches to increase throughput:
                    sb = getStringBuilder();
                    sb.setLength(0);
                    sb.append("Hi!");

                    sb = getStringBuilder();
                    sb.setLength(0);
                    sb.append("Hi again!");

                    queue.flush(); // dispatch the two messages above...
                }
            }
        }, "Producer");

        Thread consumer = new Thread(new Runnable() {

            @Override
            public void run() {

                while (true) { // the main loop of the thread

                    // (...) do whatever you have to do here...

                    // and whenever you want to check if the producer
                    // has sent a message you just do:

                    long avail;
                    while((avail = queue.availableToPoll()) == 0) {
                        // queue can be empty!
                        // busy spin (you can also use a wait strategy instead)
                    }

                    for(int i = 0; i < avail; i++) {
                        StringBuilder sb = queue.poll();
                        // (...) do whatever you want to do with the data
                        // just don't call toString() to create garbage...
                        // copy byte-by-byte instead...
                    }
                    queue.donePolling();
                }
            }
        }, "Consumer");

        consumer.start();
        producer.start();
    }
}

Disclaimer: I am one of the developers of CoralQueue.


答:
Why are you optimizing?

You seem to be concerned about memory usage.  Why?  Is the projected savings large enough to let you rent a cheaper VM?  Is the sites' current usage threatening to bust your machine's current RAM?  (And even if they are, are you confident that your going to spend less on development time for this feature than you would for just getting a better machine?)

Let's assume you already asked yourself that...

And the unfortunate conclusion was that there is a compelling reason to optimize memory usage.

You are talking about putting in work and code infrastructure to link these sites into a single, optimized unit.  If these separate sites are inextricably linked to each other in some way other than sharing the same code base, it makes sense to build physical infrastructure on top of that logical grouping.  If these are functionally separate sites that just happen to use mostly the same codebase, I would advise to not even think about using a framework like this unless you've got no other choice.

What if one of the sites later wants to pick up a windows dependency (assuming the others are running on *nix right now)?  What if one of the sites becomes so popular that it needs to be on a separate machine for performance reasons?  What if the customer wants to relocate one of the sites for better response times in Europe?

Without any other details about what you are working on, creating an architecture that ties these sites together sounds like a pretty questionable endeavor.

Title: Multiple sites with the same codebase in Python

Body:
I am trying to run a large amount of sites which share about 90% of their code. They are simply designed to query an API and return the results. They will have a common userbase / database but will be configured slightly different and will have different CSS (perhaps even different templating).

My initial idea was to run them as separate applications with a common library but I have read about the sites framework which would allow them to run from a single instance of Django which may help to reduce memory usage.

https://docs.djangoproject.com/en/dev/ref/contrib/sites/

Is the site framework the right approach to a problem like this, and does it have real benefits over running separate applications?

Initially I thought it was, but now I think otherwise. I have heard the following:

Your SITE_ID is set in settings.py, so in order to have multiple
  sites, you need multiple settings.py configurations, which means
  multiple distinct processes/instances. You can of course share the
  code base between them, but each site will need a dedicated worker /
  WSGIDaemon to serve the site.

This effectively removes  any benefit of running multiple sites under one hood, if each site needs a UWSGI instance running.

Alternative ideas of systems:

https://github.com/iivvoo/django_layers

https://github.com/shestera/django-multisite

I don't know what route to be taking with this.


问:
Good practice on Visual Studio Solutions
Hopefully a relativity simple question. I'm starting work on a new internal project to create tractability of repaired devices within the buildings.

The database is stored remotely on a webserver, and will be accessed via web API (JSON output) and protected with OAuth. The front end GUI is being done in WPF, and the business code in C#.

From this, I see the different layers Presentation/Application/Datastore. There will be code for managing all the authenticated calls to the API, class to represent entities (business objects), classes to construct the entities (business objects), parts for WPF GUI, parts of the WPF viewmodels, and so on.

Is it best to create this in a single project, or split them into individual projects?

In my heart I say it should be multiple projects. I have done it both ways previously, and found testing to be easier with a single project solution, however with multiple projects then recursive dependencies can crop up. Especially when classes have interfaces to make it easier to test, I've found things can become awkward.

答:
The only good reason to have more than one project, is if you need to share a set of classes and files across multiple applications.

If projects are used by only one application, they shouldn't have been made in the first place. Use namespaces instead. Save yourself the trouble of circular references, dll overhead, and project confusion when looking for files.

Read this article for a better more in depth explanation of why that is so: http://lostechies.com/chadmyers/2008/07/16/project-anti-pattern-many-projects-in-a-visual-studio-solution-file/

And as the article states, I'd welcome anyone who has a valid reason to have multiple projects apart from code sharing across application to tell me what it is, because I doubt there is any.


问:
Accepting a numerical range in a function call
I have encountered two ways of doing it:

```<code>void foo(int from, int to); /* 'from' inclusive, 'to' exclusive */

void foo(int startIndex, int rangelength);
</code>```

Has one style historically been preferred over the other? If so, was it just a matter of convention or was it due to some deeper underlying reason?

I'm currently programming in Java and noticed that the Arrays class uses the former style. The exclusivity of the to argument felt somewhat unintuitive to me, which led me to ask this question.

答:
Which language?  The answer to API design questions like this one is always language-specific.  Many languages have built-in support for ranges.  In those languages the answer is easy: use a single argument of whatever type is used to represent a range.

For Java, you might consider com.google.common.collect.Range from Google's Guava library.

While exclusive upper bounds may seem unnatural, they are far more convenient than inclusive ranges because they eliminate a lot of fiddling around adding and subtracting one.  Inclusive ranges over continuous types like time are very troublesome.  How often have you seen things like { start: 00:00, end: 23:59 } ?  What about 23:59:30 ?  Using exclusive ranges eliminates those questions.


问:
CANopen and CAN Driver
CAN Driver means application program that interacts with CAN hardware and helps in initializing setup and communication.

CANopen Stack provides various APIs to deal with CAN communication.

Now this is confusing me so please let me know: Is CANopen Stack and CAN driver one and the same?

答:
Not necessarily.

A 'stack' in this situation refers to a set of applications that are used for the overall product.  See wikipedia solution stack and technology stack.  The FOOstack would imply a set of software (the libraries necessary, maybe a specialized plugin or rework of the IDE (for example the SpringSource Tool Suite).  For example, the MEAN Stack uses Mongo, expressjs, angularjs, and node for a solution and thus bundle of software is often referred to as a stack.

You will sometimes see referred to the 'full stack developer' which someone who can work on any part of the system from client to database.

The driver is a particular piece of software to communicate with a particular piece of hardware.  Thats it.  A video driver is used by the operating system to communicate with the video hardware.

A driver may be included as part of the stack, but a driver is not the entirety of the solution stack.

Title: CANopen and CAN Driver


问:
Combinatorial explosion of interfaces: How many is too many?
I'm a relative newcomer to OOP, and I'm having a bit of trouble creating good designs when it comes to interfaces.

Consider a class A with N public methods. There are a number of other classes, B, C, ..., each of which interacts with A in a different way, that is, accesses some subset (<= N) of A's methods.

The maximum degree of encapsulation is achieved by implementing an interface of A for each other class, i.e. AInterfaceForB, AInterfaceForC, etc.

However, if B, C, ... etc. also interact with A and with each other, then there will be a combinatorial explosion of interfaces (a maximum of n(n-1), to be precise), and the benefit of encapsulation becomes outweighed by a code-bloat.

What is the best practice in this scenario?

Is the whole idea of restricting access to a class's public functions in different ways for other different classes just silly altogether? One could imagine a language that explicitly allows for this sort of encapsulation (e.g. instead of declaring a function public, one could specify exactly which classes it is visible to); Since this is not a feature of C++, maybe it's misguided to try to do it through the back door with interaces?

答:
The point of interfaces is to allow piece of code to express what API it works with. And then allow this API to be implemented by multiple classes. In your case, instead of AforB or AforC, make it Bneeds and Cneeds interface.

What you are saying also hints that there is actually only one implementation of those interfaces in form of A. If there is only one implementation, then there is serious flaw in the design, because point of interface is to be able to be implemented by multiple classes. If interface limits by which class it is implemented, then it is bad interface.


问:
User Story or User Stories for this specific requirement
I have to write a user story for a requirement that involves passing search filters to the same URI and retrieving corresponding results.

I have 5 filters.

I plan to write 5 different stories of type:
As a URI user I can search by #filter1 so that I can retrieve results based on #filter1.

And then a 6th story that involves searching one or more or all six filters in conjunction.

Is this is a sensible route to take?

答:
If you keep it as one single user story and you only get 4/5 filters done at the end of your sprint, then your single story is incomplete. If you split it, then if you get 4/5 filters complete, then 4 out of 5 stories can be marked as finished.

When I get stories like this, that have n features of a similar nature (such as your 5 filters, or some transformations, or some data processors, ...) I like to split them into a separate story for each feature so that if one of the features runs into unexpected problems, I can move the other stories to completion. It's more for adminstrative reasons than it is for technical, I suppose, and the administrative overhead is a bit larger when it's done this way, but it makes it easier to track the work that is done or not done, and the progress of each story.


答:
When I was being indoctrinated to UML (which is a different methodology but I still like this lesson) the premise of a Use Case was: "Someone comes to the system, does something of business value, and then goes away." That provided a nice boundary between use cases, because it divvied the work up into a number of more or less complete process flows.

Start at A, do this and this and this, end at B. If you can't get to B, throw an exception. Getting from B to C, or from A to X, are different flows.

I like the same boundaries with agile stories, for the same reason. So, from your example above, a user might come to the system, invoke filter 3, and then walk away. They may never invoke filter 2, which suggests 2 different stories.

Title: User Story or User Stories for this specific requirement

Body:
I have to write a user story for a requirement that involves passing search filters to the same URI and retrieving corresponding results.

I have 5 filters.

I plan to write 5 different stories of type:
As a URI user I can search by #filter1 so that I can retrieve results based on #filter1.

And then a 6th story that involves searching one or more or all six filters in conjunction.

Is this is a sensible route to take?


答:
If B and C need different things, there's probably a need for two interfaces. If those happen to be implemented by the same class, so be it.

What strikes me here is your inter-dependency of the classes. In order to be able to refactor code at a later point your objects shouldn't depend on each other. Even if you hide it with interfaces, they shouldn't be calling each other, which seems to me to be the actual flaw here. Maybe what you actually need is some kind of facade but that's a wild guess without knowing the details.

I think you should rethink A using B and, at the same time, B using A. That's probably the root cause of your problem.

Title: Combinatorial explosion of interfaces: How many is too many?

Body:
I'm a relative newcomer to OOP, and I'm having a bit of trouble creating good designs when it comes to interfaces.

Consider a class A with N public methods. There are a number of other classes, B, C, ..., each of which interacts with A in a different way, that is, accesses some subset (<= N) of A's methods.

The maximum degree of encapsulation is achieved by implementing an interface of A for each other class, i.e. AInterfaceForB, AInterfaceForC, etc.

However, if B, C, ... etc. also interact with A and with each other, then there will be a combinatorial explosion of interfaces (a maximum of n(n-1), to be precise), and the benefit of encapsulation becomes outweighed by a code-bloat.

What is the best practice in this scenario?

Is the whole idea of restricting access to a class's public functions in different ways for other different classes just silly altogether? One could imagine a language that explicitly allows for this sort of encapsulation (e.g. instead of declaring a function public, one could specify exactly which classes it is visible to); Since this is not a feature of C++, maybe it's misguided to try to do it through the back door with interaces?


问:
How can my team avoid frequent errors after refactoring?
To give you a little background: I work for a company with roughly twelve Ruby on Rails developers (+/- interns). Remote work is common. Our product is made out of two parts: a rather fat core, and thin up to big customer projects built upon it. Customer projects usually expand the core. Overwriting of key features does not happen. I might add that the core has some rather bad parts that are in urgent need of refactorings. There are specs, but mostly for the customer projects. The worst part of the core are untested (not as it should be...).

The developers are split into two teams, working with one or two PO for each sprint. Usually, one customer project is strictly associated with one of the teams and POs.

Now our problem: Rather frequently, we break each other's stuff. Someone from Team A expands or refactors the core feature Y, causing unexpected errors for one of Team B's customer projects. Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected.  Team B, including the PO, thought about feature Y to be stable and did not test it before releasing, unaware of the changes.

How to get rid of those problems? What kind of 'announcement technique' can you recommend me?

答: As a more long term fix, you also need better and more timely communication between teams.  Each of the teams that will ever utilize, for example, core feature Y, need to be involved in building the planned testcases for the feature.  This planning, in and of itself, will highlight the different use cases inherent in feature Y between the two teams.  Once how the feature should work is nailed down, and the testcases are implemented and agreed upon, there's an additional change in your implementation scheme that's required.  The team releasing the feature is required to run the testcase, not the team that's about to use it.  The task, if any, that should cause collisions, is the addition of a new testcase from either of the teams.  When a team member thinks of a new aspect of the feature that is not tested, they should be free to add a testcase that they have verified passing in their own sandbox.  In this way, the only collisions that will occur will be at the intent level, and should be nailed down before the refactored feature is released into the wild.</p>


答:
Is the whole idea of restricting access to a class's public functions in different ways for other different classes just silly altogether?

Yes and no. Bear with me.

Restricting access to a specific class is silly. While it is important to separate a class from the implementation of its dependencies, it's arguably more important to separate a class from the details of the class dependant on it.

For this reason, it's also silly to name your interfaces as if they are a link between the two classes. They're not.

To the calling class, as Euphoric points out, the interface is "I need to be able to do this ... I don't care how it's done." The name should reflect that. ie. Rather than an interface between ProductService and SqlProductRepository called SqlProductRepositoryForProductService, there should be an interface known to the ProductService called ProductRepository ("I need to be able to save a product and I don't care how"), which is implemented by SqlRepository.

But SqlRepository may also be able to store Orders. And in this sense, it DOES make sense to limit access FROM ProductService to SqlRepository so that it can only store Products. OrderService may access the SqlRepository through a new interface called OrderRepository.

Why bother, you ask? Why not simply access the class, or an interface that gives you access to the whole class?

Because it might be that, once SqlRepository has grown beyond control, you want to break it down. Perhaps into a SqlMembershipRepository (which might handle users, groups, roles, etc) and a SqlManufacturingRepository (which might handle products, components, etc) and a SqlSalesRepository (which might handle orders, customers, etc). If you've allowed everything access to all of the SqlRepository, you might find this a much tougher task than simply breaking the class into three and implementing the same interfaces that the Services always needed. Especially true if you have several classes that need to save a product.

Or, and this may be the most important point, you might want to change the way you handle Sales only. For some reason, you might decide to store it in a file, or in a NoSql database.

If you've kept your interfaces segregated, you only need to implement the ProductRepository interface on the new NoSqlRepository. If you kept it as one interface, you would have to implement SaveOrder in the NoSqlRepository (even if it were a blank method, because it was never used) and leave the implementation of SaveProduct on SqlRepository.

Suddenly your entire abstraction between services and repositories would make no sense. Another developer may come along and write some code that will store an order. There is a very good chance that they'll accidentally call the empty SaveOrder method on the NoSqlRepository, instead of the SaveOrder method on the SqlRepository. And they may be very confused when that doesn't work.


答:
We all know that unit tests are the way to go. But we also know that realistically retro-fitting these to a core is difficult.

A specific technique that might be useful for you when extending the functionality is to try to temporarily and locally verify that existing functionality has not been changed. This can be done like this:

Original pseudo code:

```<code>def someFunction
   do original stuff
   return result
end
</code>```

Temporary in-place test code:

```<code>def someFunctionNew
   new do stuff
   return result
end

def someFunctionOld
   do original stuff
   return result
end

def someFunction
   oldResult = someFunctionOld
   newResult = someFunctionNew
   check oldResult = newResult
   return newResult
end
</code>```

Run this version through whatever system level tests that exist. If everything is fine, you know you have not broken things and can then proceed to remove the old code. Note that when you check the old and new results match, you might also add code to analyse differences to capture cases that you know should be different because of an intended change such as a bug fix.

Title: How can my team avoid frequent errors after refactoring?

Body:
To give you a little background: I work for a company with roughly twelve Ruby on Rails developers (+/- interns). Remote work is common. Our product is made out of two parts: a rather fat core, and thin up to big customer projects built upon it. Customer projects usually expand the core. Overwriting of key features does not happen. I might add that the core has some rather bad parts that are in urgent need of refactorings. There are specs, but mostly for the customer projects. The worst part of the core are untested (not as it should be...).

The developers are split into two teams, working with one or two PO for each sprint. Usually, one customer project is strictly associated with one of the teams and POs.

Now our problem: Rather frequently, we break each other's stuff. Someone from Team A expands or refactors the core feature Y, causing unexpected errors for one of Team B's customer projects. Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected.  Team B, including the PO, thought about feature Y to be stable and did not test it before releasing, unaware of the changes.

How to get rid of those problems? What kind of 'announcement technique' can you recommend me?

Body:
We all know that unit tests are the way to go. But we also know that realistically retro-fitting these to a core is difficult.

A specific technique that might be useful for you when extending the functionality is to try to temporarily and locally verify that existing functionality has not been changed. This can be done like this:

Original pseudo code:

def someFunction
   do original stuff
   return result
end

Temporary in-place test code:

def someFunctionNew
   new do stuff
   return result
end

def someFunctionOld
   do original stuff
   return result
end

def someFunction
   oldResult = someFunctionOld
   newResult = someFunctionNew
   check oldResult = newResult
   return newResult
end

Run this version through whatever system level tests that exist. If everything is fine, you know you have not broken things and can then proceed to remove the old code. Note that when you check the old and new results match, you might also add code to analyse differences to capture cases that you know should be different because of an intended change such as a bug fix.


问:
Matching the superclass's constructor's parameter list, is treating a null default value as a non-null value within a constructor a violation of LSP?
I kind of ran into this when messing around with FlashPunk, and I'm going to use it as an example.

Essentially the main sprite class is pretty much class Entity.  Entity's constructor has four parameters, each with a default value.  One of them is graphic, whose default value is null.

Entity is designed to be inherited from, with many such subclasses providing their own graphic within their own internal workings.  Normally these subclasses would not have graphic in their constructor's parameter lists, but would simply pick something internally and go with it.

However I was looking into possibly still adhering to the Liskov Substitution Principal, which led me to the following example:

```<code>package com.blank.graphics
{
    import net.flashpunk.*;
    import net.flashpunk.graphics.Image;

    public class SpaceGraphic extends Entity
    {
        [Embed(source = "../../../../../../assets/spaces/blank.png")]
        private const BLANK_SPACE:Class;

        public function SpaceGraphic(x:Number = 0, y:Number = 0, graphic:Graphic = null,
                mask:Mask = null)
        {
            super(x, y, graphic ? graphic : new Image(BLANK_SPACE), mask);
        }
    }
}
</code>```

Alright, so now there's a parameter list in the constructor that perfectly matches the one in the super class's constructor.  But if the default value for graphic is used, it'll exhibit two different behaviors, depending on whether you're using the subclass or the superclass.  In the superclass, there won't be a graphic, but in the subclass, it'll choose the default graphic.

Is this a violation of the Liskov Substitution Principal?  Does the fact that subclasses are almost intended to use different parameter lists have any bearing on this?  Would minimizing the parameter list violate it in a case like this?  Thanks.

答: No, it is not a violation of the LSP. The LSP says that instances of a subtype should be safely substitutable for instances of the parent type (i.e. after construction). It doesn't matter how they get constructed.


答:
After that you have generated your initial population (the pool should be quite large) and you apply your fitness function to it, you select your parents for the next generation.

Once that you have your parents, you discard the other individuals so that you can replace them with the new generation. This replacing will keep your population size in control, after all, if individual I did not fit the fitness criteria to contribute to the next generation, why do you need to keep it?

Note however, that in your study, there is a high chance that your algorithm will converge to a local maxima/minima very quickly. This is because you only keep the top 20% of your population for mating. This is usually a bad idea since it will get your GA stuck in a local maxima/minima. To fix this, you would also include some of worse solutions as well, say for instance, the top 20% and the worse 5-10%.

EDIT: Alternatively, you could also go for something akin to what @ Jeff Langemeier proposes and instead of selecting the worse 10% of the population, you randomly select a given amount from the non best (in this case, the remaining 80%) individual.

Title: Genetic Algorithm new generation exponentially increasing

Body:
I'm programming Genetic Algorithm in C++ and after searching all kind of ways of doing GA'a operators (selection, crossover, mutation) I came up with a doubt.

Let's say I have an initial population of 500. My selection will consist in getting the top 20% of 500(based on best fitness). So I get 100 individuals to mate. When I do the crossover I'll get 2 children where both together have 50% of surviving. So far so good. I start the mutation, and everything's ok.. Now when I start choosing the Next generation, I see that I have a big number of children (in this case, 4950 if you wanna know). Now the thing is, every time I run GA, if I send all the children to the next generation, the number of individuals per generation will increase exponentially.

So there must be a way of choosing the children to fulfill a new generation without getting out of this range of the initial population.

What I'm asking here is if there is anyway of choosing the children to fill the new generations OR should I choose somehow (and maybe reduce) the parents to mate so I don't get so many children in the end.


问:
What if(event) statement means in JavaScript?
I'm rather new to JavaScript and programming in general so I am pretty much only used to seeing if statements that have some kind of comparison operator like, if (x < 10) or if(myBool).

I have seen an if statement checking against an event, but I don't understand what or why the event is being checked like that.  What's the semantic meaning behind that check or comparison?

Here is the code in question:

```<code>if(event){
    event.preventDefault();
}
</code>```

答: Without knowing what event is we cannot really say much, other than that by the end of the day, event resolves to either true or false. In the above, the code is most likely checking that event is not null.


答:
This means event is either non-zero (if it's value is integer), true (if it's a Boolean) or non-null (if it's something else).

In many languages (compiled or scripting), when a condition is evaluated, it results in a value. Thus, x < 10 results in true (or in some languages a non-zero numeric value), and then it is interpreted as a true condition. Thus, if you were to say if(event) where event's value was 1 (or non-null), then it would be considered true and the if block will be executed. The same logic applies to null vs non-null.

You can try this JS code and see that one alert will go up and the other won't. You can replace event with null vs a string (e.g. 'blah') as well as a 0 vs non-0 and see that it will behave similarly:

```<code>var event = true;
if (event) alert('true!');
var event = false;
if (event) alert('false!');
</code>```

Title: What if(event) statement means in JavaScript?

Body:
I'm rather new to JavaScript and programming in general so I am pretty much only used to seeing if statements that have some kind of comparison operator like, if (x < 10) or if(myBool).

I have seen an if statement checking against an event, but I don't understand what or why the event is being checked like that.  What's the semantic meaning behind that check or comparison?

Here is the code in question:

```<code>if(event){
    event.preventDefault();
}
</code>```

Body:
This means event is either non-zero (if it's value is integer), true (if it's a Boolean) or non-null (if it's something else).

In many languages (compiled or scripting), when a condition is evaluated, it results in a value. Thus, x < 10 results in true (or in some languages a non-zero numeric value), and then it is interpreted as a true condition. Thus, if you were to say if(event) where event's value was 1 (or non-null), then it would be considered true and the if block will be executed. The same logic applies to null vs non-null.

You can try this JS code and see that one alert will go up and the other won't. You can replace event with null vs a string (e.g. 'blah') as well as a 0 vs non-0 and see that it will behave similarly:

var event = true;
if (event) alert('true!');
var event = false;
if (event) alert('false!');


问:
Testing complex compositions
I have a rather large collection of classes which check and mutate a given data structure. They can be composed via the composition pattern into arbitrarily complex tree-like structures. The final product contains a lot of these composed structures.

My question is now: How can I test those? Albeit it is easy to test every single unit of these compositions, it is rather expensive to test the whole compositions in the following sense:

Testing the correct layout of the composition-tree results in a huge number of test cases

Changes in the compositions result in a very laborious review of every single test case

What is the general guideline here?

答:
If something is tedious, it often can be automated - that is true for test data generation as well as for many other tasks.

Instead of constructing each test case manually, write a test case generator, which takes some simple textual description of the tree (maybe some kind of "mini DSL") and constructs it. Write a second function which takes the composition tree and reduces it to the textual desciption again. Now it will be easy to create a data-driven test: create a bunch of tree descriptions and let the test verify that the conversion to the composition tree and the following reconversion to the text will always reproduce the original input.

(Remark: here is a former post on PSE where the idea of using a DSL for tree-like structures was explained in a different context.)

Title: Testing complex compositions


问:
Is there a more intelligent way to do this besides a long chain of if statements or switch?
I'm implementing an IRC bot that receives a message and I'm checking that message to determine which functions to call. Is there a more clever way of doing this? It seems like it'd quickly get out of hand after I got up to like 20 commands. </p>

<p>Perhaps there's a better way to abstract this?    </p>

```<code> public void onMessage(String channel, String sender, String login, String hostname, String message){

        if (message.equalsIgnoreCase(".np")){
//            TODO: Use Last.fm API to find the now playing
        } else if (message.toLowerCase().startsWith(".register")) {
                cmd.registerLastNick(channel, sender, message);
        } else if (message.toLowerCase().startsWith("give us a countdown")) {
                cmd.countdown(channel, message);
        } else if (message.toLowerCase().startsWith("remember am routine")) {
                cmd.updateAmRoutine(channel, message, sender);
        }
    }
</code>```

答:
You could have all commands implement the same interface. Then a message parser could return you the appropriate command which you'll only execute.

```<code>public interface Command {
    public void execute(String channel, String message, String sender) throws Exception;
}

public class MessageParser {
    public Command parseCommandFromMessage(String message) {
        // TODO Put your if/switch or something more clever here
        // e.g. return new CountdownCommand();
    }
}

public class Whatever {
    public void onMessage(String channel, String sender, String login, String hostname, String message) {
        Command c = new MessageParser().parseCommandFromMessage(message);
        c.execute(channel, message, sender);
    }
}
</code>```

It looks like just more code. Yes, you still need to parse the message in order to know which command to execute but now it's at a properly defined point. It may be reused elsewhere. (You might want to inject the MessageParser but that's another matter. Also, the Flyweight pattern might be a good idea for the commands, depending on how many you expect to be created.)

Body:
You could have all commands implement the same interface. Then a message parser could return you the appropriate command which you'll only execute.

public interface Command {
    public void execute(String channel, String message, String sender) throws Exception;
}

public class MessageParser {
    public Command parseCommandFromMessage(String message) {
        // TODO Put your if/switch or something more clever here
        // e.g. return new CountdownCommand();
    }
}

public class Whatever {
    public void onMessage(String channel, String sender, String login, String hostname, String message) {
        Command c = new MessageParser().parseCommandFromMessage(message);
        c.execute(channel, message, sender);
    }
}

It looks like just more code. Yes, you still need to parse the message in order to know which command to execute but now it's at a properly defined point. It may be reused elsewhere. (You might want to inject the MessageParser but that's another matter. Also, the Flyweight pattern might be a good idea for the commands, depending on how many you expect to be created.)