答:
The answer of which approach to use depends on the memory management strategy that users of your api will employ. For example, using an Object pool or Region based memory requires using strategy 2. If there is any chance that consumers of the api will want more control over memory management, strategy 2 is preferable.

If you are convinced that malloc and free are enough for all consumers of your api, strategy 1 is adequate. Even in this case it seems reasonable to provide the functions of 2 and to define the malloc and free versions in terms of those functions. This has the benefit of separating the logically distinct tasks of allocating memory and initializing that memory.

Title: How to create "constructors" for structures in C

Body:
The problem

I have this structure that I want to create a "constructor" for it.

```<code>struct example {
    int x, y, z; /* various members */
    struct another *another; /* pointer to another structure */
}
</code>```

The two different ways I know of

Using functions that create and delete structures on heap

I can create structures by making functions that allocates them on the heap like this:

```<code>/* create example */
struct example *example_new(int x, int y, int z) {
    struct example *p = malloc(sizeof *p);
    p->x = x;
    p->y = y;
    p->z = z;
    p->another = another_new();
}

/* delete example */
void example_new(struct example *p) {
    another_del(p->another);
    free(p);
}
</code>```

Using functions that initializes and frees memory for structure through pointer

Or I could initalize the structure by passing pointer to the function and have the user responsible for allocating and deallocating memory for it.

```<code>/* initalize example */
void example_init(struct example *p, int x, int y, int z) {
    assert(p);
    p->x = x;
    p->y = y;
    p->z = z;
    p->another = another_new();
}

/* free memory allocated for example */
void example_free(struct example *p) {
    another_del(p->another);
}
</code>```

My thoughts

I usually prefer first approach when creating recursive structures (like Trees and Linked Lists) but use the second approach in all other cases.

I tried to use the second approach for a recursive structure and it turned out to be quite messy.

The question

How do you choose between these two ways? Is there a third way you would use to solve this problem?


问:
How to create "constructors" for structures in C

The problem

I have this structure that I want to create a "constructor" for it.

```<code>struct example {
    int x, y, z; /* various members */
    struct another *another; /* pointer to another structure */
}
</code>```

The two different ways I know of

Using functions that create and delete structures on heap

I can create structures by making functions that allocates them on the heap like this:

```<code>/* create example */
struct example *example_new(int x, int y, int z) {
    struct example *p = malloc(sizeof *p);
    p->x = x;
    p->y = y;
    p->z = z;
    p->another = another_new();
}

/* delete example */
void example_new(struct example *p) {
    another_del(p->another);
    free(p);
}
</code>```

Using functions that initializes and frees memory for structure through pointer

Or I could initalize the structure by passing pointer to the function and have the user responsible for allocating and deallocating memory for it.

```<code>/* initalize example */
void example_init(struct example *p, int x, int y, int z) {
    assert(p);
    p->x = x;
    p->y = y;
    p->z = z;
    p->another = another_new();
}

/* free memory allocated for example */
void example_free(struct example *p) {
    another_del(p->another);
}
</code>```

My thoughts

I usually prefer first approach when creating recursive structures (like Trees and Linked Lists) but use the second approach in all other cases.

I tried to use the second approach for a recursive structure and it turned out to be quite messy.

The question

How do you choose between these two ways? Is there a third way you would use to solve this problem?

答:
There is no answer that's always going to be the right one, because different programs will have different needs.  If you have enough information to make an informed call one way or the other, that's the way you should go.  (For example, if your program is required to have the highest throughput possible, forcing a malloc()/free() pair each time some function needs to use your structure probably isn't going to fly.)

If you're going to build a general-purpose library, it isn't much additional effort to build it in a way that supports both:

void example_init(struct example *p, int x, int y, int z) - Initializes the structure pointed at by p.  This can be called by anyone who has a struct example whether it's an automatic, allocated on the heap or pulled out of a pool.

void example_destroy(struct example *p) - Does whatever is necessary to de-initialize the structure pointed at by p.  (In your case, this would be freeing the memory allocated for the another member.)  Note that it does not free p, because it has no knowledge of whether or not the structure is on the heap or if the caller isn't going to re-use it by calling example_init() again.

struct example * example_new(int x, int y, int z) - Allocates space for the structure on the heap, calls example_init() against it and returns the pointer.

void example_del(struct example * p) - Calls example_destroy(p) and then frees p.

There is a hazard to this approach, which is that someone could try to do pairs of example_init()/example_del() or example_new()/example_destroy() calls.  Tools like valgrind and some implementations of free() can weed those problems out automagically.  Another approach would be to set aside a bit somewhere in the structure that can be set when the structure was on the heap and use assertions to complain if someone goes about it the wrong way.  (example_del() would need to clear the bit before calling example_destroy().)

ContentLicense: CC BY-SA 3.0


问:
Which design pattern to choose when supporting multiple analytic tools?
I have spent quite some time learning all possible design patterns but I cannot find the ideal one for the following case. I am developing an iOS app where we are using multiple analytics tools like Google Analytics/Facebook Analytics and it is possible that in the future we will add some more (our company is obsessed with measuring :D).

Each of them uses their custom SDK to log an event which comes with its own method to send an event and its own parameters. I would love to refactor it and create a module where adding new analytics tool wouldn't lead to code smell and in best case scenario there would be a central place which would dispatch the events at once.

I was thinking about this:

Defining a protocol AnalyticsProtocol which requires implementation of sendEvent method

Defining AnalyticsEvent class for every tool (FacebookAnalyticsEvent, GoogleAnalyticsEvent) which conforms to the protocol above and implements sendEvent method. Each of these classes would have its own init method.

Cental dispatch class which takes an array of id<AnalyticsProtocol> objects and calls sendEvent on every single one of them.

Do you have any better ideas? Thanks.

答:
Is it important for you to own the solution to this problem? It sounds like what you need is already available from third parties (I've used https://segment.com/).

Since you asked for a software design pattern; the Strategy pattern might serve you well. You could define a common interface for reporting events and implement a strategy for each of your analytics services. You could also create an aggregate strategy which conforms to the same interface and forwards an event to several other strategies when you are using many analytics services at once.


问:
Containers and shared ownership within a class instance
I have two objects as member variables of a class.

```<code>std::unique_ptr<Object> specificObject;
std::vector<std::unique_ptr<Object>> objects;
</code>```

I know that specificObject will always be within objects. How can I point to specificObject without using shared_ptrs as I do not want the ownership of the objects in the container to be considered shared? Is this a case where a raw pointer can be used, or is shared_ptr really the solution?

答:
In an ideal world, all owning pointers are smart pointers, and raw non-owning pointers are only used when NULL is considered a potentially valid value. If it is indeed true that specificObject will always be within objects, then at least in theory it should be possible to make specificObject be an Object reference, thereby allowing the compiler to enforce that it always has a non-NULL value for its entire lifetime.

In a less than ideal world, it might not be feasible or even possible to initialize specificObject to point to a member of objects, depending on how exactly specificObject is determined and whether that logic can reasonably be constexpr'd. Then the question comes down to whatever the lifetimes of all the Objects within objects are. If you know that they will all continue to exist at least as long as specificObjects does, then a non-owning raw pointer is perfectly safe. I suspect this is the most typical situation.

In a very non-ideal world, it may be possible for objects to gain and lose any of its members at any time, so you need to account for the possibility that specificObject gets invalidated while your program is still trying to do stuff with it. In this case, weak_ptr is the tool of choice, as it's specifically designed for situations where you don't know when the object's lifetime might end, yet you don't want to needlessly prolong it. Of course, that would require changing all your unique_ptrs to shared_ptrs, and unsurprisingly it is the least intuitive of the smart pointers, which is why I'm mentioning this option last.


问:
Given a herd of horses, how do I find the average horn length of all unicorns?
The question above is an abstract example of a common problem I encounter in legacy code, or more accurately, problems resulting from previous attempts at solving this problem.

I can think of at least one .NET framework method that is intended to address this problem, like the Enumerable.OfType<T> method. But the fact that you ultimately end up interrogating an object's type at runtime doesn't sit right with me.

Beyond asking each horse "Are you a unicorn?" the following approaches also come to mind:

Throw an exception when an attempt is made to get the length of a non-unicorn's horn (exposes functionality not appropriate for each horse)

Return a default or magic value for the length of a non-unicorn's horn (requires default checks peppered throughout any code that wants to crunch horn stats on a group of horses that could all be non-unicorns)

Do away with inheritance and create a separate object on a horse that tells you if the horse is a unicorn or not (which is potentially pushing the same problem down a layer)

I have a feeling this is going to be best answered with a "non-answer." But how do you approach this problem and if it depends, what's the context around your decision?

I'd also be interested in any insights on whether this problem still exists in functional code (or maybe it only exists in functional languages that support mutability?)

This was flagged as a possible duplicate of the following question:
How to avoid downcasting?

The answer to that question assumes that one is in possession of a HornMeasurer by which all horn measurements must be made. But that's quite an imposition on a codebase that was formed under the egalitarian principle that everyone should be free to measure the horn of a horse.

Absent a HornMeasurer, the accepted answer's approach mirrors the exception-based approach listed above.

There's also been some confusion in the comments on whether horses and unicorns are both equines, or if a unicorn is a magical subspecies of horse. Both possibilities should be considered--perhaps one is preferable to the other?

答:
There's nothing wrong in .NET with:

```<code>var unicorn = animal as Unicorn;
if(unicorn != null)
{
    sum += unicorn.HornLength;
    count++;
}
</code>```

Using the Linq equivalent is fine too:

```<code>var averageUnicornHornLength = animals
    .OfType<Unicorn>()
    .Select(x => x.HornLength)
    .Average();
</code>```

Based on the question you asked in the title, this is the code I would expect to find.  If the question asked something like "what is average of animals with horns" that would be different:

```<code>var averageHornedAnimalHornLength = animals
    .OfType<IHornedAnimal>()
    .Select(x => x.HornLength)
    .Average();
</code>```

Note that when using Linq, Average (and Min and Max) will throw an exception if the enumerable is empty and type T is not nullable.  That's because the average really is undefined (0 / 0).  So really you need something like this:

```<code>var hornedAnimals = animals
    .OfType<IHornedAnimal>()
    .ToList();
if(hornedAnimals.Count > 0)
{
    var averageHornLengthOfHornedAnimals = hornedAnimals
        .Average(x => x.HornLength);
}
else
{
    // deal with it in your own way...
}
</code>```

Edit

I just think this needs adding... one of the reasons a question like this doesn't sit well with object-oriented programmers is that it assumes we're using classes and objects to model a data structure.  The original Smalltalk-esque object oriented idea was to structure your program out of modules that were instantiated as objects and performed services for you when you sent them a message.  The fact that we can also use classes and objects to model a data structure is a (useful) side effect, but they're two different things.  I don't even think the latter should be considered object-oriented programming, since you could do the same thing with a struct, but it just wouldn't be as pretty.

If you're using object-oriented programming to create services that do things for you, then querying whether that service is actually some other service or concrete implementation is generally frowned upon for good reasons.  You were given an interface (typically through dependency injection) and you should code to that interface/contract.

On the other hand, if you're (mis-)using the class/object/interface ideas to create a data structure or data model, then I personally don't see a problem with using the is-a idea to its fullest.  If you've defined that unicorns are a sub-type of horses and it totally makes sense within your domain, then absolutely go ahead and query the horses in your herd to find the unicorns.  After all, in a case like this we're typically trying to create a domain specific language to better express the solutions of the problems we have to solve.  In that sense there's nothing wrong with .OfType<Unicorn>() etc.

Ultimately, taking a collection of items and filtering it on type is really just functional programming, not object-oriented programming.  Thankfully languages like C# are comfortable handling both paradigms now.

Body:
There's nothing wrong in .NET with:

var unicorn = animal as Unicorn;
if(unicorn != null)
{
    sum += unicorn.HornLength;
    count++;
}

Using the Linq equivalent is fine too:

var averageUnicornHornLength = animals
    .OfType<Unicorn>()
    .Select(x => x.HornLength)
    .Average();

Based on the question you asked in the title, this is the code I would expect to find.  If the question asked something like "what is average of animals with horns" that would be different:

var averageHornedAnimalHornLength = animals
    .OfType<IHornedAnimal>()
    .Select(x => x.HornLength)
    .Average();

Note that when using Linq, Average (and Min and Max) will throw an exception if the enumerable is empty and type T is not nullable.  That's because the average really is undefined (0 / 0).  So really you need something like this:

var hornedAnimals = animals
    .OfType<IHornedAnimal>()
    .ToList();
if(hornedAnimals.Count > 0)
{
    var averageHornLengthOfHornedAnimals = hornedAnimals
        .Average(x => x.HornLength);
}
else
{
    // deal with it in your own way...
}

Edit

I just think this needs adding... one of the reasons a question like this doesn't sit well with object-oriented programmers is that it assumes we're using classes and objects to model a data structure.  The original Smalltalk-esque object oriented idea was to structure your program out of modules that were instantiated as objects and performed services for you when you sent them a message.  The fact that we can also use classes and objects to model a data structure is a (useful) side effect, but they're two different things.  I don't even think the latter should be considered object-oriented programming, since you could do the same thing with a struct, but it just wouldn't be as pretty.

If you're using object-oriented programming to create services that do things for you, then querying whether that service is actually some other service or concrete implementation is generally frowned upon for good reasons.  You were given an interface (typically through dependency injection) and you should code to that interface/contract.

On the other hand, if you're (mis-)using the class/object/interface ideas to create a data structure or data model, then I personally don't see a problem with using the is-a idea to its fullest.  If you've defined that unicorns are a sub-type of horses and it totally makes sense within your domain, then absolutely go ahead and query the horses in your herd to find the unicorns.  After all, in a case like this we're typically trying to create a domain specific language to better express the solutions of the problems we have to solve.  In that sense there's nothing wrong with .OfType<Unicorn>() etc.

Ultimately, taking a collection of items and filtering it on type is really just functional programming, not object-oriented programming.  Thankfully languages like C# are comfortable handling both paradigms now.


答:
You've pretty much covered all the options.  If you have behavior that's dependent on a specific subtype, and it's mixed in with other types, your code has to be aware of that subtype; that's simple logical reasoning.

Personally, I'd just go with horses.OfType<Unicorn>().Average(u => u.HornLength).  It expresses the intention of the code very clearly, which is often the most important thing since someone's going to end up having to maintain it later on.

Title: Given a herd of horses, how do I find the average horn length of all unicorns?

Body:
The question above is an abstract example of a common problem I encounter in legacy code, or more accurately, problems resulting from previous attempts at solving this problem.

I can think of at least one .NET framework method that is intended to address this problem, like the Enumerable.OfType<T> method. But the fact that you ultimately end up interrogating an object's type at runtime doesn't sit right with me.

Beyond asking each horse "Are you a unicorn?" the following approaches also come to mind:

Throw an exception when an attempt is made to get the length of a non-unicorn's horn (exposes functionality not appropriate for each horse)

Return a default or magic value for the length of a non-unicorn's horn (requires default checks peppered throughout any code that wants to crunch horn stats on a group of horses that could all be non-unicorns)

Do away with inheritance and create a separate object on a horse that tells you if the horse is a unicorn or not (which is potentially pushing the same problem down a layer)

I have a feeling this is going to be best answered with a "non-answer." But how do you approach this problem and if it depends, what's the context around your decision?

I'd also be interested in any insights on whether this problem still exists in functional code (or maybe it only exists in functional languages that support mutability?)

This was flagged as a possible duplicate of the following question:
How to avoid downcasting?

The answer to that question assumes that one is in possession of a HornMeasurer by which all horn measurements must be made. But that's quite an imposition on a codebase that was formed under the egalitarian principle that everyone should be free to measure the horn of a horse.

Absent a HornMeasurer, the accepted answer's approach mirrors the exception-based approach listed above.

There's also been some confusion in the comments on whether horses and unicorns are both equines, or if a unicorn is a magical subspecies of horse. Both possibilities should be considered--perhaps one is preferable to the other?


问:
Javascript Promise chaining
I recently started working with JS Promises. What I always like to do, is create function, which returns a Promise with the final desired result, but I only do 1 operation/then. Consider something like this (this fetches the versions of an npm package in an array in reverse order):

```<code>function packageVersions(name) {
  return fetchJson(npmUrls.getPackageUrl(name))
    .then(npmPackage => npmPackage.versions)
    .then(versionsObject => Object.keys(versionsObject))
    .then(versions => versions.sort((a, b) => b.localeCompare(a)));
}
</code>```

Like if I was doing a lots of .maps sequentially.

My question would be: is this considered a good practice in general? Could this have significant perfomance drawbacks, if I do a lots of chaining? Do you consider this unreadable in any way?

Would this be better?

```<code>function packageVersions(name) {
  return fetchJson(npmUrls.getPackageUrl(name))
    .then(npmPackage => {
        const versions = Object.keys(npmPackage.versions);
        return versions.sort((a, b) => a.localeCompare(b));
    });
}
</code>```

答:
It potentially could have some performance issues but that probably isn't a big deal.  It would be adding an asynchronous "tick" after each then when in this case it doesn't need to.

The big issue to me is that I would assume at first glance that the promise chain calls asynchronous methods even though it doesn't.

Title: Javascript Promise chaining


问:
Interface design - Parameter choice
Situation:

Is it better to have one or few parameters that supply more than enough information for the intended process or should you have more specific parameters that provide just enough information?

When making parameters more specific, if the process of making them more specific means including business rules/logic or heavy coupling with a very specific class is required should it still be done?

Example:

In the case of an Interface:

```<code>public interface IQuestion
{
    // Specificity in Interface parameters increases Coupling right?
    void MyFunction(IPrincipal user, string destination);

    // Is this any better? It allows me to be more flexible in what I'm doing
    // Inside these functions but it also makes them even more coupled right?
    void MyFunction(ControllerContext context);
}
</code>```

Question:

Are there general rules or cases where it's specifically better to do it one way over the other?

答:
Is it better to have one or few parameters that supply more than
  enough information for the intended process or should you have more
  specific parameters that provide just enough information?

I wanted to kind of echo Telastyn here and suggest there's a balancing act to be had, but focus more on the interface design perspective. In general I'd suggest leaning heavily towards the former whenever you can (with "whenever you can" being based on the confidence in the stability of your designs with respect to how much information they need to receive).

As a caveat, I've worked in frantic environments where, within a couple of months after you release a design to the team, already thousands of lines of code will be using it throughout the codebase, and written by multiple authors. The design is effectively cemented in stone at that stage, and to change it in response to a change in user-end requirements would cause unacceptable cascading changes which would make the rest of the team want to run you over by a coordinated bus. Yet, simultaneously, we were working with clients who always changed their minds and would brainstorm new design ideas in the middle of the process. Some of what I focus on might be overkill outside of environments where interface design so quickly becomes the most unforgiving process.

I'll try to share my mess of thoughts here.

Flexible Parameters

Instead of focusing on coupling so much here, I want to put a spotlight on just the conceptual amount of information we pass through an interface, and also return from an interface.

Do we pass just enough information for a function to do its thing? That would be absolutely ideal, provided you know exactly what the right amount of information is. Do we pass way too much? That could end up making the interface quite difficult to test, possibly couple it to some unstable monolithic type, and potentially obscure side effects.

To me just enough would be absolutely ideal, but there are occasionally times where the message passing involved between interfaces is actually the most difficult part of the interface to stabilize. What the interface should do at the broad level might be obvious and unchanging, exactly how much information it needs to do it might actually change over time.

Flexible Parameters: Regular Expressions

An example I want to use to focus more on "information" than data types is regular expressions. As a note, I hate regular expressions. The syntax gives me a headache, and I always have to look things up there. Nevertheless, it's worth noting the stability of regex interface designs, like so:

```<code>// Search for just about anything you can imagine in a string.
string regex_search(string str, string pattern);
</code>```

It's actually quite incredible to me that even though we've had all kinds of regex standards competing with each other from simple, basic, extended, that this above design can remain stable even if it continues to expand to support new regex standards.

In this case, string pattern is actually modeling a super bundle of information, capable of communicating a practically-infinite amount of information through a variable-sized string. It is largely because of this super bundle of information that this regex_search function, and the callers of the function, can remain stable (unchanging) in spite of evolving and expanding regex standards.

Where this is a bit different is that pattern would be used in full by regex_search, no matter how much information it contains. The entire contents of the string would be relevant for the search, and that's owed due to the ease and flexibility of a string interface to merely add as much information as you need at the site in which the call is made. A string can contain infinite information, but the nature of its interface and representation makes it so it doesn't have to contain more information than necessary.

Nevertheless, this quality is something I've rarely seen mentioned, of flexible parameter types, and it's a noteworthy quality to interface designers seeking greater stability in their designs.

Imagine, instead, if string pattern above was actually IRegEx pattern, with IRegEx modeling SRE (now deprecated), with functions rather than strings to modeling each individual element of a pattern. Such an interface would likely find difficulties remaining stable in the face of new standards, having to decide between outright trying to evolve and grow (possibly becoming a monolithic design with a lot of warts), or new interfaces and possibly deprecation (and therefore a new regex_search_ex kind of function in addition).

This is not a suggestion to reduce the richness of our designs to ones that accept things like strings all over the place. Nevertheless, the stability that results here is a very interesting quality to note. Interface design is always a tightrope balancing act, weighing the pros and cons of one decision over another. It becomes easier if we start to become more aware of the possibilities, and the precise pros and cons of each.

Stability

Typically we don't think so much about interface-level coupling to plain old data types or standard types like string or int. The above regex_search function might be described as "decoupled", completely independent. Yet an obscure way to look at it is that it is still coupled to the interface design of a string. The reason we can generally omit such discussions, and in our dependency diagrams, is simply because string is so incredibly stable. It's unlikely to ever change in design for as long as the language is around, as such a change could potentially break almost all codebases ever written against the language.

As a result, we can often reach for a string parameter here, an int there as parameter types, without worrying about string or int changing and breaking the implementations of both caller and callee.

However, when you reach for a user-defined type like ControllerContext, then stability starts to become a concern. Will ControllerContext's design likely change? If the design changes, would it simply grow and therefore not affect existing dependencies to it, or might there be temptations to change some existing parts of its public interface change in ways that might lead to cascading breakages? It's all a balancing act.

On the flip side, if you use this design:

```<code>void MyFunction(IPrincipal user, string destination);
</code>```

... will you have sufficient information always? Is the design for the existing parts used of IPrincipal going to remain stable?

It's difficult to answer these questions perfectly, and thus design is difficult. It's also not worth asking so much if such designs are not widely-used, in which case we might waste more time trying to too hard to come up with the right design choice upfront when it would have been cheaper to just make a mistake and change the design later without much of a cascade in changes.

Yet a big goal here is stability, always. We don't want to design interfaces that have to change, we don't want to accept parameter types that eventually offer too little information in a way that needs to expand and forces us to change these designs.

Side Effects

One thing to consider is side effects. Are there side effects (changes made) to context here?

```<code>void MyFunction(ControllerContext context);
</code>```

... or will MyFunction simply read from context? If there are side effects involved, these kinds of bundled types tend to be a lot worse, since they don't simply provide more information than the function needs, but they also supply more state than the function will actually modify.

As a result, there can be incredible confusion when passing such bundles as to exactly what the function has modified inside the bundle, and bundled information of this sort can quickly carry far more cons if it is not read-only.

Yet the same kind of concerns carry to user here:

```<code>void MyFunction(IPrincipal user, string destination);
</code>```

Obscure side effects are a very common spawning point for bugs, so we generally want to make side effects clear, and strive to design functions that only cause, at most, one logical side effect. That might affect how you name your functions, document them, and possibly even the parameter types being passed. It's also worth striving for immutability when possible.

If you ever have bundled states that could be split into a read-only part and a mutable part, for example, the split may help a whole lot instead of just mixing "input and output" parameters in one bundle.

Testing

Bundles can make testing more difficult, depending on how easy they are to construct on the fly. Strings are pretty easy to construct on the fly to contain just the right amount of information.

ControllerContext may not be so easy, and its interface might want to expose non-homogeneous data in a way that contains far more functionality than needed just at the interface level.

The ease at which you can construct such bundles on the fly with the necessary information will affect the ease at which you can test your interfaces against a wide range of relevant parameters. An example of where a bundled design might really complicate testing is if it can only be constructed from a config file.

Degeneralizing Bundles

One of the ways to achieve some sense of stability in your design but not veer too far into the danger of passing way more information than needed, and all the cons associated, is to degeneralize your bundles and make them site-specific.

For example, instead of ControllerContext used for IQuestion, maybe you should use QuestionContext which is only used by IQuestion. That mitigates the temptation to bundle way more information than needed.

This is often useful if you want to transfer potential instability elsewhere, if QuestionContext ends up being easier to change than IQuestion. An example is if you need to extend or change the underlying data representation of parameters passed to IQuestion, but not in a way that affects all code written thus far that uses it, only the implementation of QuestionContext itself. In general, a lot of interface design boils down to that. We want to transfer potential instability to places that are easier to change.

ABI and TMI

This might be slightly outside the context of this question, but when ABI (application binary interface) is a concern, too much information (TMI) can be an essential mechanism to reduce the odds of backwards compatibility breakages.

In these cases, interface stability becomes more important than ever before, because an interface change may not simply break compatibility with existing source code, but with existing binaries for products (ex: third party commercial plugins) outside of your team's control.

In such cases, a function like this:

```<code>void (*some_function)(int x, int y);
</code>```

... may very well benefit from having some extra information available to input and output that it doesn't currently benefit from having:

```<code>int (*some_function)(int x, int y, void* unused);
</code>```

It's really ugly but both the return type and unused may save our butts some day in preventing a backwards compatibility ABI change that would have otherwise been necessary, by having shaped all existing client code using some_function to pass in a null for unused which may become a valid, but still optional parameter.

A similar idea might carry for struct used in C, if it's not opaque to the client. Having some unused fields might save the day, some day, and prevent a need for deprecation or breakages. Likewise, some fields formerly used may evolve to become unused.

This kind of practice is most useful when future expansions are towards optional routes, to allow breathing room for new options (options, as in optional) from breaking existing interfaces, widely-used.

Conclusion

So anyway, these are some things to take into consideration when trying to figure out exactly how much information you need when designing the parameters and return types of an interface. The ideal design is always going to be one that just receives and returns exactly the right amount of information required. Yet a less ideal solution which accepts or returns more than required might leave some additional breathing room for changes. Stability is one of the greatest goals, and achieving stability in the face of a world of changing requirements can be very difficult unless we transfer instability elsewhere to places that are easier to change.

Title: Interface design - Parameter choice

Body:
Is it better to have one or few parameters that supply more than
  enough information for the intended process or should you have more
  specific parameters that provide just enough information?

I wanted to kind of echo Telastyn here and suggest there's a balancing act to be had, but focus more on the interface design perspective. In general I'd suggest leaning heavily towards the former whenever you can (with "whenever you can" being based on the confidence in the stability of your designs with respect to how much information they need to receive).

As a caveat, I've worked in frantic environments where, within a couple of months after you release a design to the team, already thousands of lines of code will be using it throughout the codebase, and written by multiple authors. The design is effectively cemented in stone at that stage, and to change it in response to a change in user-end requirements would cause unacceptable cascading changes which would make the rest of the team want to run you over by a coordinated bus. Yet, simultaneously, we were working with clients who always changed their minds and would brainstorm new design ideas in the middle of the process. Some of what I focus on might be overkill outside of environments where interface design so quickly becomes the most unforgiving process.

I'll try to share my mess of thoughts here.

Flexible Parameters

Instead of focusing on coupling so much here, I want to put a spotlight on just the conceptual amount of information we pass through an interface, and also return from an interface.

Do we pass just enough information for a function to do its thing? That would be absolutely ideal, provided you know exactly what the right amount of information is. Do we pass way too much? That could end up making the interface quite difficult to test, possibly couple it to some unstable monolithic type, and potentially obscure side effects.

To me just enough would be absolutely ideal, but there are occasionally times where the message passing involved between interfaces is actually the most difficult part of the interface to stabilize. What the interface should do at the broad level might be obvious and unchanging, exactly how much information it needs to do it might actually change over time.

Flexible Parameters: Regular Expressions

An example I want to use to focus more on "information" than data types is regular expressions. As a note, I hate regular expressions. The syntax gives me a headache, and I always have to look things up there. Nevertheless, it's worth noting the stability of regex interface designs, like so:

// Search for just about anything you can imagine in a string.
string regex_search(string str, string pattern);

It's actually quite incredible to me that even though we've had all kinds of regex standards competing with each other from simple, basic, extended, that this above design can remain stable even if it continues to expand to support new regex standards.

In this case, string pattern is actually modeling a super bundle of information, capable of communicating a practically-infinite amount of information through a variable-sized string. It is largely because of this super bundle of information that this regex_search function, and the callers of the function, can remain stable (unchanging) in spite of evolving and expanding regex standards.

Where this is a bit different is that pattern would be used in full by regex_search, no matter how much information it contains. The entire contents of the string would be relevant for the search, and that's owed due to the ease and flexibility of a string interface to merely add as much information as you need at the site in which the call is made. A string can contain infinite information, but the nature of its interface and representation makes it so it doesn't have to contain more information than necessary.

Nevertheless, this quality is something I've rarely seen mentioned, of flexible parameter types, and it's a noteworthy quality to interface designers seeking greater stability in their designs.

Imagine, instead, if string pattern above was actually IRegEx pattern, with IRegEx modeling SRE (now deprecated), with functions rather than strings to modeling each individual element of a pattern. Such an interface would likely find difficulties remaining stable in the face of new standards, having to decide between outright trying to evolve and grow (possibly becoming a monolithic design with a lot of warts), or new interfaces and possibly deprecation (and therefore a new regex_search_ex kind of function in addition).

This is not a suggestion to reduce the richness of our designs to ones that accept things like strings all over the place. Nevertheless, the stability that results here is a very interesting quality to note. Interface design is always a tightrope balancing act, weighing the pros and cons of one decision over another. It becomes easier if we start to become more aware of the possibilities, and the precise pros and cons of each.

Stability

Typically we don't think so much about interface-level coupling to plain old data types or standard types like string or int. The above regex_search function might be described as "decoupled", completely independent. Yet an obscure way to look at it is that it is still coupled to the interface design of a string. The reason we can generally omit such discussions, and in our dependency diagrams, is simply because string is so incredibly stable. It's unlikely to ever change in design for as long as the language is around, as such a change could potentially break almost all codebases ever written against the language.

As a result, we can often reach for a string parameter here, an int there as parameter types, without worrying about string or int changing and breaking the implementations of both caller and callee.

However, when you reach for a user-defined type like ControllerContext, then stability starts to become a concern. Will ControllerContext's design likely change? If the design changes, would it simply grow and therefore not affect existing dependencies to it, or might there be temptations to change some existing parts of its public interface change in ways that might lead to cascading breakages? It's all a balancing act.

On the flip side, if you use this design:

void MyFunction(IPrincipal user, string destination);

... will you have sufficient information always? Is the design for the existing parts used of IPrincipal going to remain stable?

It's difficult to answer these questions perfectly, and thus design is difficult. It's also not worth asking so much if such designs are not widely-used, in which case we might waste more time trying to too hard to come up with the right design choice upfront when it would have been cheaper to just make a mistake and change the design later without much of a cascade in changes.

Yet a big goal here is stability, always. We don't want to design interfaces that have to change, we don't want to accept parameter types that eventually offer too little information in a way that needs to expand and forces us to change these designs.

Side Effects

One thing to consider is side effects. Are there side effects (changes made) to context here?

void MyFunction(ControllerContext context);

... or will MyFunction simply read from context? If there are side effects involved, these kinds of bundled types tend to be a lot worse, since they don't simply provide more information than the function needs, but they also supply more state than the function will actually modify.

As a result, there can be incredible confusion when passing such bundles as to exactly what the function has modified inside the bundle, and bundled information of this sort can quickly carry far more cons if it is not read-only.

Yet the same kind of concerns carry to user here:

void MyFunction(IPrincipal user, string destination);

Obscure side effects are a very common spawning point for bugs, so we generally want to make side effects clear, and strive to design functions that only cause, at most, one logical side effect. That might affect how you name your functions, document them, and possibly even the parameter types being passed. It's also worth striving for immutability when possible.

If you ever have bundled states that could be split into a read-only part and a mutable part, for example, the split may help a whole lot instead of just mixing "input and output" parameters in one bundle.

Testing

Bundles can make testing more difficult, depending on how easy they are to construct on the fly. Strings are pretty easy to construct on the fly to contain just the right amount of information.

ControllerContext may not be so easy, and its interface might want to expose non-homogeneous data in a way that contains far more functionality than needed just at the interface level.

The ease at which you can construct such bundles on the fly with the necessary information will affect the ease at which you can test your interfaces against a wide range of relevant parameters. An example of where a bundled design might really complicate testing is if it can only be constructed from a config file.

Degeneralizing Bundles

One of the ways to achieve some sense of stability in your design but not veer too far into the danger of passing way more information than needed, and all the cons associated, is to degeneralize your bundles and make them site-specific.

For example, instead of ControllerContext used for IQuestion, maybe you should use QuestionContext which is only used by IQuestion. That mitigates the temptation to bundle way more information than needed.

This is often useful if you want to transfer potential instability elsewhere, if QuestionContext ends up being easier to change than IQuestion. An example is if you need to extend or change the underlying data representation of parameters passed to IQuestion, but not in a way that affects all code written thus far that uses it, only the implementation of QuestionContext itself. In general, a lot of interface design boils down to that. We want to transfer potential instability to places that are easier to change.

ABI and TMI

This might be slightly outside the context of this question, but when ABI (application binary interface) is a concern, too much information (TMI) can be an essential mechanism to reduce the odds of backwards compatibility breakages.

In these cases, interface stability becomes more important than ever before, because an interface change may not simply break compatibility with existing source code, but with existing binaries for products (ex: third party commercial plugins) outside of your team's control.

In such cases, a function like this:

void (*some_function)(int x, int y);

... may very well benefit from having some extra information available to input and output that it doesn't currently benefit from having:

int (*some_function)(int x, int y, void* unused);

It's really ugly but both the return type and unused may save our butts some day in preventing a backwards compatibility ABI change that would have otherwise been necessary, by having shaped all existing client code using some_function to pass in a null for unused which may become a valid, but still optional parameter.

A similar idea might carry for struct used in C, if it's not opaque to the client. Having some unused fields might save the day, some day, and prevent a need for deprecation or breakages. Likewise, some fields formerly used may evolve to become unused.

This kind of practice is most useful when future expansions are towards optional routes, to allow breathing room for new options (options, as in optional) from breaking existing interfaces, widely-used.

Conclusion

So anyway, these are some things to take into consideration when trying to figure out exactly how much information you need when designing the parameters and return types of an interface. The ideal design is always going to be one that just receives and returns exactly the right amount of information required. Yet a less ideal solution which accepts or returns more than required might leave some additional breathing room for changes. Stability is one of the greatest goals, and achieving stability in the face of a world of changing requirements can be very difficult unless we transfer instability elsewhere to places that are easier to change.


问:
What is the use case for shadowing variables?
One of the things the coffeescript programming language is criticized for is its treatment of variable declarations and scope (example).

The answers to this question (and the blog I linked to above) seem to hinge on the false dichotomy of variables either being able to be shadowed or else be global. In any language with reasonable scoping rules, this conceit seems (to me) to be a non-sequiter. In the aforementioned coffeescript:

```<code>foo = 5
f = () ->
  foo = 12 #foo in the outer scope is closed-over
  bar = 3  #binds a name in f's scope
  null

f()
foo #12
bar #undefined because it was bound in an inner scope
</code>```

So clearly, bar is not global. If the snippet above was itself inside a non-global scope then foo would not be either. It seems to me that shadowing a variable from an outer scope in a language with lexical closure could only possibly create confusion. So why does coffeescript get slammed for removing the possibility? Is there an important use case here I'm missing? Regardless of how one may feel about the rest of coffeescript, this behavior seems desirable to me.

答:
The issue with the way you describe it (I don't know coffeescript myself) is that it makes it too easy to break existing code without realizing it.  Let's say you have this code:

```<code>bar = 5
// 100 lines of code
f = () ->
    foo = 12
    null

// 100 lines of code
print bar
</code>```

Now you decide that "bar" is a lousy name and you rename the global to "foo".  Suddenly all hell breaks loose. Maybe you don't even notice right away, it slips through your tests and hits production.

Now consider other strategies:

Shadowing (C/C++/others) Have locals shadow globals.  In this case, the code just runs as is.  foo in the local scope does not affect the global scope, so everything works as before.

Disallow (C#) The compiler tells you not to do that.  You change the name of one or the other and everything is fine.

Shadow or make explicit  (Python) Have locals shadow globals, but let developers make the use of the global explicitly.  Again, everything just works as before.

A related use case, for which these same comments apply, is if you pull and existing function, either just copying the code or using some include method, where a local happens to use the name of a global in the new file.

Body:
The issue with the way you describe it (I don't know coffeescript myself) is that it makes it too easy to break existing code without realizing it.  Let's say you have this code:

bar = 5
// 100 lines of code
f = () ->
    foo = 12
    null

// 100 lines of code
print bar

Now you decide that "bar" is a lousy name and you rename the global to "foo".  Suddenly all hell breaks loose. Maybe you don't even notice right away, it slips through your tests and hits production.

Now consider other strategies:

Shadowing (C/C++/others) Have locals shadow globals.  In this case, the code just runs as is.  foo in the local scope does not affect the global scope, so everything works as before.

Disallow (C#) The compiler tells you not to do that.  You change the name of one or the other and everything is fine.

Shadow or make explicit  (Python) Have locals shadow globals, but let developers make the use of the global explicitly.  Again, everything just works as before.

A related use case, for which these same comments apply, is if you pull and existing function, either just copying the code or using some include method, where a local happens to use the name of a global in the new file.


问:
Does this class design violate the single responsibility principle?
Today I had an argument with someone.

I was explaining the benefits of having a rich domain model as opposed to an anemic domain model. And I demoed my point with a simple class looking like that:

```<code>public class Employee
{
    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastname;
    }

    public string FirstName { get private set; }
    public string LastName { get; private set;}
    public int CountPaidDaysOffGranted { get; private set;}

    public void AddPaidDaysOffGranted(int numberOfdays)
    {
        // Do stuff
    }
}
</code>```

As he defended his anemic model approach, one of his arguments was: "I am a believer in SOLID. You are violating the single responsibility principle (SRP) as you are both representing data and performing logic in the same class."

I found this claim really surprising, as following this reasoning, any class having one property and one method violates the SRP, and therefore OOP in general is not SOLID, and functional programming is the only way to heaven.

I decided not to reply to his many arguments, but I am curious what the community thinks on this question.

If I had replied, I would have started by pointing to the paradox mentioned above, and then indicate that the SRP is highly dependent on the level of granularity you want to consider and that if you take it far enough, any class containing more than one property or one method violates it.

What would you have said?

Update: The example has been generously updated by guntbert to make the method more realistic and help us focus on the underlying discussion.

答:
Single Responsibility Principle is only concerned with whether or not a piece of code (in OOP, typically we're talking about classes) has responsibility over one piece of functionality.  I think your friend saying that functions and data can't co-mingle didn't really understand that idea.  If Employee were to also contain information about his workplace, how fast his car goes, and what type of food his dog eats then we'd have a problem.

Since this class deals only with an Employee, I think it's fair to say it doesn't violate SRP blatantly, but people are always going to have their own opinions.

One place where we might improve is to separate Employee information (like name, phone number, email) from his vacation.  In my mind, this doesn't mean that methods and data cannot co-mingle, it just means that perhaps the vacation functionality could be in a separate place.


答:
Single Responsibility should be understood as an abstraction of logical tasks in your system.  A class should have the single responsibility to (do everything necessary in order to) perform one single, specific task.  This can actually bring a lot into a well-designed class, depending on what the responsibility is.  The class that runs your script engine, for example, can have a lot of methods and data involved in processing scripts.

Your coworker is focusing on the wrong thing.  The question is not "what members does this class have?" but "what useful operation(s) does this class perform within the program?"  Once that is understood, your domain model looks just fine.

Title: Does this class design violate the single responsibility principle?

Body:
Today I had an argument with someone.

I was explaining the benefits of having a rich domain model as opposed to an anemic domain model. And I demoed my point with a simple class looking like that:

```<code>public class Employee
{
    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastname;
    }

    public string FirstName { get private set; }
    public string LastName { get; private set;}
    public int CountPaidDaysOffGranted { get; private set;}

    public void AddPaidDaysOffGranted(int numberOfdays)
    {
        // Do stuff
    }
}
</code>```

As he defended his anemic model approach, one of his arguments was: "I am a believer in SOLID. You are violating the single responsibility principle (SRP) as you are both representing data and performing logic in the same class."

I found this claim really surprising, as following this reasoning, any class having one property and one method violates the SRP, and therefore OOP in general is not SOLID, and functional programming is the only way to heaven.

I decided not to reply to his many arguments, but I am curious what the community thinks on this question.

If I had replied, I would have started by pointing to the paradox mentioned above, and then indicate that the SRP is highly dependent on the level of granularity you want to consider and that if you take it far enough, any class containing more than one property or one method violates it.

What would you have said?

Update: The example has been generously updated by guntbert to make the method more realistic and help us focus on the underlying discussion.


答:
To my mind this class could potentially violate SRP if it continued to represent both an Employee and EmployeeHolidays.

As it is, and if it came to me for Peer Review, I'd probably let it through. If more Employee specific properties and methods were added, and more holiday specific properties were added I would probably advise a split, citing both SRP and ISP.


答:
Assuming you want to treat a Unicorn as a special kind of Horse, there are basically two ways you can model it.  The more traditional way is the subclass relationship.  You can avoid checking the type and downcasting by simply refactoring your code to always keep the lists separate in the contexts where it matters, and only combine them in the contexts where you never care about Unicorn traits.  In other words, you arrange it so you never get into the situation where you need to extract unicorns from a herd of horses in the first place.  This seems difficult at first, but is possible in 99.99% of cases, and usually actually makes your code a lot cleaner.

The other way you might model a unicorn is just by giving all horses an optional horn length.  Then you could test if it's a unicorn by checking if it has a horn length, and find the average horn length of all the unicorns by (in Scala):

```<code>case class Horse(val hornLength: Option[Double])

val horse = Horse(None)
val unicorn = Horse(Some(12.0))
val anotherUnicorn = Horse(Some(6.0))

val herd = List(horse, unicorn, anotherUnicorn)
val hornLengths = herd flatMap {_.hornLength}
val averageLength = hornLengths.sum / hornLengths.size
</code>```

This method has the advantage of being more straightforward, with a single class, but the disadvantage of being much less extensible, and having sort of a roundabout way of checking for "unicornness."  The trick if you go with this solution is to recognize when you start to extend it often that you need to move to a more flexible architecture.  This kind of solution is much more popular in functional languages where you have simple and powerful functions like flatMap to easily filter out the None items.

Body:
Assuming you want to treat a Unicorn as a special kind of Horse, there are basically two ways you can model it.  The more traditional way is the subclass relationship.  You can avoid checking the type and downcasting by simply refactoring your code to always keep the lists separate in the contexts where it matters, and only combine them in the contexts where you never care about Unicorn traits.  In other words, you arrange it so you never get into the situation where you need to extract unicorns from a herd of horses in the first place.  This seems difficult at first, but is possible in 99.99% of cases, and usually actually makes your code a lot cleaner.

The other way you might model a unicorn is just by giving all horses an optional horn length.  Then you could test if it's a unicorn by checking if it has a horn length, and find the average horn length of all the unicorns by (in Scala):

case class Horse(val hornLength: Option[Double])

val horse = Horse(None)
val unicorn = Horse(Some(12.0))
val anotherUnicorn = Horse(Some(6.0))

val herd = List(horse, unicorn, anotherUnicorn)
val hornLengths = herd flatMap {_.hornLength}
val averageLength = hornLengths.sum / hornLengths.size

This method has the advantage of being more straightforward, with a single class, but the disadvantage of being much less extensible, and having sort of a roundabout way of checking for "unicornness."  The trick if you go with this solution is to recognize when you start to extend it often that you need to move to a more flexible architecture.  This kind of solution is much more popular in functional languages where you have simple and powerful functions like flatMap to easily filter out the None items.


答:
The backlash towards CoffeeScript specifically is likely because CoffeeScript is supposed to be a language that is similar to Javascript; it is advertised as a variation or extension of Javascript. The homepage even says:

The golden rule of CoffeeScript is: "It's just JavaScript".

Javascript developers might be hesitant to try CoffeeScript when the foundational implicit behavior that they have grown accustomed to has been changed.

Title: What is the use case for shadowing variables?

Body:
One of the things the coffeescript programming language is criticized for is its treatment of variable declarations and scope (example).

The answers to this question (and the blog I linked to above) seem to hinge on the false dichotomy of variables either being able to be shadowed or else be global. In any language with reasonable scoping rules, this conceit seems (to me) to be a non-sequiter. In the aforementioned coffeescript:

```<code>foo = 5
f = () ->
  foo = 12 #foo in the outer scope is closed-over
  bar = 3  #binds a name in f's scope
  null

f()
foo #12
bar #undefined because it was bound in an inner scope
</code>```

So clearly, bar is not global. If the snippet above was itself inside a non-global scope then foo would not be either. It seems to me that shadowing a variable from an outer scope in a language with lexical closure could only possibly create confusion. So why does coffeescript get slammed for removing the possibility? Is there an important use case here I'm missing? Regardless of how one may feel about the rest of coffeescript, this behavior seems desirable to me.


问:
Handling interface segregation in C++
I'm designing a "view" handling system for a game. The goal is to be able to have different "views" that can be shown in sequence or stacked on-top of each other. For example, the initial splash screen is one View and the main menu that follows the splash screen is also a View which is rendered when the splash screen terminates. The camera view of the game world is also a View and the HUD is a View that is rendered on top of the game View.

While defining the interface for View I realize that the stacked nature of Views corresponds to the input focus priority. I.e. the View that's at the top of the stack should be offered to act on any user input before any other Views because in essence it is in the "foreground" for focus.

So the design of the interface for View looks like this at the moment:

```<code>/**
 * Interface for a "view". A view is a renderable target that can accept user input.
 *
 * One can think of it as a "layer", many layers can be drawn over each other in a
 * stack like fashion where the input focus travels from the top to the bottom of
 * the stack.
 */
class IView{
public:
    virtual ~IView() {}

    IView(const IView&) = delete; // Not allowed
    void operator = (const IView&) = delete; // Not allowed

    /**
     * Called to handle user keyboard input. May be called multiple times per update.
     * @param aKeyEvent The type of input event.
     * @param aKeyCode The key code of the event key.
     * @param aKeyboardState The current state of they keyboard.
     * @return True if the event was handled. False if the event should continue to lower views.
     */
    virtual bool handleInput(KeyEvent aKeyEvent, KeyCode aKeyCode, const KeyboardState& aKeyboardState) = 0;

    /**
     * Called to handle user mouse clicks. May be called multiple times per update.
     * @param aMouseButtonEvent The event to handle.
     * @param aMouseButton Which button it was.
     * @param aMouseState The current mouse state.
     * @return True if the event was handled. False if the event should continue to lower views.
     */
    virtual bool handleInput(MouseButtonEvent aMouseButtonEvent, MouseButton aMouseButton,
                             const MouseState& aMouseState) = 0;

    /**
     * Called to handle user mouse movement. Only called once per update.
     * @param aMouseEvent The event to handle.
     * @param aMouseState
     * @return True if the event was handled. False if the event should continue to lower views.
     */
    virtual bool handleInput(MouseMoveEvent aMouseMoveEvent, const MouseState& aMouseState) = 0;

    /**
     * Called when this view becomes the foreground view.
     */
    virtual void foreground() = 0;

    /**
     * Called when this view loses its foreground status and
     * has another view drawn over it.
     */
    virtual void background() = 0;

    /**
     * Called once every frame to perform periodic processing and rendering.
     */
    virtual void update() = 0;
};
</code>```

This isn't the final interface, I'm just prototyping at the moment. But it gives you an idea.

Consider a game View, with a HUD on top, and then the game is paused so a pause View is rendered on top of the HUD. The pause View is offered first chance to act on user input to continue the game and it swallows all other input. To me this makes perfect sense.

Now, not all Views are necessarily interested in receiving input. Some might only be interested in mouse events and some might only be interested in keyboard events. My initial approach was to just let them have pass-through input handlers. But then I remembered the Interface Segregation Principle so it would make sense to define two more interfaces IKeyboardHandler and IMouseHandler and let the relevant View classes implement those when needed. But then I need to use dynamic_cast when passing input to the View objects to see if a particular View implements for example IKeyboardHandler.

I'm not sure if this approach is any more elegant than having empty input handlers and I'm looking for input and ideas on the design.

答:
The interface segregation principle is focused more on completely irrelevant functionality. Here it's not so clear cut.

A blatant example of a violation of ISP is a Scrollbar interface with a setText function inherited from Widget, when a scrollbar won't even show any text. In such a case, the function may even be documented as irrelevant to callers, and to attempt to call such a function on a scrollbar may indicate a logical error.

Such blatant violations of ISP tend to be most foul, with monolithic interfaces that might have 200 functions with only 20 of them being relevant for the actual object in question. I see it often in GUI designs which are based around massive inheritance hierarchies, and often with documentation mechanisms trying to filter out the enormous amount of irrelevant derived functionality.

In your case, I think it's a bit different since given a function like this:

```<code>virtual bool handleInput(KeyEvent aKeyEvent, ...) = 0;
</code>```

... it's still relevant to clients whether or not a view handles keyboard input. The fact that it doesn't is still relevant information, and worth calling the function to find out. So I don't see this as a clear violation of ISP.

You could try to split up the interface into multiple interfaces like IKeyboardHandler, but it's likely to make things harder rather than easier. It's worth noting the scope here in terms of dependencies.

A game will typically only have a handful of such views. You might have a main menu screen of sorts, splash screen, HUD, game view, maybe an in-game pie menu or something. It's a handful of views. The clients will also tend to be few in number, maybe just one broad client which is the one handling events from the operating system and calling the relevant view functions. So it's very limited in scope/scale when it comes to the number of dependencies, and that's a sign that you don't need to try too hard to come up with a great engineering solution, and that doing so may very well contradict your goals for ease of maintenance (ease of change).

Avoiding the Dynamic Cast

That said, just for completeness, I'll show you a simple way to avoid the cast in these kinds of scenarios. You can do this:

```<code>class IView{
public:
    ...

    // Returns null if keyboard handling is unsupported.
    virtual IKeyboardHandler* keyboard() = 0;

    // Returns null if mouse handling is unsupported.
    virtual IMouseHandler* mouse() = 0;
};
</code>```

... view types that don't need inherit from (implement) IKeyboardHandler can simply return null, e.g. Ones that do can simply return this;. This way you can find out if a view supports keyboard handling with an interface query which doesn't involve casting, and if so, handle keyboard input for that view.

Taking this technique further to a greater degree of flexibility will often have you approaching COM-style designs (which does involve casting but hides it from the client), and even further, entity-component systems (which can be very useful to know about as a game developer, but probably outside of this view context). Yet I think this is absolute overkill for your case even with the basic form, and likely to just add more burdens upfront without alleviating any later.

Yet this basic version shown above can be a useful design technique if you had, say, functions in your system which can work strictly with IKeyboardHandler, and you potentially have things other than views which might implement this keyboard handling interface.

Title: Handling interface segregation in C++

Body:
The interface segregation principle is focused more on completely irrelevant functionality. Here it's not so clear cut.

A blatant example of a violation of ISP is a Scrollbar interface with a setText function inherited from Widget, when a scrollbar won't even show any text. In such a case, the function may even be documented as irrelevant to callers, and to attempt to call such a function on a scrollbar may indicate a logical error.

Such blatant violations of ISP tend to be most foul, with monolithic interfaces that might have 200 functions with only 20 of them being relevant for the actual object in question. I see it often in GUI designs which are based around massive inheritance hierarchies, and often with documentation mechanisms trying to filter out the enormous amount of irrelevant derived functionality.

In your case, I think it's a bit different since given a function like this:

virtual bool handleInput(KeyEvent aKeyEvent, ...) = 0;

... it's still relevant to clients whether or not a view handles keyboard input. The fact that it doesn't is still relevant information, and worth calling the function to find out. So I don't see this as a clear violation of ISP.

You could try to split up the interface into multiple interfaces like IKeyboardHandler, but it's likely to make things harder rather than easier. It's worth noting the scope here in terms of dependencies.

A game will typically only have a handful of such views. You might have a main menu screen of sorts, splash screen, HUD, game view, maybe an in-game pie menu or something. It's a handful of views. The clients will also tend to be few in number, maybe just one broad client which is the one handling events from the operating system and calling the relevant view functions. So it's very limited in scope/scale when it comes to the number of dependencies, and that's a sign that you don't need to try too hard to come up with a great engineering solution, and that doing so may very well contradict your goals for ease of maintenance (ease of change).

Avoiding the Dynamic Cast

That said, just for completeness, I'll show you a simple way to avoid the cast in these kinds of scenarios. You can do this:

class IView{
public:
    ...

    // Returns null if keyboard handling is unsupported.
    virtual IKeyboardHandler* keyboard() = 0;

    // Returns null if mouse handling is unsupported.
    virtual IMouseHandler* mouse() = 0;
};

... view types that don't need inherit from (implement) IKeyboardHandler can simply return null, e.g. Ones that do can simply return this;. This way you can find out if a view supports keyboard handling with an interface query which doesn't involve casting, and if so, handle keyboard input for that view.

Taking this technique further to a greater degree of flexibility will often have you approaching COM-style designs (which does involve casting but hides it from the client), and even further, entity-component systems (which can be very useful to know about as a game developer, but probably outside of this view context). Yet I think this is absolute overkill for your case even with the basic form, and likely to just add more burdens upfront without alleviating any later.

Yet this basic version shown above can be a useful design technique if you had, say, functions in your system which can work strictly with IKeyboardHandler, and you potentially have things other than views which might implement this keyboard handling interface.


问:
Why was conversion between Instant and Date named the way it was?
When Instant was introduced with JSR-310, convenience methods were added to perform conversion between Date and Instant:

```<code>Date input = new Date();
Instant instant = input.toInstant();
Date output = Date.from(instant);
</code>```

I wonder why it was chosen to be this way instead of, let's say, having Date output = instant.toDate(). My guess is that it was intended to avoid making Instant dependent on Date. Is this right?

But to me it is somehow strange that you make the new class independent of the already existing one, and make the old one dependent on the newly introduce one. Is this made so because of an expected deprecation of Date or is there any other reason?

答:
Problems with Date:

It is a mutable object

It is not thread-safe

cost of using it in a thread-safe manner (synchronized) is expensive

Instant on the other hand is designed to be thread-safe and immutable. Making the object Immutable is by itself already a simple and inexpensive way of guaranteeing thread-safety. The Javadoc for Instant states:

Implementation Requirements:

  This class is immutable and thread-safe.

Now if you want to do something like Instant t = Instant.from(new Date()), that means the implementers of the API would have to introduce synchronization to guarantee the thread-safe access of the Date object.

I suspect that they wanted to simply have a clean break with the old ways, and avoid introducing any explicit synchronized methods. Introducing synchronized methods would have suggested that it is ok to use them. While it might be useful to have, it would be setting a bad precedent.

Instead they have chosen to keep the conversion of Date to Instant within the Date API, which does not document any thread-safety. Safe assumption would be that it is up to the user to synchronize access to the Date Object first if required to do so.


答: A method GetUnicorns() that returns an IEnumerable seems the most elegant, flexible and universal solution to me. This way you could deal with any (combination of) traits that determine whether a horse will pass as a unicorn, not just class type or the value of a particular property.</p>


问:
Joda Time vs Java Time
Although Joda is feature rich and more sophisticated than standard Java time, it may not always be the best thing to use. How do I decide if I should use Joda Time or Java Time in any Java code?

Is there some kind of guideline which tells us how to pick the right one depending on our requirements?

答:
Note that on the Joda-Time website it states:

The standard date and time classes prior to Java SE 8 are poor. By tackling this problem head-on, Joda-Time has become the de facto standard date and time library for Java. Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).

The main contributor to Joda-Time, jodastephen, is also the main contributor for JSR-310, as can be seen on the GitHub repository associated with http://www.threeten.org/. By the way, jodastephen has also a SO handle ...

I think it is safe to state that we can feel comforted and safe with the new Date and Time API as provided in Java 8 onward.

Some additional references:

Official JCP-310 webpage

Joda-Time

Three-Ten

java.time.* Javadoc

Date Javadoc

Title: Joda Time vs Java Time


答:
I don't find it useful these days to debate about what does and doesn't constitute a single responsibility or a single reason to change. I would propose a Minimum Grief Principle in its place:

Minimum Grief Principle: code should either seek to minimize its probability of requiring changes or maximize the ease of being changed.

How's that? Shouldn't take a rocket scientist to figure out why this can help reduce maintenance costs and hopefully it shouldn't be a point of endless debate, but as with SOLID in general, it's not something to apply blindly everywhere. It's something to consider while balancing trade-offs.

As for the probability of requiring changes, that goes down with:

Good testing (improved reliability).

Involving only the bare minimum code required to do something specific (this can include reducing afferent couplings).

Just making the code badass at what it does (see Make Badass Principle).

As for the difficulty of making changes, it goes up with efferent couplings. Testing introduces efferent couplings but it improves reliability. Done well, it generally does more good than harm and is totally acceptable and promoted by the Minimum Grief Principle.

Make Badass Principle: classes that are used in many places should be awesome. They should be reliable, efficient if that ties to their quality, etc.

And the Make Badass Principle is tied to Minimum Grief Principle, since badass things will find a lower probability of requiring changes than things which suck at what they do.

I would have started by pointing to the paradox mentioned above, and
  then indicate that the SRP is highly dependent on the level of
  granularity you want to consider and that if you take it far enough,
  any class containing more than one property or one method violates it.

From an SRP standpoint a class which barely does anything would certainly have only one (sometimes zero) reasons to change:

```<code>class Float
{
public:
    explicit Float(float val);
    float get() const;
    void set(float new_val);
};
</code>```

That practically has no reasons to change! It's better than SRP. It's ZRP!

Except I would suggest it is in blatant violation of the Make Badass Principle. It's also absolutely worthless. Something which does so little cannot hope to be badass. It has too little information (TLI). And naturally when you have something which is TLI, it cannot do anything really meaningful, not even with the information it encapsulates, so it has to leak it to the outside world in hopes that someone else will actually do something meaningful and badass. And that leakiness is okay for something which is just meant to aggregate data and nothing more, but that threshold is the difference as I see between "data" and "objects".

Of course something which is TMI is bad as well. We might put our entire software in one class. It can even just have one run method. And someone might even argue that it now has one very broad reason to change: "This class will only need to be changed if the software needs improvement." I'm being silly, but of course we can imagine all the maintenance issues with that.

So there's a balancing act as to the granularity or coarseness of the objects you design. I often judge it by how much information you have to leak to the outside world, and how much meaningful functionality it can perform. I often find the Make Badass Principle helpful there to find the balance while combining it with the Minimum Grief Principle.

Body:
I don't find it useful these days to debate about what does and doesn't constitute a single responsibility or a single reason to change. I would propose a Minimum Grief Principle in its place:

Minimum Grief Principle: code should either seek to minimize its probability of requiring changes or maximize the ease of being changed.

How's that? Shouldn't take a rocket scientist to figure out why this can help reduce maintenance costs and hopefully it shouldn't be a point of endless debate, but as with SOLID in general, it's not something to apply blindly everywhere. It's something to consider while balancing trade-offs.

As for the probability of requiring changes, that goes down with:

Good testing (improved reliability).

Involving only the bare minimum code required to do something specific (this can include reducing afferent couplings).

Just making the code badass at what it does (see Make Badass Principle).

As for the difficulty of making changes, it goes up with efferent couplings. Testing introduces efferent couplings but it improves reliability. Done well, it generally does more good than harm and is totally acceptable and promoted by the Minimum Grief Principle.

Make Badass Principle: classes that are used in many places should be awesome. They should be reliable, efficient if that ties to their quality, etc.

And the Make Badass Principle is tied to Minimum Grief Principle, since badass things will find a lower probability of requiring changes than things which suck at what they do.

I would have started by pointing to the paradox mentioned above, and
  then indicate that the SRP is highly dependent on the level of
  granularity you want to consider and that if you take it far enough,
  any class containing more than one property or one method violates it.

From an SRP standpoint a class which barely does anything would certainly have only one (sometimes zero) reasons to change:

class Float
{
public:
    explicit Float(float val);
    float get() const;
    void set(float new_val);
};

That practically has no reasons to change! It's better than SRP. It's ZRP!

Except I would suggest it is in blatant violation of the Make Badass Principle. It's also absolutely worthless. Something which does so little cannot hope to be badass. It has too little information (TLI). And naturally when you have something which is TLI, it cannot do anything really meaningful, not even with the information it encapsulates, so it has to leak it to the outside world in hopes that someone else will actually do something meaningful and badass. And that leakiness is okay for something which is just meant to aggregate data and nothing more, but that threshold is the difference as I see between "data" and "objects".

Of course something which is TMI is bad as well. We might put our entire software in one class. It can even just have one run method. And someone might even argue that it now has one very broad reason to change: "This class will only need to be changed if the software needs improvement." I'm being silly, but of course we can imagine all the maintenance issues with that.

So there's a balancing act as to the granularity or coarseness of the objects you design. I often judge it by how much information you have to leak to the outside world, and how much meaningful functionality it can perform. I often find the Make Badass Principle helpful there to find the balance while combining it with the Minimum Grief Principle.


问:
Exception Handling for class attributes in setters and constructors
I would like to discuss a question about best practices regarding exception handling (e.g. in Java). Normally, when setting the attributes of a class,  I check the arguments in the setters for validity, and if the arguments are not valid, I throw an IllegalArgumentException.

Besides the setters, sometimes also the constructor of the class allows to set some values for the attributes. So I also have to check the arguments in the constructor for validity. This, however, would lead to duplicate code. I can only think of one solution for this problem: Instead of directly setting the value of the attribute in the constructor, I call the setter, which then also validates the given value.

However, as the setters are public, this has the problem that I would call an overrideable method from within the constructor, which is bad. To solve this problem again, I could make the setters final, but this I have never seen.

Another possibility I could think of, theoretically,  is to have a private or many private methods which check the arguments for validity and which are called by both the constructors and setters. But this would lead to even more code. What do you think are the best practices for this problem?

答:
To solve this problem again, I could make the setters final, but this I have never seen.

I think that this is the appropriate solution.

I regret that you've never seen that before because I think that setters almost always should be declared final. Can you think of a good reason to override a setter in a derived class? What's the purpose of a setter? It assigns a value to a (hopefully private) attribute, possibly after verifying the new value. What useful could it be to override this? I cannot think of any situation where overriding the setter would be anything else but very poor code. So, yes, go ahead, make them final.


答:
Great question, your hunch that you shouldn't set the setter methods as final or private is correct. You should allow child classes to override these as necessary.

Best practice is to call the setter methods in the constructor.

If other classes extend the class and override the setter methods with their own validations, the parent constructor will call the child's setter methods as long as the object is instantiated as the child class.

Title: Exception Handling for class attributes in setters and constructors

Body:
I would like to discuss a question about best practices regarding exception handling (e.g. in Java). Normally, when setting the attributes of a class,  I check the arguments in the setters for validity, and if the arguments are not valid, I throw an IllegalArgumentException.

Besides the setters, sometimes also the constructor of the class allows to set some values for the attributes. So I also have to check the arguments in the constructor for validity. This, however, would lead to duplicate code. I can only think of one solution for this problem: Instead of directly setting the value of the attribute in the constructor, I call the setter, which then also validates the given value.

However, as the setters are public, this has the problem that I would call an overrideable method from within the constructor, which is bad. To solve this problem again, I could make the setters final, but this I have never seen.

Another possibility I could think of, theoretically,  is to have a private or many private methods which check the arguments for validity and which are called by both the constructors and setters. But this would lead to even more code. What do you think are the best practices for this problem?


问:
Object Oriented Design
Suppose you have the following:

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+------+     +----+-+
       ^                 ^
       |                 |
       |                 |
  +------+              +-------+
  | Deer |              | Grass |
  +------+              +-------+
</code>```

Deer inherits from Animal, and Grass inherits from Food.

So far so good. Animal objects can eat Food objects.

Now lets mix it up a bit. Lets add a Lion which inherits from Animal.

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+-----++     +----+-+
       ^     ^           ^
       |     |           |
       |     |           |
  +------+ +------+     +-------+
  | Deer | | Lion |     | Grass |
  +------+ +------+     +-------+
</code>```

Now we have have a problem because Lion can eat both Deer and Grass, but Deer is not  Food it is Animal.

With out using multiple inheritance, and using object oriented design, how do you solve this problem?

FYI: I used http://www.asciiflow.com to create the ASCII diagrams.

答:
ECS composition-over-inheritance approach:

```<code>An entity is a collection of components.
Systems process entities through their components.

Lion has claws and fangs as weapons.
Lion has meat as food.
Lion has a hunger for meat.
Lion has an affinity towards other lions.

Deer has antlers and hooves as weapons.
Deer has meat as food.
Deer has a hunger for plants.

Grass has plant as food.
</code>```

Pseudocode:

```<code>lion = new Entity("Lion")
lion.put(new Claws)
lion.put(new Fangs)
lion.put(new Meat)
lion.put(new MeatHunger)
lion.put(new Affinity("Lion"))

deer = new Entity("Deer")
deer.put(new Antlers)
deer.put(new Hooves)
deer.put(new PlantHunger)

grass = new Entity("Grass")
grass.put(new Plant)
</code>```

Nature is a system that loops through these entities, looking for what components they have through a generalized query function. Nature will cause entities with a hunger for meat to attack other entities that have meat as food using their weapons, unless they have an affinity towards that entity. If the attack succeeds, the entity will feed on its victim, at which point the victim will turn into a corpse deprived of meat. Nature will cause entities with a hunger for plants to feed on entities that have plant as food, provided that they exist.

```<code>Nature({lion, deer, grass})

Nature(entities)
{
    for each entity in entities:
    {
       if entity.has("MeatHunger"):
           attack_meat(entity, entities.with("Meat", exclude = entity))
       if entity.has("PlantHunger"):
           eat_plants(entity, entites.with("Plant", exclude = entity))
    }
}
</code>```

Perhaps we want to extend Grass to have a need for sunlight and water, and we want to introduce sunlight and water into our world. Yet Grass cannot seek these out directly, as it does not have mobility. Animals may also need water, but can actively seek it out since they have mobility. It's pretty easy to keep extending and changing this model without cascading breakages of the entire design, as we just add new components and extend the behavior of our systems (or the number of systems).

Title: Object Oriented Design

Body:
ECS composition-over-inheritance approach:

An entity is a collection of components.
Systems process entities through their components.

Lion has claws and fangs as weapons.
Lion has meat as food.
Lion has a hunger for meat.
Lion has an affinity towards other lions.

Deer has antlers and hooves as weapons.
Deer has meat as food.
Deer has a hunger for plants.

Grass has plant as food.

Pseudocode:

lion = new Entity("Lion")
lion.put(new Claws)
lion.put(new Fangs)
lion.put(new Meat)
lion.put(new MeatHunger)
lion.put(new Affinity("Lion"))

deer = new Entity("Deer")
deer.put(new Antlers)
deer.put(new Hooves)
deer.put(new PlantHunger)

grass = new Entity("Grass")
grass.put(new Plant)

Nature is a system that loops through these entities, looking for what components they have through a generalized query function. Nature will cause entities with a hunger for meat to attack other entities that have meat as food using their weapons, unless they have an affinity towards that entity. If the attack succeeds, the entity will feed on its victim, at which point the victim will turn into a corpse deprived of meat. Nature will cause entities with a hunger for plants to feed on entities that have plant as food, provided that they exist.

Nature({lion, deer, grass})

Nature(entities)
{
    for each entity in entities:
    {
       if entity.has("MeatHunger"):
           attack_meat(entity, entities.with("Meat", exclude = entity))
       if entity.has("PlantHunger"):
           eat_plants(entity, entites.with("Plant", exclude = entity))
    }
}

Perhaps we want to extend Grass to have a need for sunlight and water, and we want to introduce sunlight and water into our world. Yet Grass cannot seek these out directly, as it does not have mobility. Animals may also need water, but can actively seek it out since they have mobility. It's pretty easy to keep extending and changing this model without cascading breakages of the entire design, as we just add new components and extend the behavior of our systems (or the number of systems).


答:
"I am a believer in SOLID. You are violating the single responsibility principle (SRP) as you are both representing data and performing logic in the same class."

Like the others, I disagree with this.

I would say that the SRP is violated if you are performing more than one piece of logic in the class. How much data need be stored within the class to achieve that single piece of logic is irrelevant.


答:
With out using multiple inheritance, and using object oriented design, how do you solve this problem?

What problem? What does this system do? Until you answer that, I have no idea what classes may be required. Are you trying to model an ecology, with carnivores and herbivores and plants, projecting species populations into the future? Are you trying to have the computer play 20 questions?

It's a waste of time to begin design before any use cases have been defined. I've seen this taken to ridiculous extremes when a team of about ten started producing an OO model of an Airline using software through pictures. They worked for two years modeling with no actual business problem in mind. Finally the customer got tired of waiting and asked the team to solve an actual problem. All that modeling was completely useless.

Title: Object Oriented Design

Body:
Suppose you have the following:

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+------+     +----+-+
       ^                 ^
       |                 |
       |                 |
  +------+              +-------+
  | Deer |              | Grass |
  +------+              +-------+
</code>```

Deer inherits from Animal, and Grass inherits from Food.

So far so good. Animal objects can eat Food objects.

Now lets mix it up a bit. Lets add a Lion which inherits from Animal.

```<code>     +--------+     +------+
     | Animal |     | Food |
     +-+-----++     +----+-+
       ^     ^           ^
       |     |           |
       |     |           |
  +------+ +------+     +-------+
  | Deer | | Lion |     | Grass |
  +------+ +------+     +-------+
</code>```

Now we have have a problem because Lion can eat both Deer and Grass, but Deer is not  Food it is Animal.

With out using multiple inheritance, and using object oriented design, how do you solve this problem?

FYI: I used http://www.asciiflow.com to create the ASCII diagrams.


答:
OP's comment in another answer clarified the question, I thought

that's part of what the question is asking too. If I have a herd of
  horses, and some of them are conceptually unicorns, how should they
  exist so that the problem can be cleanly solved without too many
  negative impacts?

Phrased that way, I think we need more information.  The answer probably depends on a number of things:

Our language facilities.  Eg, I'd probably approach this differently in ruby and javascript and Java.

The concepts themselves: What is a horse and what is a unicorn?  What data is associated with each? Are they exactly the same except for the horn, or do they have other differences?

How else are we using them, aside from taking horn length averages?  And what about herds?  Maybe we should model them too?  Do we use them elsewhere?  herd.averageHornLength() seems to match our conceptual model.

How are the horse and unicorn objects being created?  Is changing that code up within the bounds of our refactoring?

In general, though, I wouldn't even think about inheritance and subtypes here.  You have a list of objects.  Some of those objects can be identified as unicorns, perhaps because they have a hornLength() method.  Filter the list based on this unicorn-unique property.  Now the problem has been reduced to averaging the horn length of a list of unicorns.

OP, let me know if I'm still misunderstanding...


答:
There are already great answers pointing out that SRP is an abstract concept about logical functionality, but there are subtler points that I think are worth adding.

The first two letters in SOLID, SRP and OCP, are both about how your code changes in response to a change in requirements.  My favorite definition of the SRP is: "a module/class/function should have only one reason to change."  Arguing about likely reasons for your code to change is much more productive than arguing about whether your code is SOLID or not.

How many reasons does your Employee class have to change?  I don't know, because I don't know the context in which you're using it, and I also can't see the future.  What I can do is brainstorm possible changes based on what I've seen in the past, and you can subjectively rate how likely they are.  If more than one scores between "reasonably likely" and "my code has already changed for that exact reason", then you are violating SRP against that kind of change.  Here's one: someone with more than two names joins your company (or an architect reads this excellent W3C article).  Here's another: your company changes how it allocates holiday days.

Notice that these reasons are equally valid even if you remove the AddHolidays method.  Plenty of anemic domain models violate the SRP.  Many of them are just database-tables-in-code, and it's very common for database tables to have 20+ reasons to change.

Here's something to chew on: would your Employee class change if your system needed to track employee salaries?  Addresses?  Emergency contact info?  If you said "yes" (and "likely to happen") to two of those, then your class would be violating SRP even if had no code in it yet!  SOLID is about processes and architecture as much as it's about code.