问:
When is it inappropriate to make objects immutable?
I have a class which represents an entity object in our system (for sake of argument, a Customer object)

```<code>public class Customer()
{
  private int id;
  private String name;
  ... // 30+ fields

  public Customer()
  {
    // empty constructor!
  }

  // getters and setters
}
</code>```

I'm trying to refactor this so that the fields are extracted into their own objects where they are more sensibly grouped, and at the same time creating parameterised constructors - with the intent I could then lose the setter methods and make my objects immutable (since this is apparently a Good Thing(TM)).

However, this doesn't make any sense - sometimes I need to update a customer's information! It's clearly not immutable. Should I just not make this class immutable - and can I apply the same argument to all my entity classes?

答:
What are the benefits of immutability?  Do those benefits apply to a Customer object?

Generally, one uses immutability to provide determinism.  Can you access an immutable object safely across multiple threads?  Yes, because there's no danger of one thread mutating the object while another thread is processing it.

However, in the case of Line of Business applications, a database typically takes care of any concurrency problems by issuing locks on records when people edit them, or letting the last save win.  Consequently, domain classes typically aren't designed in an immutable way, since doing so attempts to solve a problem that is already solved.


问:
Unit-testing functions without business logic (only checks)
My team is trying to find out the best way to test one of our components; the main scope is to check if the user/actor has the right to complete the operation requested. The component is formed by many functions that usually have the following structure (simplified):
Example language: PHP

```<code>public function addGroup($idEntity, $nameGroup){
if (!$this->logic->isEntityActive($idEntity)){
    throw new EntityNotActiveException();
}
if ($idEntity != $this->getServiceLocator()->get('request')->getQuery()->get('idEntity')){
    throw new NoRightsException();
}
if ($this->logic->isGroupWithNameAlreadyInDB($idEntity, $nameGroup)){
    throw new GroupAlreadyExistException();
}
return $this->logic->addGroupToEntity($idEntity, $nameGroup);
}
</code>```

As you can see this method has no "logic" per se (apart from the checks) and in the end it just forwards the request to the logic underneath. We are conflicted about how to correctly test this function. Do we mock everything? We can do it and in each test fake some "failures", but the problem remains that to test the correctness of the function you mock everything. Every single function. In that case you are not testing anything. We could really use some advice on this problem. Can anybody show us examples of a good way to test a function like this?

We use phpunit. Thank in advance for your help.

答:
There is no point unit testing something trivial. There has to some logic there for there to be any value to a unit test.

In this case it might be worth covering it indirectly with your wider spanning integration tests.

ContentLicense: CC BY-SA 3.0


答:
My opinion is that you mock everything.  You are making sure that the checks are acting correctly not the underlying logic in the function call that returns the true/false).  Mocking this also removes understanding the logic behind the function calls in each of the conditions.  And this test won't fail if/when that logic changes which would become a maintenance nightmare.

The main problem with that is in this line:

```<code>if ($idEntity != $this->getServiceLocator()->get('request')->getQuery()->get('idEntity'))
</code>```

As you end up with a mock return a mock.  This is a code smell and violates the D in SOLID (http://en.wikipedia.org/wiki/Law_of_Demeter).  I would consider refactoring this so that you pass in the result of getQuery().

I would probably end up writing seperate tests for the exceptions and one for the success.  As the mocks for each would end up expecting different calls.

EDIT:
Keep in mind that the tests help provide insight into the expected behavior of the code,  and also for making sure that any changes in the logic do not break existing functionality.
If you want to change the conditions of addGroup, you can make sure that you have maintained existing functionality without having to dig into the underlying function calls.

Here is what the exception test would look like (using PHPUnit):

```<code>/**
 * @dataProvider dataExceptions
 */
public function testAddGroupExceptions($isActive, $inGroup, $id, $exception) {
    $this->expectsException($exception);

    $logic = $this->getMockBuilder('logic')->setMethods(array('isEntityActive', 'isAlreadyInGroup', 'addGroupToEntity'))->getMock();

    //Set number of calls to any to not tie to order in function
    $logic->expects($this->any())->method('isEntityActive')->will($this->returnValue($isActive));
    $logic->expects($this->any())->method('isAlreadyInGroup')->will($this->returnValue($isActive));

    //This is a fail case, so do not add group
    $logic->expects($this->never())->method('addGrouptToEntity');

    //Not doing all the mocks to get the 'idEntity'
    $query = $this->getMockBuilder('query')->setMethods(array('get'))->getMock();

    $query->expects($this->any())->method('get')->with('idEntity')->will($this->returnValue($id));

    $idEntity = 'test';
    $group = 'foo';

    //Instantiate the object - $test
    $test->addGroup($idEnity, $group);
}
</code>```

Title: Unit-testing functions without business logic (only checks)

Body:
My team is trying to find out the best way to test one of our components; the main scope is to check if the user/actor has the right to complete the operation requested. The component is formed by many functions that usually have the following structure (simplified):
Example language: PHP

```<code>public function addGroup($idEntity, $nameGroup){
if (!$this->logic->isEntityActive($idEntity)){
    throw new EntityNotActiveException();
}
if ($idEntity != $this->getServiceLocator()->get('request')->getQuery()->get('idEntity')){
    throw new NoRightsException();
}
if ($this->logic->isGroupWithNameAlreadyInDB($idEntity, $nameGroup)){
    throw new GroupAlreadyExistException();
}
return $this->logic->addGroupToEntity($idEntity, $nameGroup);
}
</code>```

As you can see this method has no "logic" per se (apart from the checks) and in the end it just forwards the request to the logic underneath. We are conflicted about how to correctly test this function. Do we mock everything? We can do it and in each test fake some "failures", but the problem remains that to test the correctness of the function you mock everything. Every single function. In that case you are not testing anything. We could really use some advice on this problem. Can anybody show us examples of a good way to test a function like this?

We use phpunit. Thank in advance for your help.

Body:
My opinion is that you mock everything.  You are making sure that the checks are acting correctly not the underlying logic in the function call that returns the true/false).  Mocking this also removes understanding the logic behind the function calls in each of the conditions.  And this test won't fail if/when that logic changes which would become a maintenance nightmare.

The main problem with that is in this line:

if ($idEntity != $this->getServiceLocator()->get('request')->getQuery()->get('idEntity'))

As you end up with a mock return a mock.  This is a code smell and violates the D in SOLID (http://en.wikipedia.org/wiki/Law_of_Demeter).  I would consider refactoring this so that you pass in the result of getQuery().

I would probably end up writing seperate tests for the exceptions and one for the success.  As the mocks for each would end up expecting different calls.

EDIT:
Keep in mind that the tests help provide insight into the expected behavior of the code,  and also for making sure that any changes in the logic do not break existing functionality.
If you want to change the conditions of addGroup, you can make sure that you have maintained existing functionality without having to dig into the underlying function calls.

Here is what the exception test would look like (using PHPUnit):

/**
 * @dataProvider dataExceptions
 */
public function testAddGroupExceptions($isActive, $inGroup, $id, $exception) {
    $this->expectsException($exception);

    $logic = $this->getMockBuilder('logic')->setMethods(array('isEntityActive', 'isAlreadyInGroup', 'addGroupToEntity'))->getMock();

    //Set number of calls to any to not tie to order in function
    $logic->expects($this->any())->method('isEntityActive')->will($this->returnValue($isActive));
    $logic->expects($this->any())->method('isAlreadyInGroup')->will($this->returnValue($isActive));

    //This is a fail case, so do not add group
    $logic->expects($this->never())->method('addGrouptToEntity');

    //Not doing all the mocks to get the 'idEntity'
    $query = $this->getMockBuilder('query')->setMethods(array('get'))->getMock();

    $query->expects($this->any())->method('get')->with('idEntity')->will($this->returnValue($id));

    $idEntity = 'test';
    $group = 'foo';

    //Instantiate the object - $test
    $test->addGroup($idEnity, $group);
}


答: Don't unit test trivial functions such as properties with no validation logic.  Your integration testing should adequately cover such methods.</p>


问:
Negative test cases confusion
In the Software testing book from Koirala, Sheihk, they say:

A positive test is when you put in a valid input and expect some
  action to be completed in accordance with the specification.

  A
  negative test is when you put in an invalid input and receive errors.

Part of my question:

Let's say there is a requirement: If the customer name=="James Bond", do something.

Is name<>"James Bond" negative or still positive test, verifying the requirement?

Or a login function:

Is correct login positive test case and incorrect negative?

Or Login failed is just confirmation of requirement that a password must be correct ->confirming invalid pass will not work.

For example, if the program is supposed to give an error when the person types in "101" on a field that should be between 1 and 100, then that is positive then if an error shows up. If, however, the application does not give an error when user types 101, then you have a negative test.

答:
You're messing up tests and conditions.

If you look at the illustration in the referred book, you'll see that Koirala and Sheikh do not talk about a decision branch, but a system as a whole.

They only look at valid system tests, i.e., blackbox tests, which results are correct.

So, in this context,

a positive test is, when you enter valid data, and the system does process it

a negative test is, when you enter invalid data, and the system does not process it (and ideally tells the user about that)

It does not matter, how the validity of the data is determined, or what exactly the wording of the requirement is.

Title: Negative test cases confusion


问:
Does the usage of LINQ and Lambda Expressions lead to less readable code?
I'm having a discussion with a co-worker on Linq, I'll copy here:

Co-Worker: Lets be honest here. Linq
syntax sucks. It's confusing and
non-intuitive.

Me: oh come on, more
confusing than T-SQL?

Co-Worker: uh,
yes.

Me: it has the same basic
parts, select, where, and from

Co-Worker: Linq, to me, is a
bastardization of relational + OO.
Co-Worker: Don't get me wrong - it's
incredibly powerful, but they
repurposed SQL to use agains object
collections.

I'm of the opinion that using Linq + Lamda's is very powerful (he agrees), and also makes code easier to read (he disagrees on that point):

pickFiles = from f in pickFolder.GetFiles("*.txt")
where ValidAuditFileName.IsMatch(f.Name)
select f;
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>var existing = from s in ActiveRecordLinq.AsQueryable<ScannedEntity>()
where s.FileName == f.FullName && s.DocumentType != "Unknown"
select s;
</code>```

or (VB code here)

   Dim notVerified = From image In images.AsParallel
     Group Join verifyFile In verifyFolder.GetFiles("*.vfy").AsParallel.Where(
      Function(v) v.Length > 0
      ).AsParallel
   On image.Name.Replace(image.Extension, ".vfy") Equals verifyFile.Name
     Into verifyList = Group
    From verify In verifyList.DefaultIfEmpty
    Where verify Is Nothing
    Select verify
```

To me this is clean and easy (at least easier than the alternatives) to read, what are your opinions on it?

答:
I saw a comment/remark where it stated something - in relation to LINQ/lambda - along the lines of: "Write code readable to humans, rather than readable to your computer".

I think that this statement has a lot of merit, however, consider the developer (such as myself) who has been through the full gamut of development languages from Assembly, through procedural, through OO, through managed, through leveraging high throughput task parallel solutions.

I have prided myself on making my code as readable and as reusable as possible and adopting many of the GOF design pattern principles in order to deliver production quality systems and services across a wide number of disparate business sectors.

The first time I encountered the lambda expression I thought: "What the hell is that!?!" It was immediately counter-intuitive to my familiar (and therefore comfortable) explicit declarative syntax. The younger < 5yrs in the job guys however lapped it up like it was manna from heaven!

That is because for years thinking like a computer (in the syntactic sense) translated very easily into direct coding syntax (irrespective of the language). When you have had that computational mindset for circa 20+yrs (30+ in my case) you have to appreciate that the initial syntactic shock of the lambda expression can easily translate into fear and mistrust.

Maybe the co-worker in the OP had come from a similar background as myself (i.e. been around the block a few times) and it was counter-intuitive to them at that time? My question is: what did you do about it? Did you try to re-educate your peer into understanding the benefits of the inline syntax, or did you pillory/ostracise them for not "being with the program"? The former would probably have seen your co-worker come round to your line of thinking, the latter would probably make them mistrust the LINQ/lambda syntax even more and thus exacerbating the negative opinion.

For myself I had to re-educate my own way of thinking (as Eric infers above, it's not an insignificant mind-shift, and I had to program in Miranda in the '80s so I've had my share of functional programming experience) but once I had gone through that pain the benefits were obvious but - more importantly - where its usage was over used (i.e. used for the sake of using it), over complex and repetitive (considering the DRY principle in that instance).

As someone who not only still writes a lot of code but who also has to technically review a lot of code it was imperative that I understood these principles so that I could review items impartially, advise where usage of a lambda expression may be more efficient/readable, and also to get developers to consider the readability of highly complex inline lambda expressions (where a method call would - in those cases - make the code more readable, maintainable and extensible).

So when someone says that they "Don't get lambda?" or LINQ syntax, rather than brand them a luddite try to help them understand the underlying principles. They may after all have an "old school" background such as myself.


问:
Web API URI Schema Design
I'm in the middle of designing an API for a very basic flashcard application for learning purposes and I'm wondering if you all think there can be any improvements.

In the app, a Folder contains Folders and Sets.  A Set contains Cards.  The Homepage lists any top-level Sets and Folders that the I've created (but never cards).  Here's the URI schema I've come up with:

Does this seem ok?  My goal is to keep the URIs terse/concise/simple and push any relationship metadata (parentFolderId, parentSetId, etc) into the body of the request.  Thoughts?

答:
It seems to me that the API would be more concise/simple if you structured your API to reflect the hierarchical structure of the data, partly because the structure would be self-documenting.

As it is, I don't see a way for a client to e.g. get the sets within a particular folder; with more structure you could do:

```<code>GET /folders/100/sets
</code>```

It really depends on what you think your clients will need to be able to do.

Also, I would probably support GET by returning a list for requests to a collection URL like /folders, but if you don't think it would be used for whatever reason, you'd probably want to return a status of 405 Method Not Allowed instead of an error.

Other than that, your use of POST, PUT, and DELETE seem correct to the best of my knowledge.

Just a note: one detail that's sometimes confusing is that PUT can also be used to create resources. The difference between that and POST is that, with PUT, your client already has the resource id and includes it in the request body; with POST you're expecting the service to create an id for the resource. You might use that differentiation if you're using a natural key to identify a resource, e.g. username for a user resource; in that case you would use PUT to create or update the user.

OwnerDisplayName: RobVious

Title: Web API URI Schema Design

Body:
It seems to me that the API would be more concise/simple if you structured your API to reflect the hierarchical structure of the data, partly because the structure would be self-documenting.

As it is, I don't see a way for a client to e.g. get the sets within a particular folder; with more structure you could do:

GET /folders/100/sets

It really depends on what you think your clients will need to be able to do.

Also, I would probably support GET by returning a list for requests to a collection URL like /folders, but if you don't think it would be used for whatever reason, you'd probably want to return a status of 405 Method Not Allowed instead of an error.

Other than that, your use of POST, PUT, and DELETE seem correct to the best of my knowledge.

Just a note: one detail that's sometimes confusing is that PUT can also be used to create resources. The difference between that and POST is that, with PUT, your client already has the resource id and includes it in the request body; with POST you're expecting the service to create an id for the resource. You might use that differentiation if you're using a natural key to identify a resource, e.g. username for a user resource; in that case you would use PUT to create or update the user.


问:
Best way to clear balances between payers and payees
Say some 20 people go to a shop and everyone buys something. When it comes to paying, 5 of them pay the complete amount of 10,000$ split unequally between them.

Since everyone bought different things they all owe different amounts to the payers. Now there are multiple ways the payers can clear the balances with the payees precisely 20 to the power 20.

My question is on what technical basis should the payers and payees contact each other for clearance? All the solutions can not be equally good, or are they?

One of the ways of clearing would be to find payers and payees with equal amount so that they can cancel out each other thus reducing the total number of transfers.

UPDATE:

People can transfer arbitrary amounts to anyone.

Minimizing total number of transfers is the main goal.

A payee can not pay an amount greater that what he owes and become secondary payer.

The output should be a list of suggested transfers. A suggested transfer would look like this {FromUser: a, ToUser: b, ClearanceAmount: 100}

The payers don't know who holds their debt.

The payees debt can be split across multiple payers.

The payees knows how much each payer paid from the total amount.

答:
This is a generalization of the subset sum problem.

In the simple case, where there are two payers, it is identical to the subset sum problem.  Either there is subset of debts exactly equal to the amount payed by one payer, or one payment must be split between the two payers.

The subset sum problem is NP complete, so there is no "fast" solution.


答:
To me, the difference between positive and negative tests is simple.

A positive test will verify that valid input is correctly processed. A negative test will verify that invalid input causes some validation to fail. (In a positive test, all validations will necessarily pass - if one doesn't, the test fails.)

Or in other words: if all validations are expected to pass for the given input/scenario, the test is positive; if at least one validation is expected to fail, the test is negative.

Therefore, in my understanding the book is wrong regarding the "101" example. In such a case, we would have a negative test for an invalid input, which must pass only if the associated validation (in this case, that the typed number is in the 1-100 range) fails.

This also means that, for some input which is not known to be valid or invalid, the behavior is undefined, with no tests for it.

Title: Negative test cases confusion

Body:
In the Software testing book from Koirala, Sheihk, they say:

A positive test is when you put in a valid input and expect some
  action to be completed in accordance with the specification.

  A
  negative test is when you put in an invalid input and receive errors.

Part of my question:

Let's say there is a requirement: If the customer name=="James Bond", do something.

Is name<>"James Bond" negative or still positive test, verifying the requirement?

Or a login function:

Is correct login positive test case and incorrect negative?

Or Login failed is just confirmation of requirement that a password must be correct ->confirming invalid pass will not work.

For example, if the program is supposed to give an error when the person types in "101" on a field that should be between 1 and 100, then that is positive then if an error shows up. If, however, the application does not give an error when user types 101, then you have a negative test.


问:
How do you keep from running into the same problems over and over?
I keep running into the same problems.  The problem is irrelevant, but the fact that I keep running into is completely frustrating.

The problem only happens once every, 3-6 months or so as I stub out a new iteration of the project.  I keep a journal every time, but I spend at least a day or two each iteration trying to get the issue resolved.

How do you guys keep from making the same mistakes over and over?

I've tried a journal but it apparently doesn't work for me.

[Edit]

A few more details about the issue:  Each time I make a new project to hold the files, I import a particular library.  The library is a C++ library which imports glew.h and glx.h GLX redefines BOOL and that's not kosher since BOOL is a keyword for ObjC.

I had a fix the last time I went through this.  I #ifndef the header in the library to exclude GLEW and GLX and everything worked hunky-dory.

This time, however, I do the same thing, use the same #ifndef block but now it throws a bunch of errors.  I go back to the old project, and it works.  New project no-worky.

It seems like it does this every time, and my solution to it is new each time for some reason.  I know #defines and #includes are one of the trickiest areas of C++ (and cross-language with Objective-C), but I had this working and now it's not.

答: I use full-text search of my email like a knowledge base and have for a dozen years. When I have a new issue I resolve that I know I'll need to remember, if there is no relevant email chain I'll just send a mail to myself so that it will get pulled up the next time I have the problem and go casting about for the answer. Not really different from a journal; the key to this is that I always already search my email if I know I've seen a particular issue before.</p>

ContentLicense: CC BY-SA 2.5


问:
How to measure team productivity?
The upper management at our company has laid out a goal for our software team to be “15% more productive” over the next year. Measuring productivity in a software development environment is very subjective, but we are still required to come up with a set of metrics.

What sorts of data can we capture that would measure our team’s productivity?

答:
I try very hard not to write non-answers on this site but I do believe that, in this case, I have to. It's the only right answer. But I'll try to help you out with more than a quip and a "you can't."

In all seriousness, there is no valid measure of developer productivity. I know this is hard for managers to cope with, but it's a fact. Refer them to a few links from people very experienced in the field. For a couple of examples:

Martin Fowler

So not just is business value hard to measure, there's a time lag too. So maybe you can't measure the productivity of a team until a few years after a release of the software they were building.

I can see why measuring productivity is so seductive. If we could do it we could assess software much more easily and objectively than we can now. But false measures only make things worse. This is somewhere I think we have to admit to our ignorance.

Joel Spolsky

Let's start with plain old productivity. It's rather hard to measure programmer productivity; almost any metric you can come up with (lines of debugged code, function points, number of command-line arguments) is trivial to game, and it's very hard to get concrete data on large projects because it's very rare for two programmers to be told to do the same thing.

Also ask them who is responsible for that increase. What measures are they allowed to take?

It is my experience that managers set these goals because they have zero clue what goals to set with respect to development teams. Maybe you can help them out with that.

Explain to them that you (or the team) want to take your targets seriously, but they have to be SMART or they're meaningless. Suggest to them some targets which are SMART. do you have a build/CI server? If not, setting one up is a SMART goal. If so, do you have some way of displaying quality statistics? If not, setting that up is also a SMART goal.

If so, then you have something that's very measurable: code quality. Maybe bringing your technical-debt rating down is a SMART goal, which will in turn improve productivity, unless they're assuming that people are slacking off, in which case you have an entirely different problem to solve: visibility.

Help them to give you targets you can actually achieve. There's no satisfaction in having goals that cannot be proven or disproven a year from now, or where you'll be wasting time gaming the system rather than improving it.

Title: How to measure team productivity?


答:
Instead of trying to focus on metrics for programmers which as others have suggested are incredibly imprecise, try suggesting non-code things like the following:

XGb memory for everyone's PCs (where x is more than you have) and quad core

2 monitors for all (3 if you already get 2)

Desks away from loud employees like managers, support, sales that are always on the phone

better specs

Less context switching between multiple projects, or because of changing specs

Less meetings, and better focus/consideration for staff being invited to meetings

Explain in detail why each of these things will actually make a programmer more productive.

These are the types of things that can drive programmer productivity, not trying to set some unachievable targets around LOC, or bug count.

Title: How to measure team productivity?

Body:
The upper management at our company has laid out a goal for our software team to be “15% more productive” over the next year. Measuring productivity in a software development environment is very subjective, but we are still required to come up with a set of metrics.

What sorts of data can we capture that would measure our team’s productivity?


答:
One of my most productive days was throwing away 1000 lines of code.

```<code>    — Ken Thompson, designer of the original Unix operating system
</code>```

Measuring software productivity isn't really that difficult, although it's somewhat imprecise.  Survey your programmers and ask what percentage of their working time is wasted on non-productive tasks, and what those are.  Have them focus not on personal productivity issues, but on non-productive assigned work tasks.  Some examples are:

Waiting for slow source control updates

Requirements changing

Too many interruptions

Compiles are too slow

Performing regression testing

Marketing cancelling projects after you've put significant work into them

Spending too much time doing status updates

Spending too much time on unexpected bugs reported from QA or the field

Waiting on dependencies from other teams

Unraveling spaghetti code

However, due to an observer effect, it's impossible to tie those survey results to any sort of reward or consequence to the programmer, including having management angry that productivity didn't increase 15%.  They will game the system even if they suspect that's how the numbers are used, and you end up with a completely useless metric.

What you can do is use the responses to move productivity in the right direction.  Pick the worst two or three and put a lot of effort into it.  Improvement can easily be measured numerically for many of the individual complaints, and hopefully when you do the survey again next year, some of the complaints will no longer be listed, or at least be reported by fewer of your programmers.

In other words, you can observe movement in the right direction, even if you can't quantify it.

Title: How to measure team productivity?

Body:
One of my most productive days was throwing away 1000 lines of code.

    — Ken Thompson, designer of the original Unix operating system

Measuring software productivity isn't really that difficult, although it's somewhat imprecise.  Survey your programmers and ask what percentage of their working time is wasted on non-productive tasks, and what those are.  Have them focus not on personal productivity issues, but on non-productive assigned work tasks.  Some examples are:

Waiting for slow source control updates

Requirements changing

Too many interruptions

Compiles are too slow

Performing regression testing

Marketing cancelling projects after you've put significant work into them

Spending too much time doing status updates

Spending too much time on unexpected bugs reported from QA or the field

Waiting on dependencies from other teams

Unraveling spaghetti code

However, due to an observer effect, it's impossible to tie those survey results to any sort of reward or consequence to the programmer, including having management angry that productivity didn't increase 15%.  They will game the system even if they suspect that's how the numbers are used, and you end up with a completely useless metric.

What you can do is use the responses to move productivity in the right direction.  Pick the worst two or three and put a lot of effort into it.  Improvement can easily be measured numerically for many of the individual complaints, and hopefully when you do the survey again next year, some of the complaints will no longer be listed, or at least be reported by fewer of your programmers.

In other words, you can observe movement in the right direction, even if you can't quantify it.


答:
I agree with pdr's answer. That's the way to go. However, here's another take.

Most process improvement efforts need to start, as you have, with deciding what to measure and then baselining current operations.

What to use as a baseline?

How about Joel's twelve questions?

If you're not already doing 11 or 12, then you only need to do another 2 and you get your 15% improvement.

Title: How to measure team productivity?


问:
Term for a Class with Multiple Interfaces
Say I have a class that implements multiple interfaces. I pass the same instance around using a different interface, depending on what the consumer is interested in.

I am trying to remember what this is called. I know there is a fancy name for it - I thought it was "interface partitioning", but I'm not finding any hits. The official name and perhaps a link to a site explaining what it is would be handy.

In case I haven't explained myself well enough, here is a real world example. I have a class, call it ContextManager, that is responsible for providing access to configuration settings, session variables, user information and other utilities. Instead of passing the object around as a ContextManager, I might pass it around as an IConfigurationManager in one spot and as a IUserManager in another. This prevents the client from accessing things they shouldn't care about and allows me to reuse code within the class.

I just want to know what it is called?

答:
You're describing the facet pattern, which is used to restrict an interface to obtain a smaller interface that provides less authority.  Inheriting multiple interfaces is one common way to implement this pattern.

This is related, but not identical, to the Interface Segregation Principle, which is the 'I' in SOLID.  That principle states that no client should be forced to depend on methods it does not use.  The facet pattern is a way to adapt that principle to a large class.  However, there are other more common ways to follow the interface segregation principle, such as creating smaller classes.


问:
What is the equivalent of Entity Framework in the world of Oracle shops?
Within the world of developers/firms specializing in building/deploying solutions built around software built/sold by Oracle (aka "Oracle houses"), what ORM middleware is considered as the "industry standard" (if any), based on your experience?

We have limited experience on Oracle's stack, so would appreciate insights from folks who have more experience in it. This might impact our product roadmap.

答:
Depends on the client language used. If you use C# to access an Oracle DB, you might use EF (and suffer the performance problems it has with Oracle, not sure if they were introduced deliberately :) ).

If you use Java you might want to use Hibernate. If you're an all-Oracle shop this is probably what you'll end up using.

There are others, and any of them are available for use with an Oracle DB, nHibernate for example!


答:
There is much field to cover between immutable types and exposing all the internals of your class through public setters.

A typical construct used for mutating immutable types is having methods akin to setters that return a copy of the object with updated values of certain fields - that is instead of having this:

```
public void setName (string value) {
   this.name = value;
}
```

you have something like this:

```
public Customer withName (string value) {
   Customer cust = this.Clone();
   cust.name = value;
   return cust;
}
```

That way you can have an immutable object that you can essentially update. Languages like F# have syntax sugar for similar operations on records, but in less functional OOP languages this seems unnatural. But anyway, this is probably not what you want to do.

What makes immutable state appealing is the fact that it makes lot of things easier to reason about, since the state won't change through a side effect in a piece of unrelated code - less places for things to go wrong. But it's just a means to the same end OOP languages encourage encapsulation for.

Instead of relying on setters, keep the updating logic inside the class. Same effect - less buttons to push and levers to pull to put your object in some unexpected and undesired state. Keep a well-defined interface for the consumers of your object to use and there will be no need for generic getters and setters.

It's more work than having your domain objects as simple Data Transfer Objects and it may sometimes be not worth it, so it's a judgement call. But if you're doing anything remotely complex with your object (and seeing you're looking at 30+ fields, you likely are), it might be well worth the effort.

Title: When is it inappropriate to make objects immutable?

Body:
I have a class which represents an entity object in our system (for sake of argument, a Customer object)

```<code>public class Customer()
{
  private int id;
  private String name;
  ... // 30+ fields

  public Customer()
  {
    // empty constructor!
  }

  // getters and setters
}
</code>```

I'm trying to refactor this so that the fields are extracted into their own objects where they are more sensibly grouped, and at the same time creating parameterised constructors - with the intent I could then lose the setter methods and make my objects immutable (since this is apparently a Good Thing(TM)).

However, this doesn't make any sense - sometimes I need to update a customer's information! It's clearly not immutable. Should I just not make this class immutable - and can I apply the same argument to all my entity classes?

Body:
There is much field to cover between immutable types and exposing all the internals of your class through public setters.

A typical construct used for mutating immutable types is having methods akin to setters that return a copy of the object with updated values of certain fields - that is instead of having this:

public void setName (string value) {
   this.name = value;
}

you have something like this:

public Customer withName (string value) {
   Customer cust = this.Clone();
   cust.name = value;
   return cust;
}

That way you can have an immutable object that you can essentially update. Languages like F# have syntax sugar for similar operations on records, but in less functional OOP languages this seems unnatural. But anyway, this is probably not what you want to do.

What makes immutable state appealing is the fact that it makes lot of things easier to reason about, since the state won't change through a side effect in a piece of unrelated code - less places for things to go wrong. But it's just a means to the same end OOP languages encourage encapsulation for.

Instead of relying on setters, keep the updating logic inside the class. Same effect - less buttons to push and levers to pull to put your object in some unexpected and undesired state. Keep a well-defined interface for the consumers of your object to use and there will be no need for generic getters and setters.

It's more work than having your domain objects as simple Data Transfer Objects and it may sometimes be not worth it, so it's a judgement call. But if you're doing anything remotely complex with your object (and seeing you're looking at 30+ fields, you likely are), it might be well worth the effort.


问:
implications of a large partial class
I'm writing a middle layer between vendor code and company business logic. Part of the exercise is to insulate our business logic from vendor's types to make swapping out vendor code easier.

As such, I'm writing a lot of extension methods that do translation to and from. I'm placing these extensions in public static partial classes. For organizational purposes and simply because, for static extension methods, the class it self does not matter(is this a correct assumption btw?)

EDIT:
  To be clear I'm creating a lot of different appropriately named source files, that all implemented one partial class

My question is, how much code is too much for a partial class. I could conceive having 100's of methods in a single class(at some point). When does this become a burden for the compiler and CIL layer? Is there really a limit if these partials classes hold no state/memory?

答:
TLDR: A single class with hundreds of methods is just fine, you won't get into problems unless you have thousands of methods.

To test this properly, I have created the following T4 template in Visual Studio:

class LotsOfMethods
{
    <# for (int i = 0; i < 100; i++) { #>
    public static void M<#= i #>()
    {
    }
    <# } #>
}
```

<p>By varying the constant in the loop, I can find out how do various numbers of methods behave. As it turns out, 100, 1 000, 10 000 or even 100 000 methods compile just fine (though in the latter cases, the compilation takes longer than a single project with one or two classes normally would and VS also sometimes freezes for few seconds).</p>

<p>When I tried to actually run the code, the cases with 100, 1 000 or 10 000 methods were all fine. The interesting part is that when you try to use the class with 100 000 methods, you'll get an exception:</p>

<blockquote>
  <p>System.TypeLoadException: Type 'LotsOfMethods' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' contains more methods than the current implementation allows.</p>
</blockquote>

<p>Specifically, this exception happens when the class has 65 521 (2<sup>16</sup>-15) methods or more. (An interesting question is why exactly this number. What does the 15 mean?)</p>

<p>Another observation is that more methods in a class make JIT compilation slower. (Or is it more methods in an assembly? I haven't tested that.) When executing 500 of the methods I get the following results:</p>

<p>For a class with 65 520 methods:</p>

<pre class="lang-none prettyprint-override"><code>For the first time: 2,2079481 s
For the second time: 0,0003259 s
</code>```

With 1 000 methods:

For the first time: 0,0545898 s
For the second time: 0,0003138 s
```

<p>And 500 methods:</p>

<pre class="lang-none prettyprint-override"><code>For the first time: 0,0361426 s
For the second time: 0,0003226 s
</code>```

The results were measured using the following code:

var sw = Stopwatch.StartNew();

int n = 500; // this is constant no matter how many methods does the class have

for (int i = 0; i < n; i++)
{
    typeof(LotsOfMethods).GetMethod(string.Format("M{0}", i)).Invoke(null, null);
}

var first = sw.Elapsed.TotalSeconds;
sw.Restart();

for (int i = 0; i < n; i++)
{
    typeof(LotsOfMethods).GetMethod(string.Format("M{0}", i)).Invoke(null, null);
}

var second = sw.Elapsed.TotalSeconds;

Console.WriteLine("For the first time: {0} s", first);
Console.WriteLine("For the second time: {0} s", second);
```

Title: implications of a large partial class

Body:
TLDR: A single class with hundreds of methods is just fine, you won't get into problems unless you have thousands of methods.

To test this properly, I have created the following T4 template in Visual Studio:

class LotsOfMethods
{
    <# for (int i = 0; i < 100; i++) { #>
    public static void M<#= i #>()
    {
    }
    <# } #>
}

By varying the constant in the loop, I can find out how do various numbers of methods behave. As it turns out, 100, 1 000, 10 000 or even 100 000 methods compile just fine (though in the latter cases, the compilation takes longer than a single project with one or two classes normally would and VS also sometimes freezes for few seconds).

When I tried to actually run the code, the cases with 100, 1 000 or 10 000 methods were all fine. The interesting part is that when you try to use the class with 100 000 methods, you'll get an exception:

System.TypeLoadException: Type 'LotsOfMethods' from assembly 'ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' contains more methods than the current implementation allows.

Specifically, this exception happens when the class has 65 521 (216-15) methods or more. (An interesting question is why exactly this number. What does the 15 mean?)

Another observation is that more methods in a class make JIT compilation slower. (Or is it more methods in an assembly? I haven't tested that.) When executing 500 of the methods I get the following results:

For a class with 65 520 methods:

For the first time: 2,2079481 s
For the second time: 0,0003259 s

With 1 000 methods:

For the first time: 0,0545898 s
For the second time: 0,0003138 s

And 500 methods:

For the first time: 0,0361426 s
For the second time: 0,0003226 s

The results were measured using the following code:

var sw = Stopwatch.StartNew();

int n = 500; // this is constant no matter how many methods does the class have

for (int i = 0; i < n; i++)
{
    typeof(LotsOfMethods).GetMethod(string.Format("M{0}", i)).Invoke(null, null);
}

var first = sw.Elapsed.TotalSeconds;
sw.Restart();

for (int i = 0; i < n; i++)
{
    typeof(LotsOfMethods).GetMethod(string.Format("M{0}", i)).Invoke(null, null);
}

var second = sw.Elapsed.TotalSeconds;

Console.WriteLine("For the first time: {0} s", first);
Console.WriteLine("For the second time: {0} s", second);


答:
Mike Partridge has the right answer above, but I just wanted to add.

Here's a good reference for the type of responses you should send to your restful requests.

Specifically, you should return 404 alongside PUT/DELETE requests to the collection (/folders) as well as for POST requests to the object (/folders/id).

Also, resources tend to be nested when it's relevant/appropriate to do so.

It seems like in your case, folders will always be a top level element, sets will always be in a folder, and cards will always be in sets, thus:

/folders/:id/sets/:id/cards/:id should be an allowed resource

I've seen this refered to as the digging-deeper-path-and-backspace convention where it's easy to move up the tree simply by backspacing to the last /

The last link I provided has a lot of example URLs that you might use in a RESTful scheme. Another example excludes the collection names for child resources when only a specific child resource may exist at n-level:

/folder/:id/:set_id/:cards_id

I apologize if I caused more confusion. My point is there are a lot of options that are considered acceptable by different groups. Whatever convention you go with, just keep it consistent, and have good documentation for anyone who ends up using your API.

Title: Web API URI Schema Design

Body:
I'm in the middle of designing an API for a very basic flashcard application for learning purposes and I'm wondering if you all think there can be any improvements.

In the app, a Folder contains Folders and Sets.  A Set contains Cards.  The Homepage lists any top-level Sets and Folders that the I've created (but never cards).  Here's the URI schema I've come up with:

Does this seem ok?  My goal is to keep the URIs terse/concise/simple and push any relationship metadata (parentFolderId, parentSetId, etc) into the body of the request.  Thoughts?


答:
Using .NET you're able to use EF with the Oracle Data Provider. You can also use nhibernate for a RDBMS agnostic framework.

If you're in the Java world you have a few big ORM choices: Hibernate, TopLink and I've also come across Apache OpenJPA being used. In my experience with Java, Hibernate tends to be used more often and I've not commercially seen TopLink used before.

For an Oracle house, the typical stack would be:

Java / JEE

An application server, I typically see Jetty or Tomcat

Hibernate

Spring

Eclipse for development

Maven for building

Title: What is the equivalent of Entity Framework in the world of Oracle shops?

Body:
Within the world of developers/firms specializing in building/deploying solutions built around software built/sold by Oracle (aka "Oracle houses"), what ORM middleware is considered as the "industry standard" (if any), based on your experience?

We have limited experience on Oracle's stack, so would appreciate insights from folks who have more experience in it. This might impact our product roadmap.


答:
Firstly (and probably unintentionally) your examples using * comparisons* tend to confuse the issue., getting the comparison "a <> b" which sounds sort of negativeish confused with the a test of whether the comparison was implemented correctly (a positive test).

So positive tests are where you test to see whether the system implements a use case correctly. (Think of a test for the vending machine use case "customer gets can of coke").

Negative tests are where you test to see if exceptions to a use case are handled properly. (Think of an exception in the above use case "user input foreign coins").

A positive test case passes if the use case succeeds.

A negative test case passes if the use case fails.

and vice versa.

Title: Negative test cases confusion


答:
In my opinion, for programmers there's only 1 metric that makes sense: the number of developers who leave to do similar work for another company.

If one programmer is unhappy enough to find a job elsewhere, it's very likely that a lot of other programmers are also unhappy and performing badly.

Title: How to measure team productivity?


答:
I think it is difficult to do, but possible, if you use good case management software like FogBugz and keep track of old data.  Obviously you can't say that we will improve performance by an exact number like 15%, but you can definitely do something about it.
So let's say you have:

5 developers

1 month release cycle

These have to be pretty consistent from release to release, otherwise accounting for those can get messy.  Here are some things you can measure and improve.

-- Estimates vs actual dev time.

Similar to Agile velocity.
If developers are planning to work whole month let's say 20 days or 100 days for 5 devs this month.  They estimated all their tasks and told management that they can fit all the features.  But it actually took 120 days instead of 100 days.

the 20 days (4 extra days for 5 devs), developers where under a lot of pressure and wrote a lot of spaghetti code.

So to improve performance - increase estimates for next month by 20% and see how much closer it becomes to actual time.  Keep updating it for future releases if it is still way off the mark. The performance improvement will not be 20%, but should be substantial, since there is going to be a lot less stress, bugs, and working weekends.

-- Amount of time spent by developers for fixing bugs found by QA

Let's say for this rollout, it took 5 man/days for QA to test.

You can try to improve this number by having less bugs:

Introduce Dev automated testing

Make sure to allocate time for Refactoring and optimization before QA gets to it

Code reviews

Keep measuring bug fixin time every release and you should see improvements if you introduce the things above.

-- Do some research on bottlenecks to development

You may find that there are other things, like communication between Business Side and developers, that are having a huge negative effect on performance.  Many times a project can be delayed because of scope creep or feature requirements not clearly communicated.  This usually happens over and over again.

This one is a bit hard to measure, but use can use measurements from 1. for this.

-- Type Faster...

Words per minute is a proven way to measure performance not only for developers but also anyone else using computers.

-- Measuring dev performance ain't easy

As other people already mentioned it is not easy thing to do, so how you communicate it to "upper management" is really important.  They need to understand that measuring development is not like measuring sales. There is no hard numbers, but there are definitely some things you can improve.  So you can give them a plan with some of the improvements and use measures from step 1. and 2. to demonstrate if there is improvement.

Title: How to measure team productivity?


问:
Tracking scientific error when working with floating-point numbers
Background

I hate the way .Net/IEEE-754 handles equality of floating-point numbers (FPNs) (i.e. double, float). It requires the programmer to be prescient with respect to the yet-to-be-determined history of the number, as the programmer must choose a 'reasonable' value of epsilon where frequently no such value can be determined (as the programmer cannot determine ahead of time how many operations, hence roundings, the number will be subject to).

I would like to create a 'better' FPN within .Net. At creation, one would set its initial scientific error (or accept a default; the default being the minimum). When one performed operations on the FPN, those operations would update the scientific error (to account for the effect of rounding). When testing the equality of two FPNs, one could determine if their ranges overlapped (and even the probability that they are the same number).

Question

The code itself is simple, my questions are:

How do operations (+ - * / to start with) affect the scientific error of a FPN? Are there formulae for determining this scientific error?

I understand that an added complication is the uneven distribution of FPNs. This can obviously be accounted for by scaling the error in proportion to the inherent scientific error of the result; but is there a formula for determining the inherent scientific error present in a given FPN?

答: It has already been done, see Interval arithmetic. This type of automatic floating-point error analysis gives you a reliable upper bound on the accumulated rounding error. Perhaps the biggest disadvantage is the Dependency problem which can lead to correct but way too conservative error bounds.</p>

OwnerDisplayName: Mark

OwnerDisplayName: Ali


问:
Team switching from TFS Source Control to TFS with Git, not sure how to handle complex project structure
I've used git for my personal projects for years, but that's always working alone, not needing to branch much, etc.

Our development team at work has decided we are definitely switching to git, and as one of the most experienced git user on the team I have the task of figuring out our project structure.

Our current structure has a single Source Control, with many Projects.  Those source control "projects" may contain multiple folders which contain multiple Visual Studio Solutions which can contain multiple Visual Studio Projects, some of which are shared.

An example:

Main Directory

Folder 1

Solution 1

Project 1

Shared Project 1

Folder 2

Solution 2

Project 2

Project 3

Solution 3

Project 4

Shared Project 1

Shared Project 2

Folder 3

Solution 4

Shared Project 1

Shared Project 2

I am not sure at all how to translate this to git properly.  The main concern that has been mentioned to me is that if we use git submodules, when checking in changes it has to be applied to multiple repositories.  Is there a way around this?  Does TFS in Visual Studio handle this in an easy to manage way?

Anyone have any good information about this kind of thing?

答:
It depends on how closely coupled the modules are. And mainly how closely coupled they are in organizational terms.

All modules developed by the same team in context of the same project (in management sense of the word) should probably go in one repository, especially if it's possible that a logical change will span more than one of them.

Modules that are developed separately, they should live in separate repositories. But than there should also be at least semi-formal release process for providing the results of one project to the other. Not because of git but to reduce communication overhead especially when a bad commit in one project would affect many people in other projects.

Git will happily work with hundreds of thousands of files. It will work if you split or if you don't. So the decision to split is organizational. You want some barrier between teams so mistakes don't affect too many people and you want reasonably small teams to limit the communication overhead (20 people is rather large team).


问:
Why is Option/Maybe considered a good idea and checked exceptions are not?
Some programming languages like e.g. Scala have the concept of Option types (also called Maybe), which can either contain a value or not.

From what I've read about them they are considered widely to be a superior way of dealing with this issue than null, because they explicitly force the programmer to consider the cases where there might not be a value instead of just blowing up during runtime.

Checked Exceptions in Java on the other hand seem to be considered a bad idea, and Java seems to be the only widely used language that implements them. But the idea behind them seems to be somewhat similar to the Option type, to explicitly force the programmer to deal with the fact that an exception might be thrown.

Are there some additional problems with checked Exceptions that Option types don't have? Or are these ideas not as similar as I think, and there are good reasons for forcing explicit handling for Options and not for Exceptions?

答:
because with Maybe you can delay handling the error until you actually need the value (which may be a few method calls away)

whereas the checked exception needs to be handled at the call location

the only upside to exceptions is that more information can be passed about why it failed (unless someone develops a MaybeError with a throwable field when it's an error)


答:
While related, exceptions and Maybe objects do not deal with the same type of problems.

Exceptions

Exceptions really shine when you have to deal non-locally with an exceptional situation (which in some cases happens to be an error). For example you are parsing a csv, and want to protect yourself against lines with wrong formatting. The place where you find that something is wrong may be some function calls away from the line iteration. If you throw an exception at the deepest level (where you find out about the formatting issue), you can catch it in the loop, log the error, and proceed to the next line. You don't have to modify anything in the rest of the code.

Checked exception adds a lot of pain because all the intermediate functions have to declare the throwable type. The feature defeats the original purpose, which is why they are not popular nowadays.

Maybe objects

Maybe objects should be choosen when you are able to deal locally with a "failure". In that sense, they are a replacement for a return code + pass by reference api or a nullable type.

The advantage of the Maybe object is that you explicitly declare that something might be wrong. In haskell, a non maybe object has to have a value, or else the program won't compile.

The problem with nullable types is that you have to check for null all the time to be absolutely safe. The "something might be wrong" state is the default one.

The problem with return codes + pass by ref apis is that they are less readable for most people.

Title: Why is Option/Maybe considered a good idea and checked exceptions are not?

Body:
Some programming languages like e.g. Scala have the concept of Option types (also called Maybe), which can either contain a value or not.

From what I've read about them they are considered widely to be a superior way of dealing with this issue than null, because they explicitly force the programmer to consider the cases where there might not be a value instead of just blowing up during runtime.

Checked Exceptions in Java on the other hand seem to be considered a bad idea, and Java seems to be the only widely used language that implements them. But the idea behind them seems to be somewhat similar to the Option type, to explicitly force the programmer to deal with the fact that an exception might be thrown.

Are there some additional problems with checked Exceptions that Option types don't have? Or are these ideas not as similar as I think, and there are good reasons for forcing explicit handling for Options and not for Exceptions?


答:
Because Options are composable. There are a lot of useful methods on Option that allow you to write concise code, while still allowing precise control on the flow: map, flatMap, toList, flatten and more. This is due to the fact that Option is a particular kind of monad, some objects that we know very well how to compose. If you did not have these methods and had to pattern match always on Option, or call isDefined often, they would not be nearly as useful.

Instead, while checked exceptions do add some safety, there is not much you can do with them other than catching them or let them bubble up the stack (with the added boilerplate in the type declaration).


问:
Best language or tool for automating tedious manual tasks
We all have tasks that come up from time to time that we think we'd be better off scripting or automating than doing manually.

Obviously some tools or languages are better for this than others - no-one (in their right mind) is doing a one off job of cross referencing a bunch of text lists their PM has just given them in assembler for instance.

What one tool or language would you recommend for the sort of general quick and dirty jobs you get asked to do where time (rather than elegance) is of the essence?

Background: I'm a former programmer, now development manager PM, looking to learn a new language for fun.  If I'm going to learn something for fun I'd like it to be useful and this sort of use case is the most likely to come up.

答: A modern unix shell. E.g. bash. </p>

Body: A modern unix shell. E.g. bash.


答:
Ah, the old "shared projects".. for those who don't use TFS (or VSS) you can create a kind of symlink inside your repo so a single project appears to be in 2 places at once. This is what is being used here.

To my knowledge, no other SCM has this feature. IMHO this is a good thing as it makes you think of each project as an independent entity and not mix it up inside projects - I think its only really usefulness is if your IDE doesn't handle external references well...

So, if you want to migrate away, you're going to have to split these shared projects into a different project structure, and build them separately. then change your projects so they build with references to the sub-projects. Do not try to keep the same mind-set of keeping these projects in the existing tree/solution structure. Your solutions will not be able to contain all the projects within them. MS has some guidelines for organising your SCM, you'll have to move from the 'partitioned solution' model to the 'multiple solutions' model.

you'll have to manage dependencies between the projects, but that's not so hard if you have a good CI system that will build a chain of dependencies when 1 changes (I recommend Jenkins, its as powerful yet much simpler than the unmaintainable xaml-based build TFS2012 now uses)

Title: Team switching from TFS Source Control to TFS with Git, not sure how to handle complex project structure

Body:
I've used git for my personal projects for years, but that's always working alone, not needing to branch much, etc.

Our development team at work has decided we are definitely switching to git, and as one of the most experienced git user on the team I have the task of figuring out our project structure.

Our current structure has a single Source Control, with many Projects.  Those source control "projects" may contain multiple folders which contain multiple Visual Studio Solutions which can contain multiple Visual Studio Projects, some of which are shared.

An example:

Main Directory

Folder 1

Solution 1

Project 1

Shared Project 1

Folder 2

Solution 2

Project 2

Project 3

Solution 3

Project 4

Shared Project 1

Shared Project 2

Folder 3

Solution 4

Shared Project 1

Shared Project 2

I am not sure at all how to translate this to git properly.  The main concern that has been mentioned to me is that if we use git submodules, when checking in changes it has to be applied to multiple repositories.  Is there a way around this?  Does TFS in Visual Studio handle this in an easy to manage way?

Anyone have any good information about this kind of thing?


问:
Multiple threads and single output source
For the sake of an exercise, say you have an input file with a series of lines of text with the objective of reversing their respective character sequences.

Now introduce 5 threads that will each do the reversing, thread 1 taking care of line 1, thread 2 taking care of line 2 and so on.

If the aim is to save these reversed lines in order, how would you save them to the same file ?

P.S: I've thought of having some kind of queue but there is no guarantee on the order. Also, I'm wondering if there's some way to lock the file temporarily and have a thread wait it's turn. I imagine I should keep track of which line is being saved.

答:
I put this out completely without comment. If you don't understand what it's doing, feel free to ask. If you're planning to submit it as an interview response, be prepared to discuss.</p>

```<code>public class SequencedThread {

    private final Runnable runnable;
    private final SequencedThread predecessor;

    public SequencedThread(Runnable runnable, SequencedThread predecessor) {
        this.runnable = runnable;
        this.predecessor = predecessor;
    }

    public void run() {
        try {
            if (predecessor != null) {
                predecessor.join();
            }
        }
        catch (InterruptedException ex) {
            // do something here
        }

        runnable.run();
    }
}
</code>```

Body:
I put this out completely without comment. If you don't understand what it's doing, feel free to ask. If you're planning to submit it as an interview response, be prepared to discuss.

public class SequencedThread {

    private final Runnable runnable;
    private final SequencedThread predecessor;

    public SequencedThread(Runnable runnable, SequencedThread predecessor) {
        this.runnable = runnable;
        this.predecessor = predecessor;
    }

    public void run() {
        try {
            if (predecessor != null) {
                predecessor.join();
            }
        }
        catch (InterruptedException ex) {
            // do something here
        }

        runnable.run();
    }
}


问:
Should methods always be closed for modification?
Say I have a method called 'functionA' that is called by a service and carries out a single piece of functionality, it is easy to unit test as it is does one thing only.

If a few months later an new requirement comes in that requires another method 'functionB' to be called directly after 'functionA' has executed. What is the better approach to add functionB to my code.

to call 'functionB' at the end of the 'functionA' method:

```<code>functionA() {
    //do something..

    functionB();
}

functionB() {
    //do somehting...
}
</code>```

Problem with this is that when I unit test functionA it will call functionB that will also be part of the test (so now it is more of an integration test).

Or refactor the code with a new method 'functionX' that calls 'functionA' and then 'functionB'?

```<code>functionX() {
    functionA();
    functionB();
}

functionA() {
    //do something..
}

functionB() {
    //do somehting...
}
</code>```

I can unit test both methods individually but now I have changed the API.

I see the first approach so much in legacy code, is it best practice to always make methods closed for modification or are there examples when it is OK to use the first approach?

答:
My rule of thumb is that when adapting a design, you should aim to make the design as you would have were you starting from scratch. Don't make your design sub-optimal now because of the characteristics of some previous design. The only result of that will be a big mess of a code base.

The fact that you need to modify this function says there was a problem with your original design. It did a poor job of adapting to requirements. Ideally, you shouldn't have to modify your code in order to adapt to requirements. (Its a bit of an unattainable goal, but it's the goal nonetheless).

So you've learned something about how requirements tend to change. Using that knowledge, how would have designed this piece of code to make it easier to make those sorts of changes in future? How can you avoid breaking unit tests, ease implementation?

Of course, your example is too vague to know what the best approach is. But I'd say: don't be afraid to modify the function, but keep in mind that you want to produce designs that won't require you to modify it for future uses.

The situation is somewhat different if you are writing code that other projects will use. For them any change of functionality, even just fixing bugs, can cause problems. There care needs to be taken. However, if its just your code, I don't think thats a concern.


答:
you need what I would call a producer-transformer-consumer solution

you can adapt an existing produce-consumer but each element has a complete flag

there will be 3 pointers: one for the head; one for the tail and one for the "stomach" which point to the next element that needs transforming

the tail can't advance past a element that doesn't have the complete flag set,

the stomach pointer advances as the concurrent threads pull elements (without removing it from the queue) to transform and sets the complete flag only when the transformation is done

Title: Multiple threads and single output source

Body:
For the sake of an exercise, say you have an input file with a series of lines of text with the objective of reversing their respective character sequences.

Now introduce 5 threads that will each do the reversing, thread 1 taking care of line 1, thread 2 taking care of line 2 and so on.

If the aim is to save these reversed lines in order, how would you save them to the same file ?

P.S: I've thought of having some kind of queue but there is no guarantee on the order. Also, I'm wondering if there's some way to lock the file temporarily and have a thread wait it's turn. I imagine I should keep track of which line is being saved.


问:
What are good Information System design resources?
After taking a class about information systems, I want to find additional resources for learning the various patterns, concepts, and examples of their implementation. The course did focus on Martin Fowler's Principles of Enterprise Application Architecture and had a project that attempted to implement some of them.

Basically, where can I learn more about Information System design and implementation?

答:
Well, if you are looking for examples from a Coders point of view - this book - Core J2EE Patterns helped me a lot when I was first starting out developing Enterprise applications in Java.  It's examples are specific to Java, but they can easily be applied to most OOP languages.  Of course, there is always the Gang of Four book.

However, if you are looking for more high level concepts... go no further than Fowlers own Domain Specific Languages or something like this.  Also, it never hurts to read classics like Mythical Man-Month or CODE Complete to get overview of what it will take to design, develop and deliver enterprise solutions. (Even if those last two are not specific to enterprise development - but do apply).

Also, one last point - everyone should read this Peopleware.  It really brings home how without the right people, not design will ever be successfully developed and delivered.


答:
What you'd need for a problem like this is a sliding window to hold your output.

Lines are sequentially passed to your threads to be processed and, at the same time, assigned a same-numbered slot in the window.  When a line comes back, the result is placed into its numbered slot.  When the lowest-numbered slot in the window is filled, you emit its line to the output and slide the window up by one slot, repeating until you reach a slot that doesn't have a processed line in it.  Since you've now got one or more threads free, you can start them processing the next set of lines for the slots you just opened up by moving the window.

How you size the window will depend on how you handle your threads.  You might have one thread chewing on a very long line at the bottom of the window while others work on a bunch of short ones, which will bring everything to a stop if all of the other slots in the window are filled.  Your choices are to either grow the window (which is acceptable) so you can keep your threads occupied or do nothing until the thread working on the low slot finishes.


问:
How to unit test code which is intended to have different results on different platforms
I noticed some duplicate code in a codebase I am working on that appended a filename to a directory path, so I decided to refactor it into its own method. The application I am working on is not well tested, however; I just set up the first unit tests on it two days ago, so I am very concerned to get as much code under test as possible whenever I touch it.

So I began to write a unit test like this (pseudocode):

```<code>Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeEqualTo("a/b")
</code>```

However, I then remembered that the application is cross-platform. So I thought about this:

```<code>Directory directory("a")
String separator = "/" if (platform is *nix) else "\"
Expect(directory.prependPathToFilename("b")).toBeEqualTo("a" + separator + "b")
</code>```

But I remembered that Roy Osherove says in section 7.1.2 ("Avoiding logic in tests") of The Art of Unit Testing (178):

If you have any of the following inside a test meethod, your test contains logic that should not be there:

switch, if, or else statements

foreach, for or while loops

A test that contains logic is usually testing more than one thing at a time, which isn't recommended, becauset he test is less readable and more fragile. But test logic also adds complexity that may contain a hidden bug.

Now, it does not seem that in this case I am testing more than one thing at a time. Would this be a case of an acceptible logic block in a test? Is there a pattern for cleanly testing behaviors/results that are expected to be different on different platforms?

答:
It is disputed how religious you have to be about unit testing - surely there is some value to tests even if they violate some of the precepts of the Wise Elders of testing (certainly more value than not having them!).

However, in this instance you need not break the rules if you don't want to. Note that your test is only testing one of the possible separators, because by definition it runs only on one platform. If you make the platform-detecting routine mockable, you can write different tests and inject different pseudo-platforms into them. Each of the tests then need not have any logic in it, and you achieve greater coverage at the same time.


问:
How to write "good" unit tests?
Triggered by this thread, I (again) am thinking about finally using unit tests in my projects. A few posters there say something like "Tests are cool, if they are good tests". My question now: What are "good" tests?

In my applications, the main part often is some kind of numerical analysis, depending on large amounts of observed data, and resulting in a fit function that can be used to model this data. I found it especially hard to construct tests for these methods, since the number of possible inputs and results are too large to just test every case, and the methods themselves are often quite longish and can not be easily be refactored without sacrificing performance. I am especially interested in "good" tests for this kind of method.

答:
I see that Andry Lowry has already posted Roy Osherove's unit test metrics; but it seems no one has presented the (complimentary) set that Uncle Bob gives in Clean Code (132-133). He uses the acronym FIRST (here with my summaries):

Fast (they should run quickly, so people won't mind runing them)

Independent (tests should not do setup or teardown for one another)

Repeatable (should run on all environments/platforms)

Self-validating (fully automated; the output should be either "pass" or "fail", not a log file)

Timely (when to write them—just before writing the production code they test)

Title: How to write "good" unit tests?


问:
Migrating web app from php to Java
Hi I had today my first interview for  a position of android developer.In my portfolio I had a php e-commerce application that has a catalog , ajax powered shopping cart , and administrator functionality.

Because my Android knowledge is prety limited , I only started learning about 3 weeks ago , I was asked to migrate my current PHP web appplication to Java Web until April 19th when the second stage of the interview will take place , so they can asses how fast I can learn a new technology.

I have no experience with Java working on the web so I do no know where to start.

After a bit of research I found that for developing website with Java usually you use JSP, Spring or Struts.

I would like a recommendation on witch one should I learn to quickly get started on migrating the web application to Java and some resources that do not get into to mutch details just enought to get started.

答:
I don't think Java web development will have any direct bearing on Android development apart from serving as a generic gauge of your ability to acquire new topics on your own. There may be some logic to this though as getting your first "Hello world" style Android program up and running involves a substantial amount of setup work. In the case of web development, there's much less setup (but still a small amount, more on this below)

As a PHP developer, plain old servlets + JSP will likely be closest to your mental model (as Adrian pointed out). One of the big differences is that you will have access to the application context where you can store global objects and the session context where you can store user/session specific objects. This gives you the ability to have state in your web application without constantly hitting a database or rolling it manually with memcached or similar. Another difference is that Java has the concept of a web application. A web application is a single file with a .war extension. if you're curious, you can unzip the .war file and you'll see inside a tree with various files and folders, including your JSPs as well as various config files, compiled classes, other jar files etc.

Application Structure

Using plain old servlets and JSP, you can implement the concept of MVC by structuring your code as follows:

Create a servlet called controller. The job of controller will be to carry out any actions required. Controller won't have any presentation logic in it. In a hypothetical shopping cart application, controller would know how to update the cart, submit the order, log the user in etc.

Create various JSPs for each view. For example, you might have a cart.jsp for displaying the shopping cart.

Your JSPs should only be used for presentation only, not logic (that belongs in the controller)

This should be enough to get the basic idea. FYI, the JSF framework takes the above idea and formalises it. That is, you create a file which declares all of the actions that can be taken and which view should be shown following the action. The controller is implicitly created. I would recommend staying away from JSF unless you are familiar with JSP/Servlets.

There are other frameworks such as Struts and Shale that play a similar role and I would likewise consider them to be best approached only when you know JSP/Servlets. There are plenty of analogies to this in the PHP world such as CodeIgnitor, Yii etc. etc.

Spring is substantially bigger than JSF/Struts etc. It may be worth learning in the long run but becoming productive in Spring would likely be a substantial undertaking for most experienced Java developers.

Getting set up for web development

My own personal view is that it's hard to beat Netbeans for ease of use when getting started. Netbeans comes in different bundles; if you download the JavaEE bundle then it will come with Glassfish and Tomcat bundled. Glassfish provides a superset of the functionality provided by Tomcat but for plain old servlet/JSP applications, you can use either.

I recommend glassfish which is slightly better integrated with Netbeans. In this case, integrated means that you can click the "Run" icon in Netbeans and it will result in Netbeans doing the following:

Start your server if it's not running

Build and deploy your web application

Launch a browser pointing at the appropriate URL

Tomcat will work equally well but I think support for debugging from Netbeans is better in Glassfish.

Title: Migrating web app from php to Java


问:
Domain-specific language for text search/processing?
I work for an organization that does a lot of work with government data.  We have a couple of different projects where we've abstracted out common text search/manipulation operations into reusable libraries, for things like standardizing the way politicians' names are displayed (e.g., transforming "MCDONALD, BOB (R-VA)" into "Bob McDonald (R-VA)"), or finding legal citations in text (e.g., finding a reference to (e.g., finding occurrences of things like "1 U.S.C. 7" in text, determining that it's a US Code citation, and returning a structure that says it's referring to section 1 of title 7).  These are relatively simple operations, and lots of collaborators in our space would like to use them, but we end up having to pick a language in which to implement each (the former is in Python; the latter, Javascript), and we freeze out potential consumers/contributors who work in different languages and don't want to resort to hacks like shelling out to a node process to handle their text.  This all seems like a shame because what we're expressing is so simple, and ought, one would think, to be pretty easy to share.

What would be ideal would be a tiny DSL that could express a few basic text processing operations: regular expression search/replace, a few list-processing operations like map and filter, and the ability to store stuff in JSON-ish data structures (maps and lists), and a mechanism to either translate this DSL into or allow it to be consumed from the actual higher-level languages we and our collaborators want to work with (Python, JS, Ruby, and PHP are probably the main ones).  Does anything like this exist?

I've considered building one myself... maybe a declarative thing on top of something like YAML, or maybe a tiny subset of Scheme or Lua, or maybe something entirely invented for this purpose.  But I wanted to see if anything was already out there first.

答:
You don't need to write a DSL for this.

Text processing/manipulation is a task virtually every programming project has to deal with in some way or another, and as a result virtually all popular programming languages have text processing capabilities.

Perl, Python, C#, etc can do all of the text processing things you've thought of, plus the additional aspects you haven't thought of yet.

Just use your higher level language.


答:
Here are some situations where the first approach would have been sufficient.

If the "new requirement" is a change in implementation detail, that is, caused by a response to another code change or code-contract change somewhere else.

In this case, your change should be "billed" to the original source of that change.

If it is actually a bug fix, that is, if functionA should have always called functionB were they to be re-written from scratch.

Bug fixing is an explicitly permitted exception to this principle.

Either way, it is helpful to remember the original motivation for this principle:

To avoid causing behavior changes in existing clients that don't need/expect the new behavior.

To reduce the effort (via testing) of re-establishing that the code change does not introduce bugs into the overall system.

And also remember that OCP is typically applied during class design.

Typically, OCP influences class design by encouraging the designers to think about the extension points of a set of classes, and make them explicit in the code contract or  interface.

From this thinking, one could ask: Is it possible that some clients would have preferred functionA to call functionB and meanwhile some other clients preferred otherwise? This would have required a toggle switch (in the simplest sense), or an extension point (in the OOP sense).

Title: Should methods always be closed for modification?

Body:
Say I have a method called 'functionA' that is called by a service and carries out a single piece of functionality, it is easy to unit test as it is does one thing only.

If a few months later an new requirement comes in that requires another method 'functionB' to be called directly after 'functionA' has executed. What is the better approach to add functionB to my code.

to call 'functionB' at the end of the 'functionA' method:

```<code>functionA() {
    //do something..

    functionB();
}

functionB() {
    //do somehting...
}
</code>```

Problem with this is that when I unit test functionA it will call functionB that will also be part of the test (so now it is more of an integration test).

Or refactor the code with a new method 'functionX' that calls 'functionA' and then 'functionB'?

```<code>functionX() {
    functionA();
    functionB();
}

functionA() {
    //do something..
}

functionB() {
    //do somehting...
}
</code>```

I can unit test both methods individually but now I have changed the API.

I see the first approach so much in legacy code, is it best practice to always make methods closed for modification or are there examples when it is OK to use the first approach?


答:
A strict adherence to OCP would imply that a new object with the functionA() interface that has the correct behavior be created and substituted for this object. Whether inheritance or interfaces are used to ensure substitutability (LSP) depends on the flavor of OCP you prefer, but the ideas are the same.

Your unit tests for the old object would not change and you would write new unit tests for the new object.

If you're finding difficult to create a new object that has all the behavior necessary to substitute it for this object, that speaks to your objects having too many responsibilities (SRP).

How strictly you want to apply OCP (and the other SOLID principles) here is a decision for you to make.


答: Assuming terseness isn't a requirement of your DSL, you may consider defining a JSON or XML document structure and avoid inventing a new language. This makes parsing in python, perl, and other environments far easier, and they only have to understand the structure, not the syntax. </p>

Title: Domain-specific language for text search/processing?

Body:
I work for an organization that does a lot of work with government data.  We have a couple of different projects where we've abstracted out common text search/manipulation operations into reusable libraries, for things like standardizing the way politicians' names are displayed (e.g., transforming "MCDONALD, BOB (R-VA)" into "Bob McDonald (R-VA)"), or finding legal citations in text (e.g., finding a reference to (e.g., finding occurrences of things like "1 U.S.C. 7" in text, determining that it's a US Code citation, and returning a structure that says it's referring to section 1 of title 7).  These are relatively simple operations, and lots of collaborators in our space would like to use them, but we end up having to pick a language in which to implement each (the former is in Python; the latter, Javascript), and we freeze out potential consumers/contributors who work in different languages and don't want to resort to hacks like shelling out to a node process to handle their text.  This all seems like a shame because what we're expressing is so simple, and ought, one would think, to be pretty easy to share.

What would be ideal would be a tiny DSL that could express a few basic text processing operations: regular expression search/replace, a few list-processing operations like map and filter, and the ability to store stuff in JSON-ish data structures (maps and lists), and a mechanism to either translate this DSL into or allow it to be consumed from the actual higher-level languages we and our collaborators want to work with (Python, JS, Ruby, and PHP are probably the main ones).  Does anything like this exist?

I've considered building one myself... maybe a declarative thing on top of something like YAML, or maybe a tiny subset of Scheme or Lua, or maybe something entirely invented for this purpose.  But I wanted to see if anything was already out there first.


答:
The best language I'm aware of specific to text search and processing is awk.  If awk doesn't meet your needs, it's likely nothing will unless you create it yourself.

However, if you do need to make your own, you don't need to start completely from scratch for each language.  You can use a tool like antlr that can be exported to various languages, or build it in one language and use the respective native interfaces to access it from other languages.


答:
To keep your unit test clean and simple, you could extend the test library by adding a new assertion for paths. This new assertion would abstract from the different path separators. Your test would then look like

```<code>Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeSamePathAs("a/b")
</code>```

and - depending on implementation - work identically when using

```<code>Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeSamePathAs("a\b")
</code>```

Title: How to unit test code which is intended to have different results on different platforms

Body:
I noticed some duplicate code in a codebase I am working on that appended a filename to a directory path, so I decided to refactor it into its own method. The application I am working on is not well tested, however; I just set up the first unit tests on it two days ago, so I am very concerned to get as much code under test as possible whenever I touch it.

So I began to write a unit test like this (pseudocode):

```<code>Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeEqualTo("a/b")
</code>```

However, I then remembered that the application is cross-platform. So I thought about this:

```<code>Directory directory("a")
String separator = "/" if (platform is *nix) else "\"
Expect(directory.prependPathToFilename("b")).toBeEqualTo("a" + separator + "b")
</code>```

But I remembered that Roy Osherove says in section 7.1.2 ("Avoiding logic in tests") of The Art of Unit Testing (178):

If you have any of the following inside a test meethod, your test contains logic that should not be there:

switch, if, or else statements

foreach, for or while loops

A test that contains logic is usually testing more than one thing at a time, which isn't recommended, becauset he test is less readable and more fragile. But test logic also adds complexity that may contain a hidden bug.

Now, it does not seem that in this case I am testing more than one thing at a time. Would this be a case of an acceptible logic block in a test? Is there a pattern for cleanly testing behaviors/results that are expected to be different on different platforms?

Body:
To keep your unit test clean and simple, you could extend the test library by adding a new assertion for paths. This new assertion would abstract from the different path separators. Your test would then look like

Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeSamePathAs("a/b")

and - depending on implementation - work identically when using

Directory directory("a")
Expect(directory.prependPathToFilename("b")).toBeSamePathAs("a\b")


问:
Distributed Issue Tracking
Distributed issue tracking seems like a belting idea to me, but it has never really taken off in a big way. Is there a good reason for that?

I am aware of:

bugz everywhere

too complex to set up

too many requirements

reasonably successful, used by some large projects

fossil

tries to integrate too many things, and ends up being a slightly worse version of all of them - except maybe for the distributed issue tracking part, which is decent (probably best I have seen)

several other smaller projects

none of which have gained any traction

I am thinking about making my own, but before I begin, I would like to know why none of the others have taken off in a big way.

Anticipated issues: (I think they can all be overcome)

merging distributed issues as they are updated is complex, as is merging any code files

conversation continuity can be destroyed, as comments can come in at any time, perhaps not in the correct flow

expectation of central server with issues up-to-date

答:
I don't think being decentralized is as important as having off-line capabilities. Integration with source control is a big benefit, so you want each user to be able to conveniently handle both tasks. The closer together they do it the more continuity you'll have.

Even the most distributed teams should be able to put together a web server and tracking system. It would be more beneficial to have a central bug tracker since every user only needs a subset of the bug database.  Bugs are usually assigned to someone who can work on it individually. There's nothing wrong with being unavailable to everyone else if it uses some sort of "check-out" system that leaves it in a read only state. A website also allows clients/users to enter and view their own tickets.

You're on to something with the off-line need, but many of the problems you addressed could be avoided with just checking out parts of the bug-tracker to work on while disconnected.

For many users, one of the best integration tools is email especially when you have people outside the team. I'm not going to go back to your website to see if my issue has been resolved. I want an email with a possible reply link to provide feedback. Any developer who responds to a change request email, can send a reply and have it tracked in the system.

Title: Distributed Issue Tracking


问:
How to synchronize client and server model objects?
We have a client-server application with a thick client (GWT).

There are client-side MVP presenters (MVC controllers) which hold references to some objects viewed in the GUI. Some user actions cause these objects to be updated on the server. After that we can send updated objects back to the client and reassign them to the presenter.

The problem is that there are usually a few references to an object on the client (Lists, HashMaps, etc.) and it is hard to update all of them.

Another approach is not to update the references but update the object itself, e.g. copy all the properties from the server object to the client one. But if an object is complex it is not easy too.

Which approach is better? Or maybe I miss something?

答:
I don't think you should be updating the whole objects because this would mean moving "business data" through the interweb. If this is compromised, the whole system can be crippled in seconds. This, obviously, is if you're creating something large-scale.

Pertaining to speed, the references option is also favorable since there is less information flowing through interconnects.


答:
Start by reading Hamming's classic book Numerical Methods for Scientists and Engineers.  He goes into a great deal of detail on the nature of floating-point numbers and of numbers in science in general.  (Interesting tidbit: Floating point numbers are not uniformly distributed, and neither are the fundamental constants of physics, but the the two distributions are similar.)

In any computational problem, you have to have some idea what constitutes a "good" answer.  In simplest form: what value of epsilon is appropriate?  For example, for problems with distances measured in astronomical units (1 AU = 93 million miles, approximately), epsilon of 1 mile corresponds to 1E-8 relative error.  Depending on what you are doing, that may or may not be enough.

Title: Tracking scientific error when working with floating-point numbers

Body:
Background

I hate the way .Net/IEEE-754 handles equality of floating-point numbers (FPNs) (i.e. double, float). It requires the programmer to be prescient with respect to the yet-to-be-determined history of the number, as the programmer must choose a 'reasonable' value of epsilon where frequently no such value can be determined (as the programmer cannot determine ahead of time how many operations, hence roundings, the number will be subject to).

I would like to create a 'better' FPN within .Net. At creation, one would set its initial scientific error (or accept a default; the default being the minimum). When one performed operations on the FPN, those operations would update the scientific error (to account for the effect of rounding). When testing the equality of two FPNs, one could determine if their ranges overlapped (and even the probability that they are the same number).

Question

The code itself is simple, my questions are:

How do operations (+ - * / to start with) affect the scientific error of a FPN? Are there formulae for determining this scientific error?

I understand that an added complication is the uneven distribution of FPNs. This can obviously be accounted for by scaling the error in proportion to the inherent scientific error of the result; but is there a formula for determining the inherent scientific error present in a given FPN?


问:
Should I tell the interviewer I already know the answer to the question being asked?
In a programming interview if I am asked a question I already know the answer for, such as giving an algorithm for a particular problem. Should I disclose that to the interviewer? This issue only makes sense when there's a novelty aspect to the question.

One example is "How would you reverse each word in a string, but not their order?". There also seems to be a division between easier stuff, that you are "supposed" to know, such as my example and harder more contrived problems.

Whats your policy and rationale for dealing with this issue?  If you are already familiar with the question/brainteaser, should you disclose this in addition to answering the question?  Is there any ethical dilemma involved with not disclosing your prior knowledge of the question?

答:
So what's the alternative?  If you tell the interviewer that you know the answer to a question that is posed and expect them to give you only questions that you don't know the answer to, what happens?  Either

They will respect you because you will only attempt to answer questions you have never seen/heard before,

They will be blown away by your brilliance - after all, you already know the answers to the questions they're posing - and will immediately offer you a job

They will think you're a smart-ass because you already seem to know everything - just ask you!, or

They will think you're a fool because you don't know when things are going well.

I suspect that options (1) and (2) aren't going to happen - call me Mr. Cynical.  So you're left with either being a fool or a smart-ass, neither of which is likely to land you a job.  Hey, good luck!

The point of an interview, as others have pointed out, is to offer you a chance to demonstrate your technical proficiency by answering whatever questions are put to you.  This kind of means that it's in your favor to be asked questions you're already familiar with.  If you insist on sabotaging yourself, go ahead - nobody's going to stop you - but I suggest you don't.

Share and enjoy.