答:
One common use is when you want to use the template method pattern.

I that pattern you write the skeleton of an algorithm in an abstrac class. In some parts of that skeleton you can certain methods that are not implemented.

Subclassed implement those methods completing the algorithm. That can also be achieved without inheritance using injection and or delegates.

In general you should not subclass where there is not "is a" relationship between class.

Another patter that uses inheritance is the decorator patter which is similar to the toolbar example you gave.

Title: Heuristics on when should one subclass and when not

Body:
Are there any good tips, when one should subclass and when should not?

It's clear that we should not subclass when

we want to reuse a single method of some class

we override all methods, changing the behavior of superclass completely.

But in real life, it's more difficult to decide. For example, I have a BasicToolbar class, which has several buttons arranged on a panel. There is a second class ExtendedToolbar, which hould

have some additional buttons

change the ordering of all buttons

on condition hide/remove a couple of buttons from parent class

I tend to subclass to reuse those buttons and override ordering/addition logic, but occasional removing of a button of the parent class seem to be against idea of inheritance.

Any opinion is welcome.


问:
Heuristics on when should one subclass and when not
Are there any good tips, when one should subclass and when should not?

It's clear that we should not subclass when

we want to reuse a single method of some class

we override all methods, changing the behavior of superclass completely.

But in real life, it's more difficult to decide. For example, I have a BasicToolbar class, which has several buttons arranged on a panel. There is a second class ExtendedToolbar, which hould

have some additional buttons

change the ordering of all buttons

on condition hide/remove a couple of buttons from parent class

I tend to subclass to reuse those buttons and override ordering/addition logic, but occasional removing of a button of the parent class seem to be against idea of inheritance.

Any opinion is welcome.

答:
The Liskov Substiution Principle is by far the best "heuristic" I know of for determining whether direct subclassing is a good idea.

Say you have a base class Foo, and derived classes Bar1 through Bar9. In a nutshell, the LSP states that any block of code using a Foo must work correctly no matter which of the nine Bar types that Foo actually is.

From the user's point of view, that means code using the base class should be able to work almost exclusively with that base class, without caring what the actual type of the object is.

From the implementer's point of view, that means each subclass must implement the full interface of the base class, including all of the implied semantic properties, without any surprises or additional restrictions.

If the subclass you're thinking of writing won't follow these rules, that's a very strong indication you should not be using inheritance.

Regarding your toolbar example, I don't think it makes a lot of sense to use inheritance that way. I'd rather have Button classes, a generic Toolbar class that can contain any arrangement of Buttons, and then make BasicToolbar and ExtendedToolbar be objects with a Toolbar member that they add Buttons to in their constructors. If they share a bunch of buttons, make BackButton/LikeButton/UpvoteButton classes with a Button member, and let the Toolbars contain them. Using inheritance anywhere in this arrangement will only add unnecessarily tight restrictions on how you can rearrange these classes in the future.

ContentLicense: CC BY-SA 3.0


问:
How do I design an arbitrary system in an interview?
A common question in Tech Interview is to design a particular system, usually an existing product of the company. For example, "Design Google Docs".

What is the expected answer for such a question? I mean, such systems surely have a complex design which is beyond the scope of any interview. What are the interviewers expecting in such a short time?

答:
I also ask this kind of question, and I agree with most of the other answers.  Maybe it would help interviewees to understand WHY this type of question is important?  Suppose we have an important business decision to make, and in order to do it, we need to build a new system.  If someone runs up to you and asks what it would take to build a system that does X, can you give them an insightful answer that predicts the major challenges and resources required?

A junior programmer has no idea where to start.  They are not ready to start talking without a detailed specification.  A senior programmer will instantly see that there are many facets to the issue, and will attempt to hone in on a challenge.  You don't have to architect every aspect, just identify an architectural challenge and then figure out how to address it.

Consider the issue of Google Docs:

One interesting thing is the shear scale of requests that will be coming.  You can't just get a single server and deploy your code to it - this is a larger undertaking.  A successful interviewee might zero in on this and will describe the types of resources that will be needed, and some of the technical challenges in implementing at that scale, with an application that not only has state, it shares state across multiple users.

Another interesting thing about Google Docs is that multiple people can edit at the same time.  A successful interviewee will be able to discuss mechanisms for making sure the resulting doc isn't garbage, and a truly great candidate will realize that different methods of synchronizing or merging edits will have a big impact on performance and UX.  Maybe even discuss variations:  A shared document editor for writing code should probably use a different method of resolving conflicts than the typical Google Doc, because there are different consequences to things happening in a different order or having slightly different structure.

There's no single right way to create an app like Google Docs, you don't have to identify what you would do for every trade-off, but it's really great to find an area that has an interesting issue, and clearly explain what the trade-offs might be.

-t.


问:
Should I use exceptions to control the range of parameters in Python?
For example for the following method signature:

def genClusters(n_clusters, n_nodes, cluster_distribution):

n_clusters should be an integer of more than 1.

n_nodes should be an integer of more than n_clusters

cluster_distribution should be a float between 0 and 1.

Should I use a series of if then raise exception statements to handle the argument parameter bounds?

eg:

```<code>def genClusters(n_clusters, n_nodes, cluster_distribution):
    if (cluster_distribution < 0 or cluster_distribution > 1):
        raise ValueError("cluster distribution must be between 0 and 1")
    if n_clusters < 1:
         raise ValueError("n_clusters must be at least 1")
    if n_nodes <= n_clusters:
         raise ValueError("n_nodes must be at least n_clusters")
</code>```

The second question is whether I should include these exception statements in every method that also calls this one.

For example:

```<code>def myFoo(foo, bar, bang):
    clusters = genClusters(foo, bar, bang)
</code>```

In this scenario, if foo, bar, or bang don't fit previously defined parameter bounds, an exception will be thrown when genClusters is called. So should I also be throwning exceptions at the start of myFoo?

答:
Say you don't check the input arguments beforehand, and just let the function run its course.  Consider this: what's worst that's going to happen?  (This is not a rhetorical question.)  Is giving it bad input going to:

cause the function to fail with another exception somewhere deep in the code?

waste a lot of time, then fail midway?

do something potentially harmful (e.g. delete your valuable data ...)?

return a bogus result?

cause a confusing error message?

Take these into consideration carefully.  In most scenarios, where performance is not of utmost importance, you really want it to fail early and as loudly as possible, so checking for invalid arguments is generally a good idea (hopefully answers your first question).

This helps debugging and reduces the risk of your code doing something awful.  Of course, this can be tedious at times, so if you want a quick approach (useful for prototyping), use assert:

```<code>assert 0 <= cluster_distribution <= 1
</code>```

However, there's no use in doing it twice if it's obvious that another function will do it for you, as it will lead to unnecessary code duplication (hopefully answers your second question).

For example, say you have a (rather useless) function like this:

```<code>def square_root(s);
    return math.sqrt(s)
</code>```

There's no need to check whether s is nonnegative because sqrt does that already.  In most "small" functions like this, you won't need to do much input checking.  Usually, only "big" functions require explicit input checking like these.  In some cases, you can restructure code without explicit checks so that if the inputs are invalid it will fail automatically.

Body:
Say you don't check the input arguments beforehand, and just let the function run its course.  Consider this: what's worst that's going to happen?  (This is not a rhetorical question.)  Is giving it bad input going to:

cause the function to fail with another exception somewhere deep in the code?

waste a lot of time, then fail midway?

do something potentially harmful (e.g. delete your valuable data ...)?

return a bogus result?

cause a confusing error message?

Take these into consideration carefully.  In most scenarios, where performance is not of utmost importance, you really want it to fail early and as loudly as possible, so checking for invalid arguments is generally a good idea (hopefully answers your first question).

This helps debugging and reduces the risk of your code doing something awful.  Of course, this can be tedious at times, so if you want a quick approach (useful for prototyping), use assert:

assert 0 <= cluster_distribution <= 1

However, there's no use in doing it twice if it's obvious that another function will do it for you, as it will lead to unnecessary code duplication (hopefully answers your second question).

For example, say you have a (rather useless) function like this:

def square_root(s);
    return math.sqrt(s)

There's no need to check whether s is nonnegative because sqrt does that already.  In most "small" functions like this, you won't need to do much input checking.  Usually, only "big" functions require explicit input checking like these.  In some cases, you can restructure code without explicit checks so that if the inputs are invalid it will fail automatically.


问:
Throw exception or let code fail
I am wondering if there are any pros and cons against this style:

```<code>private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}
</code>```

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

答:
I agree with Ixrec's answer.  However, you might want to consider a third alternative:  making the function idempotent.  In other words, return early instead of throwing an ArgumentException.  This is often preferable if you would otherwise be forced to check if it has already been loaded before calling LoadMaterial every time.  The fewer preconditions you have, the less cognitive load on the programmer.

Throwing an exception would be preferable if it's truly a programmer mistake, where it should be obvious and known at compile time if the material has already been loaded, without having to check at runtime before calling.

Title: Throw exception or let code fail


问:
Peer review for tests just like code reviews
Does anyone practice the "code review" process for functional tests? Do you find it useful? The way that my current employer practices SCRUM we include functional testing as part of our "must have done" stuff in any given sprint.</p>

答:
We peer-review functional tests at least casually, and it is strongly encouraged at our organization to get everything code-reviewed.

I would recommend choosing your reviewer based off of your goals for the review.  Coded tests might be best reviewed by both a dev (for code quality primarily) and another tester (for test coverage primarily).  Tests with no code (using a harness, e.g., data driven tests) might be best reviewed only by another tester. Peer reviews are also a great way to encourage testers to learn from each other.

ContentLicense: CC BY-SA 2.5


问:
Structuring data to represent a tree with squirrels
What I want to represent

Let's assume I have several schemas of the following kind:

It is a tree on which positions of squirrels are represented by a blue dot. The number of bifurcations differ from one tree to another, the number of squirrels varies from one tree to another, the positions of the squirrels vary (and are on a continuous scale), all trees are not necessarily symmetric (unlike the picture) and the length of the branches differ (on the picture the length of the second branches are all the same, the lengths of the third branches are all the same. This is not necessarily always the case).

The problem

I am trying to describe these trees with numbers so that I can play with these numbers and easily calculate the distance between two squirrels (following the branches, not by jumping), calculate the distance between a squirrel and the ground (the bottom of the trunk) or calculate the density of squirrels per branch.

The angles between branches do not matter and the branches have no width (they are just lines). The info I need are the length of the branches (on a continuous scale), the positions of the squirrels (on a continuous scale) relative to their branch, the number of bifurcations and the positions of the branches relative to other branches (whether one branch is attached to another one).

My (very) poor solutions

One way to describe this tree is to digitalize it. I could make a big array with 0s everywhere there is nothing, 1s everywhere there is a branch and a 2 everywhere there is a squirrel (and a branch necessarily, no flying squirrel on the picture!). That would be a solution but I would very big arrays and it is really not very handy to infer things like the average distance between two squirrels. Moreover, we lose precision about the positions of the squirrels and the lengths of the branches

Another solution would be to have two sets of vectors and one set of points. The first set of vector describes the positions of each squirrel relative to the bottom-left corner, another set of vector defines the the length and direction (although we don't directly need this info) of each branch and the set of points indicate where the starting points of the vectors describing the branches. It really doesn't seem to be a good idea; it is too descriptive (too much info) and is not very handy for making the kind of calculations I need to perform afterward.

I feel like I focus too much on the picture and have a hard time realizing how the informations I need could be coded/stored. Can you help me with that?

答:
Branches is fairly easy:

Root of tree is "1".

First bifurcation results in branches  "1x1" and "1x2" counting from the left.

So the top rightmost branch in your tree is labeled "1x2x2x2".

This schema is quite useful for querying as you can get all the sub branches of say "1x2" by a simple " LIKE '1x2%' " in SQL.

Squirrel position is more problematic but I would suggest a simple distance from the beginning of the branch.

So you table would look like:

```<code>Branches:
      Branch    Length
      1         4
      1x1       3
      1x1x1     2
      1x1x1x1   1
      1x2       3
      ...................
      1x2x2     2
      1x2x2x1   1
      1x2x2x1   1

  Branch    Position   Name
  ------    --------   ----
  1         2          Fluffytail
  1         3          Nutkin
  1x1       1          Brighteyes
  1x1       2          Loopy
  1x1x1     1          Lefty
....................
  1x2x2     3          Jumper
  1x2x2x1   1          Topper
  1x2x2x2   1          Rightmost
</code>```

Body:
Branches is fairly easy:

Root of tree is "1".

First bifurcation results in branches  "1x1" and "1x2" counting from the left.

So the top rightmost branch in your tree is labeled "1x2x2x2".

This schema is quite useful for querying as you can get all the sub branches of say "1x2" by a simple " LIKE '1x2%' " in SQL.

Squirrel position is more problematic but I would suggest a simple distance from the beginning of the branch.

So you table would look like:

Branches:
      Branch    Length
      1         4
      1x1       3
      1x1x1     2
      1x1x1x1   1
      1x2       3
      ...................
      1x2x2     2
      1x2x2x1   1
      1x2x2x1   1

  Branch    Position   Name
  ------    --------   ----
  1         2          Fluffytail
  1         3          Nutkin
  1x1       1          Brighteyes
  1x1       2          Loopy
  1x1x1     1          Lefty
....................
  1x2x2     3          Jumper
  1x2x2x1   1          Topper
  1x2x2x2   1          Rightmost


问:
torrent support in browser
i was thinking it would be cool to implement native torrent support in a web browser so that the following html would render an image on the page:

```<code><img src="magnet:?xt=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C" alt="smiley face" height="42" width="42">
</code>```

i have looked around and such a thing doesn't appear to have been done before, but it seems to me that it would have a lot of advantages - for example in content delivery networks, or to provide redundancy when hosting files.

could such functionality be implemented as a browser plugin, or is there a better way? what steps would be required?

答:
The idea is feasible, but of little use due to the nature of web browsing and bittorrent behaviour.

For small resources, e.g. images, the overhead of setting up a swarm and keeping it reliably seeded is way too big compared to just serving the image directly from some server.

For large resources, e.g. long video elements, it would be justified, but then you would want to stream the content so that the user has something to see right away, not download-and-play. (It's a web browser, after all, not a download utility.) But BT doesn't offer any guarantee that you receive the first part of a file first, so it can't reliably stream anything. I suspect this is why others haven't run with the idea yet.

Title: torrent support in browser


问:
Exception messages and event logging - which tense to use?
Do you have best practices regarding to which tense to use in message when you're coding exception-throwing or message-logging code: "Could not acquire connection from DataSource" versus "Can not acquire connection from DataSource"?

答:
I like to use present tense when the error/exception-generating code is the "root cause" of the problem, and past tense when I'm merely repackaging an error/exception from a lower layer of code.

For example, when our frontend makes a request to our backend, the backend may return an error message "Cannot connect to database", and the frontend will throw "Failed to retrieve your widgets because: Cannot connect to database".

In general, the only "best practices" in regards to exception/error wording are to make it as clear, unambiguous, non-misleading and consistent as possible. In my opinion the tense convention I just described fits those criteria the best, but there are probably other equally valid conventions.


问:
Why does Git have tags?
I've read Git branching and tagging best practices and git tagging comments - best practices, but I don't see a direct answer to something I've wondered for a long time:

Why does Git have tags? (instead of just branches)

They seem to be second-class citizens, or at least "different." They aren't pushed unless you specify that explicitly. Deletions of remote tags doesn't cause deletion in downstream repos.

This last point was a problem recently, as someone pushed a bunch of garbage tags with tons of commits from another repo. We could delete them upstream and gc the commits, but that wouldn't propogate, and the next time someone pushed a tag with git push --tags, they'd repush those garbage tags and commits. So we had to make sure everyone deleted them.

When and why would I use a tag instead of a branch?

答:
1) Why are git tags second-class citizens?

Because sadly, git has a lot of bad defaults. As much as I like it, it simply is not a very newbie-friendly or intuitive tool. Pretty much everyone has to set up git configs or aliases or scripts that use a dozen or so of the -- options (like --ff-only) to make git start behaving the way they actually want it to. Tags are just one more example.

2) Why would I use a git tag instead of a branch?

A branch is intended to mark a commit that you make other commits on top of. When you make a new commit to that branch, the branch itself "moves" so that it points to the new commit.

A tag, on the other hand, marks a commit, and then keeps marking that same commit pretty much forever (in theory). The most common usage is tagging commits with their official release versions every time you roll out a new version to production.

We use both branches and tags for our release versions. The branch merely represents major/minor version, while the tags specify patch/build releases within that major/minor version. So if we need to apply a bug fix to an old version, we simply cherry-pick the bugfix commit from master onto the appropriate branch, then tag the new commit with the new version number it gets during deployment.

Title: Why does Git have tags?


问:
Designing a REST api by URI vs query string
Let's say I have three resources that are related like so:

```<code>Grandparent (collection) -> Parent (collection) -> and Child (collection)
</code>```

The above depicts the relationship among these resources like so: Each grandparent can map to one or several parents. Each parent can map to one or several children. I want the ability to support searching against the child resource but with the filter criteria:

If my clients pass me an id reference to a grandparent, I want to only search against children who are direct descendants of that grandparent.

If my clients pass me an id reference to a parent, I want to only search against children who are direct descendants of my parent.

I have thought of something like so:

```<code>GET /myservice/api/v1/grandparents/{grandparentID}/parents/children?search={text}
</code>```

and

```<code>GET /myservice/api/v1/parents/{parentID}/children?search={text}
</code>```

for the above requirements, respectively.

But I could also do something like this:

```<code>GET /myservice/api/v1/children?search={text}&grandparentID={id}&parentID=${id}
</code>```

In this design, I could allow my client to pass me one or the other in the query string: either grandparentID or parentID, but not both.

My questions are:

1) Which API design is more RESTful, and why? Semantically, they mean and behave the same way. The last resource in the URI is "children", effectively implying that the client is operating on the children resource.

2) What are the pros and cons to each in terms of understandability from a client's perspective, and maintainability from the designer's perspective.

3) What are query strings really used for, besides "filtering" on your resource? If you go with the first approach, the filter parameter is embedded in the URI itself as a path parameter instead of a query string parameter.

Thanks!

答:
The following is more RESTfull because every grandparentID gets it own URL. This way the resource gets identified in a unique way.

```<code>GET /myservice/api/v1/grandparents/{grandparentID}
GET /myservice/api/v1/grandparents/{grandparentID}/parents/children?search={text}
</code>```

The query parameter search is a good way to execute a search from the context of that resource.

When a family is getting very large you can use start/limit as query options for example:

```<code>GET /myservice/api/v1/grandparents/{grandparentID}/children?start=1&limit=50
</code>```

As a developer it is good to have different resources with a unique URL/URI. I think you should use query parameter only when they also could be left out.

Maybe this is a good read http://www.thoughtworks.com/insights/blog/rest-api-design-resource-modeling and otherwise the original PhD thesis of Roy T Fielding https://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf that explains the concepts very well and complete.

Body:
The following is more RESTfull because every grandparentID gets it own URL. This way the resource gets identified in a unique way.

GET /myservice/api/v1/grandparents/{grandparentID}
GET /myservice/api/v1/grandparents/{grandparentID}/parents/children?search={text}

The query parameter search is a good way to execute a search from the context of that resource.

When a family is getting very large you can use start/limit as query options for example:

GET /myservice/api/v1/grandparents/{grandparentID}/children?start=1&limit=50

As a developer it is good to have different resources with a unique URL/URI. I think you should use query parameter only when they also could be left out.

Maybe this is a good read http://www.thoughtworks.com/insights/blog/rest-api-design-resource-modeling and otherwise the original PhD thesis of Roy T Fielding https://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf that explains the concepts very well and complete.


答:
This is done on purpose.

They seem to be second-class citizens, or at least "different." They
  aren't pushed unless you specify that explicitly. Deletions of remote
  tags doesn't cause deletion in downstream repos.

I don't agree with lxrec's answer about git having bad defaults.
If you follow the mailing list, you can see that git developpers actually care about having sensible defaults. Would it make sense to have --ff-only as a default? I don't think so.

Tags make it possible to have annotations for your own, local development copy. I would not like to see my why_does_it_break_here and todo_fix_formatting tags being pushed without my consent (those are not actual tag names).
Tagging a release, on the other hand, is something that occurs less often, and it makes sense to require an explicit push (or use an alias).

I don't see a major difference between tags and branches w.r.t. how push/fetch behaves. In your example, if the garbage tags had been branches, would the deletion propagate as you intended?

When and why would I use a tag instead of a branch?

Generally speaking:

branches are for trees: they point to different commits over time

tags are for individual commits and are immutable (this includes frozen trees such as releases)

Title: Why does Git have tags?

Body:
I've read Git branching and tagging best practices and git tagging comments - best practices, but I don't see a direct answer to something I've wondered for a long time:

Why does Git have tags? (instead of just branches)

They seem to be second-class citizens, or at least "different." They aren't pushed unless you specify that explicitly. Deletions of remote tags doesn't cause deletion in downstream repos.

This last point was a problem recently, as someone pushed a bunch of garbage tags with tons of commits from another repo. We could delete them upstream and gc the commits, but that wouldn't propogate, and the next time someone pushed a tag with git push --tags, they'd repush those garbage tags and commits. So we had to make sure everyone deleted them.

When and why would I use a tag instead of a branch?


问:
If-else in C++ Programming Language
I am a little bit confused about this code. Why does the else block get executed?

Please explain it.

```<code>int a=10,b=20;
char x=1,y=0;
if(a,b,x,y){
    cout << "A" << endl;
}else{
    cout << "B" << endl;
}
</code>```

答:
According to this Wiki Page:

In the C and C++ programming languages, the comma operator
  (represented by the token ,) is a binary operator that evaluates its
  first operand and discards the result, and then evaluates the second
  operand and returns this value (and type).

So this: if(a,b,x,y){ will only take the value of y into consideration for the actual if part, which has a value of 0 which would evaluate to false, thus causing the else part of your code to execute.

EDIT: That being said, the code you posted does not make much sense. The comma operator will evaluate and discard the result (other than the last item). This would be helpful if you would need to chain a series of methods which depend on each other and decide what to do by using the result of the last one.

Title: If-else in C++ Programming Language


问:
Enum as singleton or fully functional class
Joshua Bloch claims that

"a single-element enumeration type is the best way to implement a
  singleton"

Why? I totally disagree with this statement because enumeration is data type with some type-safe constants, like NORTH, SOUTH, WEST, EAST. I think that stable singleton can be creating using class with adding some boiler plate code. Using enumeration as fully-functional object seems misleading to me. Is it really a good approach to do it?

答:
This is why:

This approach is functionally equivalent to the public field approach,
  except that it is more concise, provides the serialization machinery
  for free, and provides an ironclad guarantee against multiple
  instantiation, even in the face of sophisticated serialization or
  reflection attacks. While this approach has yet to be widely adopted,
  a single-element enum type is the best way to implement a singleton.

(from http://www.informit.com/articles/article.aspx?p=1216151&seqNum=3)

Have you not read this, or are you disagreeing with Bloch's reasoning?


答:
Why not change the method so it return 'true' it the matterial is added and 'false' if it wasn't?</p>

```<code>private bool LoadMaterial(string name)
{
   if (_Materials.ContainsKey(name))

    {

        return false; //already present
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );

    return true;

}
</code>```

Title: Throw exception or let code fail

Body:
I am wondering if there are any pros and cons against this style:

```<code>private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}
</code>```

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

Body:
Why not change the method so it return 'true' it the matterial is added and 'false' if it wasn't?

private bool LoadMaterial(string name)
{
   if (_Materials.ContainsKey(name))

    {

        return false; //already present
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );

    return true;

}


问:
How much Ruby should I learn before moving to Rails?
Just a quick question..

I can never get a definitive answer when googling this, either. Some people say you can learn Rails without knowing any Ruby, but at some point you'll run into a brick wall and wish you knew Ruby and will have to go back to learn it..and some say to learn the "basics" of Ruby before learning Rails and it will make your life that much easier..

My current knowledge is low. I'm not a beginner, but I'm not pro, either. I went through the Learn Python The Hard Way online book in about a month, but I stopped once I got to the OOP side of Python (I know booleans, elif/if/else/statements, for loops, while loops, functions)

I agree with learning the "basics" of Ruby before learning Rails, but what exactly are the "basics" of Ruby? Would I need to learn the whole OOP side of Ruby before I went on to Rails? Or would I just need to learn the Ruby syntax up to where I learned Python (booleans, elif/if/else/statements, for loops, while loops, functions) before I went on to Rails?
Thanks!

答:
Try to learn the fundamental points of Ruby. While you are doing this try to understand how things happen. For a better understanding you should always write some examples to each topic.
So most of the time you will see how things work.

After you are running fine with the major Ruby language features, you can switch to Rails and start to learn it from scratch.

I will list up the imo most important points that you should know about Ruby before starting with Rails:

Variables

String and symbols

Operators

Statements

Loops

Blocks/Procs/Lambdas

Classes / Modules

OOP

Eigenclass/Singletonclass

There you go. If you are running fine with all that points i listed, then you can start with Rails. There you will notice that it was worth to put all the effort in learning Ruby before Rails.


问:
Do web applications use HTTP as a transport layer, or do they count as an integral part of the HTTP server?
Given an HTTP server (e.g. Apache, IIS) and a web application (user code running in the server using PHP, ASP.NET and the likes), which of those can decide which HTTP status code to return for any request?

Or rather, is a "web application" to be interpreted as an integral part of "server" as used in the HTTP RFCs? The latter (RFC 7230) is pretty short on that:

An HTTP "server" is a program that accepts connections in order to service HTTP requests by sending HTTP responses.

Since the actual response is generated by a web application (excluding static resources), I'd say the web application is actual part of the server.

However, apart from the eternal "which HTTP status code to use in [arbitrary situation]?" discussions, there also is the discussion "Should web applications even use HTTP status codes?", which I'd like a normative answer to.

See for example the Google Maps REST API. They return 200 for every repsonse, which can be interpreted as "The request ended up at the HTTP server, so that part went OK (200)". Any application error that happens that is returned in the message body as a JSON status, up till the point of NOT_FOUND.

Is this correct? Shouldn't a request for GET /Clients/123 return a 404 when that client doesn't exist? Then what about GET /clients.php?id=123, assuming clients.php exists?

Or does 404 really and only mean "I don't know what you're trying to do, but I'm not going to serve you a resource as there is no resource at (a part of) that URI", "resource" meaning "a (routed) file or directory", which should only be returned by the server when someone forgot to deploy the ClientService application?

Do status code only work for the HTTP part of things, or is a web application part of the server, allowing it to utilize the appropriate status codes where they fit, using HTTP status codes as API response codes?

答:
When dealing with HTTP status codes the level of abstraction to be thinking on is the context of the HTTP request that was just made.

If your client makes a request

```<code>GET http://example.com/someresource
</code>```

your client is saying

```<code>Yo! example.com! Give me a representation of "someresource"
</code>```

If the client cannot do that then do not return 200 (OK). What Google do is wrong. Saying "OK! I cannot do that" is a confused response.

Imagine if you went into a shop and said give me a 6 pack of beer and the shop keeper said "Ok here you go" and then when you looked down into your bag there was a letter saying "Sorry, all out of beer"!

The client does not care about the internal workings of example.com, in the same way you don't care about the problems the shop may or may not be having. You care if you can get your beer.

If you cannot get your beer you only care if you have done something wrong ("Sorry, I need ID") or if there is nothing more you can do ("Sorry we are all out of beer" or "Sorry this is a knitting store, we don't sell beer"). The sorry I cannot give you that resource responses are 4xx and 5xx

If example.com has to talk to 100 different servers or databases to do what the client asked the client doesn't care, any more than you care if the shop keeper has to shout over the intercom "Hey! I need some more beer!" in order to give you the beer. You don't care, you care about the beer.

Body:
When dealing with HTTP status codes the level of abstraction to be thinking on is the context of the HTTP request that was just made.

If your client makes a request

GET http://example.com/someresource

your client is saying

Yo! example.com! Give me a representation of "someresource"

If the client cannot do that then do not return 200 (OK). What Google do is wrong. Saying "OK! I cannot do that" is a confused response.

Imagine if you went into a shop and said give me a 6 pack of beer and the shop keeper said "Ok here you go" and then when you looked down into your bag there was a letter saying "Sorry, all out of beer"!

The client does not care about the internal workings of example.com, in the same way you don't care about the problems the shop may or may not be having. You care if you can get your beer.

If you cannot get your beer you only care if you have done something wrong ("Sorry, I need ID") or if there is nothing more you can do ("Sorry we are all out of beer" or "Sorry this is a knitting store, we don't sell beer"). The sorry I cannot give you that resource responses are 4xx and 5xx

If example.com has to talk to 100 different servers or databases to do what the client asked the client doesn't care, any more than you care if the shop keeper has to shout over the intercom "Hey! I need some more beer!" in order to give you the beer. You don't care, you care about the beer.


问:
Most efficient way to generate all descendents of all nodes in a tree
I'm looking for the most efficient algorithm to take a tree (stored as either a list of edges; OR as a list of mappings from parent node to a list of child nodes); and produce, for EVERY node, a list of all nodes descended from it (leaf level and non-leaf level).

The implementation must be via loops instead of recusion, due to scale; and should ideally be O(N).

This SO question covers a standard reasonably obvious solution for finding the answer for ONE node in a tree. But obviously, repeating that algorithm on every tree node is highly inefficient ( off the top of my head, O(NlogN) to O(N^2) ).

The tree root is known. The tree is of absolutely arbitrary shape (e.g. not N-nary, not balanced in any way, shape or form, not uniform depth) - some nodes have 1-2 children, some have 30K children.

On a practical level (though it shouldn't affect the algorithm) the tree has ~100K-200K nodes.

答:
If you actually want to PRODUCE every list as different copies, you cannot hope to achieve better than n^2 space in the worst case. If you just need ACCESS to each list:

I would perform an in-order traversal of the tree starting from the root:

http://en.wikipedia.org/wiki/Tree_traversal

Then for each node in the tree store the minimum in-order number and maximum in-order number in its subtree (this is easily maintained through recursion -- and you can simulate that with a stack if you wish).

Now you put all nodes in an array A of length n where the node with in-order number i is in position i. Then when you need to find the list for a node X, you look in A[X.min, X.max] -- note that this interval will include the node X, which can also easily be fixed.

All of this is accomplished in O(n) time and takes O(n) space.

I hope this helps.


答:
I think past tense is a safer bet. In your example:

1) "Could not acquire connection from DataSource" - an attempt was made, failed, situation could've changed since then.

2) "Can not acquire connection from DataSource" - an attempt was made, failed, it's 100% certain that situation is still the same.

Also which tense would you pick for a timeout error?

"Timed out while acquiring connection..."

vs

"Timing out while acquiring connection..."

PS: I would be more worried about including all the helpful details, e.g.: "Could not acquire connection from DataSource '[name of server, name of database]' at [date and time] for user [username]."

Title: Exception messages and event logging - which tense to use?

Body: Do you have best practices regarding to which tense to use in message when you're coding exception-throwing or message-logging code: "Could not acquire connection from DataSource" versus "Can not acquire connection from DataSource"?


答:
This is where you get it wrong:

If my clients pass me an id reference

In a REST systems, client should never be bothered with IDs. The only resource identifiers that the client should know about should be URIs. This is the principle of "uniform interface".

Think about how clients would interact with your system. Say the user starts browsing through a list of grandparents, he picked one of grandparent's child, that brings him to /grandparent/123. If the client should be able to search the children of /grandparent/123, then according to "HATEOAS", whatever returned when you do a query on /grandparent/123 should return a URL to the search interface. This URL should already have whatever data is needed to filter by the current grandparent embedded in it.

Whether the link looks like /grandparent/123?search={term} or /parent?grandparent=123&search={term} or /parent?grandparentTerm=someterm&someothergplocator=blah&search={term} are inconsequential according to REST. Notice how all of those URLs have the same number of parameters, which is {term}, even though they use different criterias. You can switch between any of those URLs or you can mix them up depending on the specific grandparents and the client wouldn't break, because the logical relationship between the resources are the same even though the underlying implementation might differ significantly.

If you had instead created the service such that it requires /grandparent/{grandparentID}?search={term} when you go one way but /children?parent={parentID}&search={term} a} when you go another way, that is too much coupling because the client would have to know to interpolate different things on different relations that are conceptually similar.

Whether you actually go with /grandparent/123?search={term} or /parent?grandparent=123&search={term} is a matter of taste and whichever implementation is easier for you right now. The important thing is to not require the client to be modified if you change your URL strategy or if you use different strategies on different parents-children relations.

Title: Designing a REST api by URI vs query string

Body:
Let's say I have three resources that are related like so:

```<code>Grandparent (collection) -> Parent (collection) -> and Child (collection)
</code>```

The above depicts the relationship among these resources like so: Each grandparent can map to one or several parents. Each parent can map to one or several children. I want the ability to support searching against the child resource but with the filter criteria:

If my clients pass me an id reference to a grandparent, I want to only search against children who are direct descendants of that grandparent.

If my clients pass me an id reference to a parent, I want to only search against children who are direct descendants of my parent.

I have thought of something like so:

```<code>GET /myservice/api/v1/grandparents/{grandparentID}/parents/children?search={text}
</code>```

and

```<code>GET /myservice/api/v1/parents/{parentID}/children?search={text}
</code>```

for the above requirements, respectively.

But I could also do something like this:

```<code>GET /myservice/api/v1/children?search={text}&grandparentID={id}&parentID=${id}
</code>```

In this design, I could allow my client to pass me one or the other in the query string: either grandparentID or parentID, but not both.

My questions are:

1) Which API design is more RESTful, and why? Semantically, they mean and behave the same way. The last resource in the URI is "children", effectively implying that the client is operating on the children resource.

2) What are the pros and cons to each in terms of understandability from a client's perspective, and maintainability from the designer's perspective.

3) What are query strings really used for, besides "filtering" on your resource? If you go with the first approach, the filter parameter is embedded in the URI itself as a path parameter instead of a query string parameter.

Thanks!


问:
Do I need use really INNER JOIN?
Imagine a coiffeur, with his services:

```<code>+----+-----------------+--------+
| id |      name       | amount |
+----+-----------------+--------+
|  1 | hair cut        |     40 |
|  2 | shampoo         |     10 |
|  3 | french manicure |     90 |
+----+-----------------+--------+
</code>```

Imagine a table of transactions:

```<code>+----+------------+------------------+
| id | id_service | date_transaction |
+----+------------+------------------+
|  1 |          1 | 01/01/2015       |
|  2 |          1 | 02/01/2015       |
|  3 |          1 | 02/01/2015       |
|  4 |          2 | 02/01/2015       |
|  5 |          2 | 02/01/2015       |
|  6 |          1 | 06/01/2015       |
|  7 |          1 | 06/01/2015       |
|  8 |          3 | 06/01/2015       |
|  9 |          2 | 06/01/2015       |
| 10 |          2 | 10/01/2015       |
| 11 |          1 | 10/01/2015       |
| 12 |          3 | 10/01/2015       |
| 13 |          1 | 10/01/2015       |
| 14 |          2 | 10/01/2015       |
| 15 |          2 | 11/01/2015       |
| 16 |          1 | 16/01/2015       |
+----+------------+------------------+
</code>```

With a simple INNER JOIN we can read, for example, the SUM of a specific day.

But our coiffeur is no technology addicted and tomorrow he will change every service.

So, to prevent this drama, how I must setup my webapp?

1) I repeat service.name and amount.name every time in the table of transactions? So, I don't use the INNER JOIN?

1a) I could lose also the possibility to GROUP BY, without numerics ID. And I cannot use them from service table because service change (or, worst) is deleted...

2) I need to block the user to edit/delete his service(s)?

3) What your consideration?

答:
Your transaction table should not have to rely on the services table.
That's because the moment a transaction is done, the relation to the services table is lost. Why?
In the services table apparently the name of your service or the amount of the service can change. In a historical transaction table, the name and amount will be what it is at the time you enter it into the transaction table and won't change if there's a changes in the services table.

That's why amount shouldn't be in the services table either but should have its' own table. That way you can keep a historical price record. And no, you don't make references to that in your transaction table either. Because a price can be anything. (like let's say you come in, but because you also bring your kid, the kid gets a haircut for half price. The transactions table has to have freedom to receive any custom amount.).

Ofcourse you can keep a reference to your services table, so if your client decides to change "super haircut" to "awesome haircut" which is the same service under another name, that way you can still group.

Title: Do I need use really INNER JOIN?


问:
Can a class method be accessed both in an instance and statically?
I am relatively new to class design and I have a task that I'm not sure how best to complete, or whether my idea in general is a code smell.

I'm developing a RPG where people can own monsters, so each one is an object instance of the Monster class. Since the sprite of a monster changes depending on a few different factors, the Monster class has a method for drawing the sprite that I call which does all the checks and logic and displays the correct sprite using the object's properties and I just call it like:

```<code>$Monster->drawSprite();
</code>```

This method does checks using other class methods, such as

```<code>$this->isHoldingItem();
</code>```

which checks data from the database using a unique monster ID (a class property) and stored as object properties.

Now and then for the story and in other places, I want to draw a monster sprite that isn't actually owned by anyone, so has no database row or object instance. Rather than hardcode the image URL or duplicate my code, is there any way a method can be called both as part of an instance and statically and respond accordingly? Is this even a good idea?

So in my head I could do:

```<code> $Monster->drawSprite();
</code>```

This will use the instance properties to determine all the necessary logic to display the sprite, or I could do:

```<code>Monster::drawSprite();
</code>```

To draw a monster sprite without relying on class properties. Maybe I could pass an array as an argument for all the necessary object property checks the method usually relies on.

I imagine I could do something using func_get_args() or lots of conditionals but I could see that turning into spaghetti code quickly. Is this a good idea, or is it even possible? I'm specifically referring to PHP with this question.

答:
If a method uses $this it cannot be called statically. Or at least it shouldn't be called statically even if some sort of weird PHP behavior allows it. You never know with PHP.

If you insist on keeping your architecture as is, i.e. with monsters drawing themselves (which is not a good architecture, like Doval said), the simplest way would be something like this.

Monster class has a static method drawSprite($img_url, $maybe_other_params) which accepts all data needed to draw a monster as it's arguments. You can pass it i.e. image url. It also has a method drawSelf() which draws itself, like your current drawSprite() does, but by calling drawSprite() and passing all the required parameters.

```<code>$usersMonster->drawSelf(); //called non statically
Monster::drawSprite($img_url, $other_stuff); // called statically

class Monster
{
    public function drawSelf()
    {
        $other_stuff = someComplicatedLogic();
        self::drawSprite($this->img_url, $other_stuff);
    }
    public static function drawSprite($img_url, $other_stuff)
    {
         // do the sprite drawing stuff
    }
}
</code>```

Although I should stress again it's not a good architecture. Doval's suggestion is what you really need. Even if it's not a complicated app... especially if it's not a complicated app: start developing good habits early, before you move to complicated stuff.

Body:
If a method uses $this it cannot be called statically. Or at least it shouldn't be called statically even if some sort of weird PHP behavior allows it. You never know with PHP.

If you insist on keeping your architecture as is, i.e. with monsters drawing themselves (which is not a good architecture, like Doval said), the simplest way would be something like this.

Monster class has a static method drawSprite($img_url, $maybe_other_params) which accepts all data needed to draw a monster as it's arguments. You can pass it i.e. image url. It also has a method drawSelf() which draws itself, like your current drawSprite() does, but by calling drawSprite() and passing all the required parameters.

$usersMonster->drawSelf(); //called non statically
Monster::drawSprite($img_url, $other_stuff); // called statically

class Monster
{
    public function drawSelf()
    {
        $other_stuff = someComplicatedLogic();
        self::drawSprite($this->img_url, $other_stuff);
    }
    public static function drawSprite($img_url, $other_stuff)
    {
         // do the sprite drawing stuff
    }
}

Although I should stress again it's not a good architecture. Doval's suggestion is what you really need. Even if it's not a complicated app... especially if it's not a complicated app: start developing good habits early, before you move to complicated stuff.


答:
The fundamental question that you have to ask is: What do you want the interface for your function to be? In particular, is the condition _Materials.ContainsKey(name) a precondition of the function?

If it is not a precondition, the function must provide a well-defined result for all possible vales of name. In this case, the exception thrown if name is not part of _Materials becomes part of the function's interface. That means it needs to be part of the interface documentation and if you ever decide to change that exception in the future, that will be a breaking interface change.

The more interesting question is what happens if it is a precondition. In that case the precondition itself becomes part of the function interface, but the way that a function behaves when this condition is violated is not necessarily part of the interface.

In this case, the approach that you posted, checking for precondition violations and reporting the error, is what is known as defensive programming. Defensive programming is good in that it notifies the user early when they made a mistake and called the function with a bogus argument. It is bad in that it significantly increases the maintenance burden, as user code might depend that the function handles precondition violations in a certain way. In particular, if you find that the runtime check ever becomes a performance bottleneck in the future (unlikely for such a simple case, but quite common for more complex preconditions), you might no longer be able to remove it.

It turns out that those disadvantages can be very significant, which gave defensive programming kind of a bad reputation in certain circles. However, the initial goal is still valid: We want to users of our function to notice early when they did a mistake.

Therefore many developers nowadays propose a slightly different approach for these kinds of issues. Instead of throwing an exception, they use an assert-like mechanism for checking preconditions. That is, preconditions may get checked in debug builds to assist users in catching mistakes early on, but they are not part of the functions interface. The difference may seem subtle at first glance, but it can make a huge difference in practice.

Technically, calling a function with violated preconditions is undefined behavior. But the implementation might decide to detect those cases and notify the user right away if that happens. Exceptions are unfortunately not a good tool to implement this, as user code can react on them and thus might start relying on their presence.

For a detailed explanation of the problems with the classic defensive approach, as well as a possible implementation for assert-style precondition checks, refer to John Lakos' talk Defensive Programming Done Right from CppCon 2014 (Slides, Video).

Title: Throw exception or let code fail


答:
I'm not sure why people think putting the ID values in the URL means its somehow a REST API, REST is about handling verbs, passing resources.

So if you want to PUT a new user, you'd have to send a fair chunk of data and a POST http request is ideal, so although you might send the key (eg. user id), you'll send the user data (eg name, address) as POST data.

Now it is a common idiom to put the resource identifier in the URI, but this is more convention than any form of canonical "its not REST if its not in the URI". Remember that the original thesis of REST doesn't really mention http at all, its an idiom for handling data in a client-server, not something that is an extension to http (though, obviously, http is our primary form of implementing REST).

For example, Fielding uses the request of an academic paper as an example. You want to retrieve the resource "Dr John's Paper on the drinking of beers", but you might also want the initial version, or the latest version, so the resource identifier might not be something that is easily referenced as a single ID that can be placed in the URI. REST allows for this and a stated intention behind it is:

REST relies instead on the author
  choosing a resource identifier that best fits the nature of the concept being identified

So there's nothing stopping you from using a static URI to retrieve your parents, passing in a search term in the query string to identify the exact user you're after. In this case, the 'resource' you're identifying is the set of grandparents (and so the URI contains 'grandparents' as part of the URI. REST includes the concept of 'control data' that is designed for determining which representation of your resource is to be retrieved - the example given in the these is cache control, but also version control - so my request for Dr John's excellent paper can be refined by passing the version as control data, not part of the URI.

I think an example of REST interface that is not usually mentioned is SMTP. When constructing a mail message, you send verbs (FROM, TO etc) with the resource data for each part of the mail message. This is RESTful even though it doesn't use the http verbs, it uses its own set.

So... whilst you do need to have some resource identification in your URI, it doesn't have to be your id reference. This can happily be sent as control data, in the query string or even in POST data. What you're really identifying in your REST API is that you're after a child, which you already have in your URI.

So to my mind, reading the definition of REST, you're requesting a child resource, passing in control data (in the form of querystring) to determine which one you want returned. As a result, you cannot make a URI request for a grandparent or parent. You want children returned so the term parent/grandparent or id should definitely not be in such a URI. Children should be.


问:
Comments for a class that isn't an entity
According to Java's commenting conventions, classes comments should describe a "thing", rather than "actions". It is easy when the class IS a thing (ex. a Clown), but what if it isn't?

In this case, the ShapeProvider is a proxy class that requests "stringified" Strings  to a small server application via the get method. The string is then parsed to build a BaseShape object, that is returned to the client of the service. The client simply draws the shape on a small GUI. This is a school work, so I'd want my comments to be as close as possible to the Java conventions.

```<code>/**
* How should I comment this?
*/
public class ShapeProvider extends ServerConnection{

    /**
    * Method comment that is okay.
    */
    public BaseShape get(){
       //Requests the shape
       //Parses the response
       //Use a Factory to create an instance of BaseShape
       //Return it
    }
}
</code>```

答:
But your ShapeProvider is a thing!

How comes, you don't see it as a thing? Your ShapeProvideris a someone who is responsible for providing you shapes while relying on X and Y to do so. I think that is a acceptable commentation regarding the commenting conventions.

But it shows you, that this code is actually not very well designed or named. Because why on earth would a ShapeProvider extend a ServerConnection? That's just wrong. A ShapeProviderrather relies on some repository or repository connection and uses it to create the shapes. extends should therefore not be used for this purpose at all!


问:
Strategies for parameter wrapping
Methods with many parameters are often sometimes unavoidable. In my own experience I often find this is the case for program entry points and complex mathematical procedures - where refactoring is either not possible, or would obscure the meaning of the method. Although there are no concrete limits for the number of parameters a method might have, it is patently undesirable to write/maintain/see methods with a large number of parameters.

An alternative is wrapping parameters into classes. This has some clear advantages, including:

Easier on the eye; nobody likes parameter fishing.

Easier maintenance; changing the parameters does not require modification to the method declaration.

Better typing; wrapping related parameters together into a single type can help clarify the meaning of the function.

However, there are several disadvantages to this approach:

Worse typing; coupling parameters that do not naturally fit together can be misleading.

Overloading becomes either impossible or messy.

Can impose unwanted foreign types on users.

Can lead to laziness.

For example: I've often seen Python code where the author repeatedly passes around objects generated by optparse (or argparse) whilst only using a small subset of the parameters in each method.

At the sake of brevity, here are the options:

```<code>my_method(Param1 a, Param2 b, Param3 c, ...., ParamInf zzz)
my_method(Params params)
my_method(Param1 a, Param2 b, Param3 c, SomeParams the_rest)
my_method(ParamSetA a, ParamSetB b, ...)
</code>```

Whilst this is a somewhat subjective subject, I am interested to hear strategies for dealing with methods with large numbers of parameters. Real-life examples - especially those that have undergone code review - would be especially helpful.

答:
Methods with many parameters are often unavoidable.

Since when?

I mean it might be unavoidable to have a couple of methods like this in a non-trivial codebase, but the vast majority of your methods will have one or two parameters.

Having a boatload of parameters is a sign that:
 1. Your function is doing too much.
 2. Your boatload of separate parameters are really more cohesive than you thought.

How you solve the problem depends on which sign is applicable. If your function is doing too much, then splitting it up will naturally lead to fewer parameters - even if one orchestration function has too many. The more isolated code also makes it easier to see what's going on to simplify further.

If your parameters are more cohesive, then aggregating them (or at least some of them) into a useful bundle/class/structure is better since that would be used outside of just this one function.

But at least personally, I find parameter objects to be vile. If the parameters are cohesive, then they should've been in a class from the start. If you're making them into a class "to make that function prettier" then you're missing the point. Fix the problem, not the symptom.

Title: Strategies for parameter wrapping


问:
How do I design an arbitrary system in an interview?
A common question in Tech Interview is to design a particular system, usually an existing product of the company. For example, "Design Google Docs".

What is the expected answer for such a question? I mean, such systems surely have a complex design which is beyond the scope of any interview. What are the interviewers expecting in such a short time?

答:
For me, if the person doesn't start off with identifying the key use-cases/stories then that would be enough to know they aren't prepared for a position requiring this particular skill.

Afterwards, they should be able to come up with an architectural solution based on the key use-cases/stories. Hopefully they used some systematic process for identifying modules other than pulling them from their.... I wouldn't expect much more from an interview situation for the solution.

However, I might pick one of the architectural modules and ask for a more detailed design, just to see if they have some design skills. It would also be nice to see that they consider the failure cases/performance issues. But I suspect at this point, we would be running into a time wall.  Thus, I really couldn't penalize them for not considering these issues because there's only so much time and I think it is reasonable for them to assume that considering every possible scenario is not expected out of a time-limited interview situation.


答:
The key factor here is how cohesive the parameters are.

If you have a group of parameters that are logically grouped and should belong to a class, then create a class for them. If they happen to occur together in parameter lists but are not logically grouped, keep them separate.

Keep this method as-is:

```<code>function getDistance(Point p1, Point p2) { ... }
</code>```

This one might be better served with an object to group parameters:

```<code>function manufacture(Make make, Model model, Year year) { ... }
</code>```

These parameters all work together to describe something:

```<code>class VehicleDescriptor {
  Make make;
  Model model;
  Year year;
}

function manufacture(VehicleDescriptor v) { ... }
</code>```

Title: Strategies for parameter wrapping

Body:
Methods with many parameters are often sometimes unavoidable. In my own experience I often find this is the case for program entry points and complex mathematical procedures - where refactoring is either not possible, or would obscure the meaning of the method. Although there are no concrete limits for the number of parameters a method might have, it is patently undesirable to write/maintain/see methods with a large number of parameters.

An alternative is wrapping parameters into classes. This has some clear advantages, including:

Easier on the eye; nobody likes parameter fishing.

Easier maintenance; changing the parameters does not require modification to the method declaration.

Better typing; wrapping related parameters together into a single type can help clarify the meaning of the function.

However, there are several disadvantages to this approach:

Worse typing; coupling parameters that do not naturally fit together can be misleading.

Overloading becomes either impossible or messy.

Can impose unwanted foreign types on users.

Can lead to laziness.

For example: I've often seen Python code where the author repeatedly passes around objects generated by optparse (or argparse) whilst only using a small subset of the parameters in each method.

At the sake of brevity, here are the options:

```<code>my_method(Param1 a, Param2 b, Param3 c, ...., ParamInf zzz)
my_method(Params params)
my_method(Param1 a, Param2 b, Param3 c, SomeParams the_rest)
my_method(ParamSetA a, ParamSetB b, ...)
</code>```

Whilst this is a somewhat subjective subject, I am interested to hear strategies for dealing with methods with large numbers of parameters. Real-life examples - especially those that have undergone code review - would be especially helpful.

Body:
The key factor here is how cohesive the parameters are.

If you have a group of parameters that are logically grouped and should belong to a class, then create a class for them. If they happen to occur together in parameter lists but are not logically grouped, keep them separate.

Keep this method as-is:

function getDistance(Point p1, Point p2) { ... }

This one might be better served with an object to group parameters:

function manufacture(Make make, Model model, Year year) { ... }

These parameters all work together to describe something:

class VehicleDescriptor {
  Make make;
  Model model;
  Year year;
}

function manufacture(VehicleDescriptor v) { ... }


问:
Declarative caching on Collections
I am interested in using Spring's Cache Abstraction on a module that I am working with but all data operations are on collections to avoid multiple datasource invocations, so I am not sure I have a decent "pointcut" at which to method-level cache. This is not a Spring or Java specific issue but more of a design problem.

For example:

```<code>public class SomeDataAccessObject{
 private SomeBatchingDataSourceAbstraction datasource;

 //would ideally add a cache annotation to this method to cache based on input, but that
 //clearly won't work in this scenario because we are loading multiple which may have
 //some cache hits only
 public List<String> getNames(List<Integer> ids){
  //ideally I would load as many names as I can from the cache and
  //then use the datasource to get the rest
  //I can achieve this with a programatic cache but it is very invasive
  return datasource.fetch(ids);
 }

}
</code>```

Has anyone come up with a good way to redesign such a scenario that would allow me to use Spring-style method level declarative caching? Please remember that I want to keep the data access object (above) effectively stateless in order to be thread safe.

答:
I don't believe this can be accomplished via Spring's cache abstraction, its design doesn't appear to support your use case (unless I'm misunderstanding your intent).

Spring's method level caching hinges on the ability to generate a unique key given the method parameters via a KeyGenerator.  This simple key-value store approach will not work since you expect a subset of the data to be cached depending on the specific IDs being passed in.

If you're looking to cache based on the subset of IDs in the invocation, utilizing the JPA/Hibernate query cache may meet your needs.

Spring 4 by default uses the new SimpleKeyGenerator, which produces SimpleKey objects utilizing hashCode() and equals() contracts - delegating to Arrays.deepHashCode() and Arrays.deepEquals() for method invocations with multiple parameters.

Title: Declarative caching on Collections


问:
Is it better to perform a calculation in the field's setter or have a different method?
I'm implementing a simple Quota object which determines a usage percentage based on the maximum and the used.

```<code>private int maximum;
private int used;

public Quota(int used, int maximum) {
    this.maximum = maximum;
    this.used = used;
}

public double getUsagePercentage() {
    return ((double) used / (double) maximum) * 100.0;
}

public int getMaximum() {
    return maximum;
}

public void setMaximum(int maximum) {
    this.maximum = maximum;
}

public int getUsed() {
    return used;
}

public void setUsed(int used) {
    this.used = used;
}
</code>```

I realized that I could do it another way, though, and have the logic actually in the setter:

```<code>private int maximum;
private int used;
private double percentageUsed;

public Quota(int used, int maximum) {
    this.maximum = maximum;
    this.used = setUsed(used);
}

public int getMaximum() {
    return maximum;
}

public void setMaximum(int maximum) {
    this.maximum = maximum;
    percentageUsed = ((double) used / (double) maximum) * 100.0;
}

public int getUsed() {
    return used;
}

public void setUsed(int used) {
    this.used = used;
    percentageUsed = ((double) used / (double) maximum) * 100.0;
}

public double getUsagePercentage() {
    return percentageUsed;
}
</code>```

The second way seems much, much uglier to me, but maybe I'm just indoctrinated.  Obviously I realize that the logic is copied between the two setters, but even if you extracted it into its own private helper method, you get the point.  I thought that perhaps this was the better approach so that the calculation of the percentage doesn't have to happen every single time the getUsagePercentage() method is called.  If neither the maximum nor the used values have changed, it seems wasteful to continue performing an operation that we already know the answer to.

Is there any precedent for which to choose over the other?  I like the first better just because I've been doing Java forever, but that's not a solid argument for actually keeping it that way.  What are the benefits and drawbacks of both?  Or is one genuinely, objectively better than the other?

答: If you set the one value (maximum) and then update the next (used) (and even more often - think of a progress bar) you are doing the calculation twice and even worse, nobody asked for the values between the setXY-operations. Why spend time for things nobody actually requests. Thus it is perfectly fine to use the getter to calculate the real value whenever it is needed. As you found out, you are violating the DRY (don't repeat yourself)-Principle. With more complex setters and complex calculations, your tradeoff will be even more worse. Your first example is fine.</p>


答:
One common guideline is that for any fact known by your system, there should be only one place where it is stored. In a database, this is known as normalisation; in object design the principle is sometimes referred to as "Single Point of Truth", or the acronym SPOT.  This is closely related to the principle "don't repeat yourself" (DRY), and in fact in one formulation of DRY is actually identical:

"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."

In your example, there are two points of truth for the percentage - the variable that stores it directly, and the variables that hold the full integer values it is calculated from.  This isn't a particularly bad problem, because the two are within a single small class and can therefore be managed, but unless you have a good reason to do this, I'd avoid it.

Title: Is it better to perform a calculation in the field's setter or have a different method?

Body:
I'm implementing a simple Quota object which determines a usage percentage based on the maximum and the used.

```<code>private int maximum;
private int used;

public Quota(int used, int maximum) {
    this.maximum = maximum;
    this.used = used;
}

public double getUsagePercentage() {
    return ((double) used / (double) maximum) * 100.0;
}

public int getMaximum() {
    return maximum;
}

public void setMaximum(int maximum) {
    this.maximum = maximum;
}

public int getUsed() {
    return used;
}

public void setUsed(int used) {
    this.used = used;
}
</code>```

I realized that I could do it another way, though, and have the logic actually in the setter:

```<code>private int maximum;
private int used;
private double percentageUsed;

public Quota(int used, int maximum) {
    this.maximum = maximum;
    this.used = setUsed(used);
}

public int getMaximum() {
    return maximum;
}

public void setMaximum(int maximum) {
    this.maximum = maximum;
    percentageUsed = ((double) used / (double) maximum) * 100.0;
}

public int getUsed() {
    return used;
}

public void setUsed(int used) {
    this.used = used;
    percentageUsed = ((double) used / (double) maximum) * 100.0;
}

public double getUsagePercentage() {
    return percentageUsed;
}
</code>```

The second way seems much, much uglier to me, but maybe I'm just indoctrinated.  Obviously I realize that the logic is copied between the two setters, but even if you extracted it into its own private helper method, you get the point.  I thought that perhaps this was the better approach so that the calculation of the percentage doesn't have to happen every single time the getUsagePercentage() method is called.  If neither the maximum nor the used values have changed, it seems wasteful to continue performing an operation that we already know the answer to.

Is there any precedent for which to choose over the other?  I like the first better just because I've been doing Java forever, but that's not a solid argument for actually keeping it that way.  What are the benefits and drawbacks of both?  Or is one genuinely, objectively better than the other?


问:
Structuring data to represent a tree with squirrels
What I want to represent

Let's assume I have several schemas of the following kind:

It is a tree on which positions of squirrels are represented by a blue dot. The number of bifurcations differ from one tree to another, the number of squirrels varies from one tree to another, the positions of the squirrels vary (and are on a continuous scale), all trees are not necessarily symmetric (unlike the picture) and the length of the branches differ (on the picture the length of the second branches are all the same, the lengths of the third branches are all the same. This is not necessarily always the case).

The problem

I am trying to describe these trees with numbers so that I can play with these numbers and easily calculate the distance between two squirrels (following the branches, not by jumping), calculate the distance between a squirrel and the ground (the bottom of the trunk) or calculate the density of squirrels per branch.

The angles between branches do not matter and the branches have no width (they are just lines). The info I need are the length of the branches (on a continuous scale), the positions of the squirrels (on a continuous scale) relative to their branch, the number of bifurcations and the positions of the branches relative to other branches (whether one branch is attached to another one).

My (very) poor solutions

One way to describe this tree is to digitalize it. I could make a big array with 0s everywhere there is nothing, 1s everywhere there is a branch and a 2 everywhere there is a squirrel (and a branch necessarily, no flying squirrel on the picture!). That would be a solution but I would very big arrays and it is really not very handy to infer things like the average distance between two squirrels. Moreover, we lose precision about the positions of the squirrels and the lengths of the branches

Another solution would be to have two sets of vectors and one set of points. The first set of vector describes the positions of each squirrel relative to the bottom-left corner, another set of vector defines the the length and direction (although we don't directly need this info) of each branch and the set of points indicate where the starting points of the vectors describing the branches. It really doesn't seem to be a good idea; it is too descriptive (too much info) and is not very handy for making the kind of calculations I need to perform afterward.

I feel like I focus too much on the picture and have a hard time realizing how the informations I need could be coded/stored. Can you help me with that?

答:
The classic way to store a tree in a database is to use a self-referential table. If you take James Anderson's branch table and add an optional parentBranchID field, you are there. The only branch with a null parentBranchId will be the root node.

Similarly, read the whole table into memory using branch classes that have both a parentBranchID and a parentBranch instance pointer. The class will also need a collection of squirrels - this can be created (in Java) by an OR tool like myBatis or Hibernate.

Iterate over the list of classes, creating the parent pointer linkages, and populating a list of child branches in each branch. You now have an in-memory tree that can be traversed in both directions.

Finding the distance between 2 squirrels is likely a two-step process.

Starting from one squirrel, work your way up the tree (towards the root node) until you find a node that is also a parent of the second squirrel.

Write a branch member function like getDistanceTo(Squirrel squirrel). This is likely to be recursive, as if the squirrel is not on the branch, you need to try each child branch in turn. Call the function for each squirrel, and add the distances.


问:
Throw exception or let code fail
I am wondering if there are any pros and cons against this style:

```<code>private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}
</code>```

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

答:
The exception throwing code is redundant.

If you call:

_Materials.Add(
          name,
          Resources.Load(string.Format("Materials/{0}", name)) as Material

with the same key it will throw a

```<code>System.ArgumentException
</code>```

The message will be: "An item with the same key has already been added."

The ContainsKey check is redundant since essentially the same behavior is achieved without it.  The only item that is different is the actual message in the exception.  If there is true benefit from having a custom error message, then the guard code has some merit.

Otherwise, I would probably refactor out the guard in this case.

Title: Throw exception or let code fail

Body:
The exception throwing code is redundant.

If you call:

_Materials.Add(
          name,
          Resources.Load(string.Format("Materials/{0}", name)) as Material

with the same key it will throw a

System.ArgumentException

The message will be: "An item with the same key has already been added."

The ContainsKey check is redundant since essentially the same behavior is achieved without it.  The only item that is different is the actual message in the exception.  If there is true benefit from having a custom error message, then the guard code has some merit.

Otherwise, I would probably refactor out the guard in this case.


问:
Sudoku hidden sets algorithm
I am writing a solver for the game sudoku. I am trying to implement the hidden set check in it and I can't figure out a way to do it well.

I need to find out if there is a set of cells of size N in which a number of N candidates appear, where those N candidates are not present in any of the cells outside the set. For example suppose I have the following cells containing possible values:

```<code>A={1,2,5} B={2,3,8} C={2,3,4,5,8} D={3,4,5} E={5,6,7}
</code>```

The hidden set in this case is {1,2,8} (and N in this case is 3)

{1} appears in cell A only

{2} appears in cells B and C only

{8} appears in cells B and C only

Not all three cells contain all three numbers, but together they only appear in three cells.

As a counterexample, the set {2,8} would not be valid, because even though cell B contains both and cell C does as well, the number 2 is also included in cell A, which means I have two values covered by three cells, and as I said in the beginning, I need the number of cells to be equal to the number of values in the set.

It should be mentioned that I will not know which values to test for. The only input would be the list of cells, and the algorithm needs to find any such sets that may exist in it for N = 1 to the number of cells - 1.

答:
Edit:  I cut it down too much here.  I'll leave the original intact and then point out the flaw.

Before rejecting the brute force solution look at the problem size.

Sudoku has only 9 items in a row.  Thus the naive brute force is only 512 combinations to check.

In practice there can't be a hidden set of 9 in 9 entries, this means the largest set you need to check is 8--for a maximum of 256 combinations.

However, suppose you have a hidden set of 8 in 9 entries--what does that say about the 9th value?  It can only have one prospect, thus you would have already picked it and you're finding a hidden set of 8 in 8--but again that can't occur.

Thus you're down to 7, for a total of 128 cases.

However, suppose you have that?  What are the values of the last two entries?  If any entry had only one prospect you would have already picked it.  That leaves only one possible case--both of the remaining two cells have exactly two prospects.  Two cells, two prospects, you have a set--you should have found that before you were looking for hidden sets.

Now we are down to 6, for a total of 64 cases.

Brute forcing 64 cases?  Horrifying!

Update: My logic as to the maximum set size you can find is correct but the number of cases is higher than I was figuring.  It's not 6 out of 6, it's 6 out of 9.  Therefore there are 465 combinations to check.

In practice, however, you rarely find an entire row with no known values and thus you'll rarely have to do anything like all the cases.

The conclusion is the same:  Brute force is quite reasonable.

Title: Sudoku hidden sets algorithm


问:
Classic ASP to Java UI Conversion
My question is based on a business model of a financial services organization that currently is supporting applications that are a hybrid mix of Classic ASP and Java, with some JSP’s already in some of the applications.

Specifically, in our large application, all of the FE starts with ASP and then uses a crude request based token that is used by other code to determine which JSP to call.  In the other application, which is a suite of four linked applications, the main application and one other use all ASP in the front end and java code for the BE.  The two others that are linked to it use JSPs and java code exclusively.

Due to excessive maintenance costs of using this hybrid system and concerns for using obsolete technology, management has bought into modernizing our applications to all Java and removing all ASPs on these applications.  I'm on a panel group that would have to propose which Java UI to use as each UI technology has its own set of strengths and weaknesses.

Making the assumption that the following item makes up our basic use case: modernizing our current classic ASP UI to a Java standard, which incorporates the following goals:

In general, a system that is more amenable to change.

That would be flexible for future growth based on technology changes in the market.

Not tied to a niche market or something experimental or unstable or cutting edge.

More modularized code that would allow the UI to be converted to another technology, if the business need arises.  This would coincide with the code structure and not just the technology, but I felt it was worth mentioning.

Better performance.

Stable and scalable.

More secure than classic ASP.

Better ROI on development time.  It's been hard finding people with Classic ASP that also know Java well.  Also, this would also have to incorporate the learning curve for new developers as I've heard JSF has a steep one.

Now, to the point, with the number of java UI frameworks that I’m aware of: JSP, JSF, JavaFx, Tapestry, Vaadin, GWT, Velocity, Freemarker, and Thymeleaf, based on actual experience from other developers that have actually had to do this type of conversion what have you used to do this?

Do you have any lessons learned that would coincide with this use case and business model?  I don't want opinions, but answers from real life experiences.

Currently, we are being asked to limit ourselves to just JSP or JSF, but I'm not so sure those should be the only alternatives.  Currently, the talk is to move everything to one or the other as another team is going down the JSF route.  We are wanting to adopt a standard for everyone however.  So overall, we have some infrastructure for JSF, but it's heavily favored for JSP at this time.

答:
After more research I concurred with our group that for this particular application, some form of JSP technology was the correct answer.
These were some of the main points:

ASP to JSP is not a huge paradigm shift and are someone similar in my opinion.  I read that JSP's came from the ASP concept originally.

JSF has a steep learning curve and it's hard to find devs with that expertise.

JSF abstracts away HTML, CSS, and HTTP from the devs and is a departure from all the modern web apps I've worked with.  Therefore, if you decide later to move to something else, it's a rewrite.

As stated before, JSP is already in the app, about 50% of the pages approximately, so the technology is already there and it's maintained by experienced devs that have been on the app for years.

To mitigate risk and to keep costs lower, JSP's are the right choice for us.  Now we are deciding on what we are going to use along with it, like Spring MVC or Struts2.

I found this official link for a listing of technologies in Java EE 7.  JSP is still listed there and is still in JSR 366 for Java EE 8, so JSP's are not truely deprecated overall.  What else was important to me was that JSTL and EL are also supported in Java 7 & 8.

Title: Classic ASP to Java UI Conversion


问:
MVC URL structure with URI parameters
When creating routes for your MVC web application I have seen two possible ways to pass variables to a controller method:

With the first approach the variable is passed to a parameter of the controller method and utilized as such:

```<code>1a. http://domain.com/controller1/method1/variable1

1b. class controller1 extends main_controller(){

      function method1($var1){

         echo $var1; //prints "variable1"

      }

    }
</code>```

The next approach uses URI parameters and allows for the name of the variables being passed to appear in the URL:

```<code>2a. http://domain.com/controller1/method1/variable1/34/variable2/56

2b. class controller1 extends main_controller(){

        function method1(){

            //split the uri into an array using framework function
            $uri = $this->uri_to_assoc()

            //call the uri variables as array indexes
            echo $uri['variable1']; //prints "34"

            echo $uri['variable2']; //prints "56"

        }

    }
</code>```

My question is concerning when to use one case vs the other? My guess would be that approach #2 would be more for RESTful web services while approach #1 would be for a web application that will be serving html and crawled by search engines?

答:
I would say it depends on your needs.

Do you need to know the name of the variable?

Do you want the (multiple) variables to be passed in a specific order?

Is the amount of variables going to grow (like filters)?

Does it need to be part of the url? (i.e. for SEO reasons)

I mostly know two variants (different then the examples you gave), and in applications I write I catch these in these ways:

1. In the url: www.youtube.com/brandname

Using a regular expression I predefine the names of the different parts in the url. And thus their position is (mostly) fixed.

/(?<id>[0-9])/(?<slug>[a-z0-9])/

Then you can pass these named or unnamed to the controller. How doesn't matter that much, as you already know which are coming in already.

function channel($id, $slug)

2. In the GET/POST request: www.google.com/?q=foo&client=bar&channel=baz&...

Just accessing the GET/POST directly.

```<code>function search() {
    if (empty($_GET['q']) || invalid($_GET['q'])) {
        // return to user
    }

    $query = $_GET['q'];
}
</code>```

Title: MVC URL structure with URI parameters

Body:
I would say it depends on your needs.

Do you need to know the name of the variable?

Do you want the (multiple) variables to be passed in a specific order?

Is the amount of variables going to grow (like filters)?

Does it need to be part of the url? (i.e. for SEO reasons)

I mostly know two variants (different then the examples you gave), and in applications I write I catch these in these ways:

1. In the url: www.youtube.com/brandname

Using a regular expression I predefine the names of the different parts in the url. And thus their position is (mostly) fixed.

/(?<id>[0-9])/(?<slug>[a-z0-9])/

Then you can pass these named or unnamed to the controller. How doesn't matter that much, as you already know which are coming in already.

function channel($id, $slug)

2. In the GET/POST request: www.google.com/?q=foo&client=bar&channel=baz&...

Just accessing the GET/POST directly.

function search() {
    if (empty($_GET['q']) || invalid($_GET['q'])) {
        // return to user
    }

    $query = $_GET['q'];
}


问:
Are There Realistic/Useful Solutions for Source Control for Ladder Logic Programs
Version control for ladder logic (LL) programs for programmable logic controllers (PLCs) seems to be virtually non-existent. It may be because LL is a visual language and tends to be stored in binary files, or it may be because source code control hasn't "caught on" in process control engineering circles - or perhaps my Google-Fu is weak tonight.

Do you know of any realistic and useful solutions for version control for such systems?

Definitions:

realistic = changes to the programs are tracked by user and subject to reversion and merges

useful = the system integrates with visual LL designers, is not limited to LL from a single PLC manufacturer, and does not cost a ridiculous amount of money?

Note: I have heard of people using SVN or Mercurial et al to track the binary files, but I don't think the diff/merge capabilities would display readable differences.

ADDENDUM:

At first we only had to support Allen-Bradley PLCs. Now we also have Siemens and MicroLogix PLCs. Still searching for a viable solution...

答:
I only just saw this question, and there is actually a canned solution - from GE-IP of all places.  Check out Proficy Change Management.  This product does version control from a PLC control systems point of view, rather than a pure version control of files point of view - it works as a layer sitting on top of a VCS (the scary part is that originally this VCS was Visual SourceSafe) and handles rights management, reporting and checkout/checkin.

While the product is from GE-IP, it is designed to support a variety of PLC and HMI systems out of the box.

Full disclosure, I used for work for a company selling and installing PCM (but that was 7 years ago).  So if you ask me what it was like back then I'm likely to tell you where it all went wrong!


答:
If you build a graph like below, it's not too difficult to solve.  You still have to test a lot of combinations, but you can do a lot of pruning.  I took Doc Brown's suggestion to add 1 to C to make it a little more interesting.

Start by looking at the numbers with only one edge.  These are the sets of 1.  You can remove them from the graph.

Next we find sets of two.  We can temporarily prune 2, 3, and 5 from consideration in this set, because they are all present in at least three cells.  That leaves 1, 4, and 8.

Loop through them and follow the edges up.  If you start with 1, then A and C must be in the set.  Follow the edges of A and C back down, which gives you 4 and 8 as candidates for the set.  In order for it to be a set of two, neither must introduce a new cell, but 4 introduces D and 8 introduces B, so we know there are no sets of two containing 1, so it can be temporarily pruned.

Backtrack and repeat with 4 and 8 and we can determine there are no sets of two.  If we had found sets of two, we could remove those from the graph.

Sets of three work similarly.  We just recurse one level deeper.

Title: Sudoku hidden sets algorithm

Body:
I am writing a solver for the game sudoku. I am trying to implement the hidden set check in it and I can't figure out a way to do it well.

I need to find out if there is a set of cells of size N in which a number of N candidates appear, where those N candidates are not present in any of the cells outside the set. For example suppose I have the following cells containing possible values:

```<code>A={1,2,5} B={2,3,8} C={2,3,4,5,8} D={3,4,5} E={5,6,7}
</code>```

The hidden set in this case is {1,2,8} (and N in this case is 3)

{1} appears in cell A only

{2} appears in cells B and C only

{8} appears in cells B and C only

Not all three cells contain all three numbers, but together they only appear in three cells.

As a counterexample, the set {2,8} would not be valid, because even though cell B contains both and cell C does as well, the number 2 is also included in cell A, which means I have two values covered by three cells, and as I said in the beginning, I need the number of cells to be equal to the number of values in the set.

It should be mentioned that I will not know which values to test for. The only input would be the list of cells, and the algorithm needs to find any such sets that may exist in it for N = 1 to the number of cells - 1.