答:
For a developer new to the system, it'd be pretty difficult guessing what true did. First thing you'd do is hover over the method name or go to the definition (neither of which are big tasks in the slightest)

Yes, true. Self documenting code is a beautiful thing. As other answers have pointed out, there are ways to remove the ambiguity of the call to ReturnEmployeeIds by using an enum, different method names, etc. However sometimes you can't really avoid the case but you don't want to go off and use them everywhere (unless you like the verbosity of visual basic).

For instance, it may help clarify one call but not necessarily another.

A named argument may be helpful here:

```<code>var ids = ReturnEmployeeIds(includeManagement: true);
</code>```

Not add much additional clarity (I'm going to guess that this is parsing an enum):

```<code>Enum.Parse(typeof(StringComparison), "Ordinal", ignoreCase: true);
</code>```

It may actually reduce clarity (if a person doesn't understand what capacity on a list is):

```<code>var employeeIds = new List<int>(capacity: 24);
</code>```

Or where it doesn't matter because you're using good variable names:

```<code>bool includeManagement = true;
var ids = ReturnEmployeeIds(includeManagement);
</code>```

Is there anywhere that, formally, discusses whether or not to explicitly specify optional parameters when the compiler doesn't need you to?

Not AFAIK. Let's address both parts though: the only time you need to explicitly use named parameters is because the compiler requires you to do so (generally it's to remove statement ambiguity). So other than that you can use them whenever you'd like. This article from MS has some suggestions on when you may want to use them but it's not particularly definitive https://msdn.microsoft.com/en-us/library/dd264739.aspx.

Personally, I find I use them most often when I'm creating custom attributes or stubbing out a new method where my parameters may change or be reordered (b/c named attributes can be listed in any order). Additionally I only use them when I'm providing a static value inline, otherwise if I'm passing a variable I try to use good variable names.

TL;DR

Ultimately it comes down to personal preference. Of course there are a few use cases when you have to use named parameters but after that you need to make a judgement call. IMO - Use it anywhere that you believe it will help document your code, reduce ambiguity, or allow you to protect method signatures.

Body:
For a developer new to the system, it'd be pretty difficult guessing what true did. First thing you'd do is hover over the method name or go to the definition (neither of which are big tasks in the slightest)

Yes, true. Self documenting code is a beautiful thing. As other answers have pointed out, there are ways to remove the ambiguity of the call to ReturnEmployeeIds by using an enum, different method names, etc. However sometimes you can't really avoid the case but you don't want to go off and use them everywhere (unless you like the verbosity of visual basic).

For instance, it may help clarify one call but not necessarily another.

A named argument may be helpful here:

var ids = ReturnEmployeeIds(includeManagement: true);

Not add much additional clarity (I'm going to guess that this is parsing an enum):

Enum.Parse(typeof(StringComparison), "Ordinal", ignoreCase: true);

It may actually reduce clarity (if a person doesn't understand what capacity on a list is):

var employeeIds = new List<int>(capacity: 24);

Or where it doesn't matter because you're using good variable names:

bool includeManagement = true;
var ids = ReturnEmployeeIds(includeManagement);

Is there anywhere that, formally, discusses whether or not to explicitly specify optional parameters when the compiler doesn't need you to?

Not AFAIK. Let's address both parts though: the only time you need to explicitly use named parameters is because the compiler requires you to do so (generally it's to remove statement ambiguity). So other than that you can use them whenever you'd like. This article from MS has some suggestions on when you may want to use them but it's not particularly definitive https://msdn.microsoft.com/en-us/library/dd264739.aspx.

Personally, I find I use them most often when I'm creating custom attributes or stubbing out a new method where my parameters may change or be reordered (b/c named attributes can be listed in any order). Additionally I only use them when I'm providing a static value inline, otherwise if I'm passing a variable I try to use good variable names.

TL;DR

Ultimately it comes down to personal preference. Of course there are a few use cases when you have to use named parameters but after that you need to make a judgement call. IMO - Use it anywhere that you believe it will help document your code, reduce ambiguity, or allow you to protect method signatures.


问:
Difficult design with multiple associations between two entities
I'm trying to design the data schema and the restful api for a specific case.

In my system I have several users and several books. Every book can have several users as authors and at the same time every user can be an authors of several books.

Now the hard part, users are interested to have a list of their books and to let the system know they are the authors, but it's important that they can also keep this association private. So a user can be the author of a book but doesn't want to make this information public.

Now a first solution can be to replicate the books information for every author and set them as private or public but this is not what I want. My idea was to use two associations in the user entity (books, public_books) where the second one is a subset of the first one.

But another problem comes with the restful api. I'm not sure what is a good way to expose this kind of data.

Something like this maybe?

```<code>/users/:id/books
</code>```

that returns a list of books made with an additional boolean property ispublic?

Is there a better idea to handle this situation in your opinion?

EDIT:
The REST API needs to return all the books linked to the user and offer a way to distinguish between public and private books. A user can obviously see all his books, but only the public books of the other users.

Another necessary thing is the possibility for a user to change the status of one of his books. A private book can become public and viceversa.

答:
But another problem comes with the restful api. I'm not sure what is a good way to expose this kind of data.

Any way you like.  REST doesn't care, so long as the application state is completely captured in the hypermedia.  In particular, REST doesn't care how you spell your URI.

Convention is to express hierarchy in the path, and filtering in the query.  For your case, that might mean

```<code>/users/:id/books?public
/users/:id/books?private
</code>```

or

```<code>/users/:id/books?visibility=public
/users/:id/books?visibility=private
</code>```

Alternatively, you can think about the context of the data -- what is the application trying to do when it is looking at these book collections.  For example, you might decide that there should be a "profiles" resource

```<code>/users/:id/profiles/private/books
/users/:id/profiles/public/books
</code>```

Or even several of these -- there's no rule that there must be no more than one URI that returns a particular data representation.  You just need to figure out how many different paths you want to support.

ContentLicense: CC BY-SA 3.0

Body:
But another problem comes with the restful api. I'm not sure what is a good way to expose this kind of data.

Any way you like.  REST doesn't care, so long as the application state is completely captured in the hypermedia.  In particular, REST doesn't care how you spell your URI.

Convention is to express hierarchy in the path, and filtering in the query.  For your case, that might mean

/users/:id/books?public
/users/:id/books?private

or

/users/:id/books?visibility=public
/users/:id/books?visibility=private

Alternatively, you can think about the context of the data -- what is the application trying to do when it is looking at these book collections.  For example, you might decide that there should be a "profiles" resource

/users/:id/profiles/private/books
/users/:id/profiles/public/books

Or even several of these -- there's no rule that there must be no more than one URI that returns a particular data representation.  You just need to figure out how many different paths you want to support.


问:
Prorating a license (its expiry) dependent on feature add-ons
I've ran into a problem trying to calculate prorating of a service. Hoping to get some help/hint from the community.

I apologize if this isn't the right place to ask this question - will appreciate help in finding the right StackExchange service.

Given:

An online service that issues "licenses" that can be purchased for the time periods in multiples of 30 days/1 month (for simplicity, let's assume that all months have 30 days)

"Base" subscription costs $15/month

On top of base subscription there are also 20 "feature add-ons". Their price varies between $2 and $5 per month

Customer is allowed to purchase "base" subscription without any add-ons

Having paid the "base" $15, customer is allowed to add any "feature add-on" any time he desires without paying extra for it.

Details:

a. Item #5 above needs a bit of explanation. The idea there is to allow customers who are paying the base amount to "try out" any "feature add-on" without collecting more money from them.

Rationale:

"Customer X has already paid me $15 for 30days of service. Now, I will let him add a new "feature add-on" worth of $5/mo without sending him to shopping cart. However, I'll recalculate the expiry of the license based on $15+$5/mo rate. Thus the license would have fewer days until it expires".

Difficulty:

a. The newly added $5 add-on should itself be prorated. It is also possible that customer selects the amount of add-ons that would lead to the situation when the service would owe the customer.

b. There is a "cut-off" date that's determined by the amount the new add-ons cost after which moving license expiry date "to the left" (i.e. closer to current moment in time) would essentially make it expire immediately.

Questions:

How do I calculate the updated expiry of a license based on the rationale above?

How do I calculate the highest value of add-ons that can be selected without making license expire?

答:
The easiest way to resolve this is to shift how you're defining the end of their license term.

Currently, I suspect you're using the natural approach of "User purchased base item for $N, so user has an expiration date of ..."  In other words, the expiration date is determined at the time of purchase.

The challenge with that approach comes about when you want to allow clients to try features out for some period of time.

To fix that, you need to change your internal representation of how charges are accrued.

Pick a base unit of time, such as hours or days.  From there, you can determine a rate per base unit of time.  If we pick days as the base unit, and $15 for the basic license for 30 days, we end up with ~$0.50 per day.

From there, you'll need to have a slightly different equation for determining the remaining term within the license.  You'll want something like:

var remTermInBaseTime = client.Balance / client.SelectedItems.BurnRate
```

That allows you to calculate the remaining amount of time in the base unit of time based upon the client's balance and selected feature burn rate.  To provide a prediction of when the license will expire, you would add the remaining term to the current time.

Then, when a client selects additional features then all you have to do is update their burn rate and recalculate the remaining term.  This also gracefully handles the case where a client tries feature X for a day and then removes the feature for whatever particular reason.

Ultimately this moves your clients to a per-feature subscription basis where they top off their balance as their funds dictate and you return with a reply of "this buys you N units of time" with your license.  Whether or not you change your pricing to be reflected in the base units of time is dependent upon how your customers react to the change and what they appear to prefer to see.

One challenge with this approach is that some feature prices won't divide evenly into the base unit of time.  For example, if you picked hours as the base unit, then you would end up with ~$0.020833 per hour for the base license.  That could be handled with some rounding, or you could change the rates to be divisible by the number of base units of time that you pick.

Body:
The easiest way to resolve this is to shift how you're defining the end of their license term.

Currently, I suspect you're using the natural approach of "User purchased base item for $N, so user has an expiration date of ..."  In other words, the expiration date is determined at the time of purchase.

The challenge with that approach comes about when you want to allow clients to try features out for some period of time.

To fix that, you need to change your internal representation of how charges are accrued.

Pick a base unit of time, such as hours or days.  From there, you can determine a rate per base unit of time.  If we pick days as the base unit, and $15 for the basic license for 30 days, we end up with ~$0.50 per day.

From there, you'll need to have a slightly different equation for determining the remaining term within the license.  You'll want something like:

var remTermInBaseTime = client.Balance / client.SelectedItems.BurnRate

That allows you to calculate the remaining amount of time in the base unit of time based upon the client's balance and selected feature burn rate.  To provide a prediction of when the license will expire, you would add the remaining term to the current time.

Then, when a client selects additional features then all you have to do is update their burn rate and recalculate the remaining term.  This also gracefully handles the case where a client tries feature X for a day and then removes the feature for whatever particular reason.

Ultimately this moves your clients to a per-feature subscription basis where they top off their balance as their funds dictate and you return with a reply of "this buys you N units of time" with your license.  Whether or not you change your pricing to be reflected in the base units of time is dependent upon how your customers react to the change and what they appear to prefer to see.

One challenge with this approach is that some feature prices won't divide evenly into the base unit of time.  For example, if you picked hours as the base unit, then you would end up with ~$0.020833 per hour for the base license.  That could be handled with some rounding, or you could change the rates to be divisible by the number of base units of time that you pick.


问:
If a number is too big does it spill over to the next memory location?
I've been reviewing C programming and there are just a couple things bothering me.

Let's take this code for example:

```<code>int myArray[5] = {1, 2, 2147483648, 4, 5};
int* ptr = myArray;
int i;
for(i=0; i<5; i++, ptr++)
    printf("\n Element %d holds %d at address %p", i, myArray[i], ptr);
</code>```

I know that an int can hold a maximum value of positive 2,147,483,647. So by going one over that, does it "spill over" to the next memory address which causes element 2 to appear as "-2147483648" at that address? But then that doesn't really make sense because in the output it still says that the next address holds the value 4, then 5. If the number had spilled over to the next address then wouldn't that change the value stored at that address?

I vaguely remember from programming in MIPS Assembly and watching the addresses change values during the program step by step that values assigned to those addresses would change.

Unless I am remembering incorrectly then here is another question: If the number assigned to a specific address is bigger than the type (like in myArray[2]) then does it not affect the values stored at the subsequent address?

Example: We have int myNum = 4 billion at address 0x10010000. Of course myNum can't store 4 billion so it appears as some negative number at that address. Despite not being able to store this large number, it has no effect on the value stored at the subsequent address of 0x10010004. Correct?

The memory addresses just have enough space to hold certain sizes of numbers/characters, and if the size goes over the limit then it will be represented differently (like trying to store 4 billion into the int but it will appear as a negative number) and so it has no effect on the numbers/characters stored at the next address.

Sorry if I went overboard. I've been having a major brain fart all day from this.

答:
So, there are two things here:

the language level: what are the semantics of C

the machine level: what are the semantics of the assembly/CPU you use

At the language level:

In C:

overflow and underflow are defined as modulo arithmetic for unsigned integers, thus their value "loops"

overflow and underflow are Undefined Behavior for signed integers, thus anything can happen

For those would want a "what anything" example, I've seen:

```<code>for (int i = 0; i >= 0; i++) {
    ...
}
</code>```

turn into:

```<code>for (int i = 0; true; i++) {
    ...
}
</code>```

and yes, this is a legitimate transformation.

It means that there are indeed potential risks of overwriting memory on overflow due to some weird compiler transformation.

Note: on Clang or gcc use -fsanitize=undefined in Debug to activate the Undefined Behavior Sanitizer which will abort on underflow/overflow of signed integers.

Or it means that you can overwrite memory by using the result of the operation to index (unchecked) into an array. This is unfortunately far more likely in the absence of underflow/overflow detection.

Note: on Clang or gcc use -fsanitize=address in Debug to activate the Address Sanitizer which will abort on out-of-bounds access.

At the machine level:

It really depends upon the assembly instructions and CPU you use:

on x86, ADD will use 2-complement on overflow/underflow, and set the OF (Overflow Flag)

on the future Mill CPU, there will be 4 different overflow modes for Add:

Modulo: 2-complement modulo

Trap: a trap is generated, halting computation

Saturate: value gets stuck to min on underflow or max on overflow

Double Width: the result is generated in a double-width register

Note that whether things happen in registers or memory, in neither case does the CPU overwrite memory on overflow.

Body:
So, there are two things here:

the language level: what are the semantics of C

the machine level: what are the semantics of the assembly/CPU you use

At the language level:

In C:

overflow and underflow are defined as modulo arithmetic for unsigned integers, thus their value "loops"

overflow and underflow are Undefined Behavior for signed integers, thus anything can happen

For those would want a "what anything" example, I've seen:

for (int i = 0; i >= 0; i++) {
    ...
}

turn into:

for (int i = 0; true; i++) {
    ...
}

and yes, this is a legitimate transformation.

It means that there are indeed potential risks of overwriting memory on overflow due to some weird compiler transformation.

Note: on Clang or gcc use -fsanitize=undefined in Debug to activate the Undefined Behavior Sanitizer which will abort on underflow/overflow of signed integers.

Or it means that you can overwrite memory by using the result of the operation to index (unchecked) into an array. This is unfortunately far more likely in the absence of underflow/overflow detection.

Note: on Clang or gcc use -fsanitize=address in Debug to activate the Address Sanitizer which will abort on out-of-bounds access.

At the machine level:

It really depends upon the assembly instructions and CPU you use:

on x86, ADD will use 2-complement on overflow/underflow, and set the OF (Overflow Flag)

on the future Mill CPU, there will be 4 different overflow modes for Add:

Modulo: 2-complement modulo

Trap: a trap is generated, halting computation

Saturate: value gets stuck to min on underflow or max on overflow

Double Width: the result is generated in a double-width register

Note that whether things happen in registers or memory, in neither case does the CPU overwrite memory on overflow.


答:
First (assuming C99 standard), you may want to include <stdint.h> standard header and use some of the types defined there, notably int32_t which is exactly a 32 bits signed integer, or uint64_t which is exactly a 64 bits unsigned integer, and so on. You might want to use types like int_fast16_t for performance reasons.

Read others answers explaining that unsigned arithmetic never spills (or overflows) to adjacent memory locations. Beware of undefined behavior on signed overflow.

Then, if you need to compute exactly huge integer numbers (e.g. you want to compute factorial of 1000 with all its 2568 digits in decimal), you want bigints a.k.a. arbitrary precision numbers (or bignums). Algorithms for efficient bigint arithmetic are very clever, and usually requires using specialized machine instructions (e.g. some add word with carry, if your processor has that). Hence I strongly recommend in that case to use some existing bigint library like GMPlib

Title: If a number is too big does it spill over to the next memory location?

Body:
I've been reviewing C programming and there are just a couple things bothering me.

Let's take this code for example:

```<code>int myArray[5] = {1, 2, 2147483648, 4, 5};
int* ptr = myArray;
int i;
for(i=0; i<5; i++, ptr++)
    printf("\n Element %d holds %d at address %p", i, myArray[i], ptr);
</code>```

I know that an int can hold a maximum value of positive 2,147,483,647. So by going one over that, does it "spill over" to the next memory address which causes element 2 to appear as "-2147483648" at that address? But then that doesn't really make sense because in the output it still says that the next address holds the value 4, then 5. If the number had spilled over to the next address then wouldn't that change the value stored at that address?

I vaguely remember from programming in MIPS Assembly and watching the addresses change values during the program step by step that values assigned to those addresses would change.

Unless I am remembering incorrectly then here is another question: If the number assigned to a specific address is bigger than the type (like in myArray[2]) then does it not affect the values stored at the subsequent address?

Example: We have int myNum = 4 billion at address 0x10010000. Of course myNum can't store 4 billion so it appears as some negative number at that address. Despite not being able to store this large number, it has no effect on the value stored at the subsequent address of 0x10010004. Correct?

The memory addresses just have enough space to hold certain sizes of numbers/characters, and if the size goes over the limit then it will be represented differently (like trying to store 4 billion into the int but it will appear as a negative number) and so it has no effect on the numbers/characters stored at the next address.

Sorry if I went overboard. I've been having a major brain fart all day from this.


问:
Specify optional parameter names even though not required?
Consider the following method:

```<code>public List<Guid> ReturnEmployeeIds(bool includeManagement = false)
{

}
</code>```

And the following call:

```<code>var ids = ReturnEmployeeIds(true);
</code>```

For a developer new to the system, it'd be pretty difficult guessing what true did. First thing you'd do is hover over the method name or go to the definition (neither of which are big tasks in the slightest). But, for readability sake, does it make sense to write:

```<code>var ids = ReturnEmployeeIds(includeManagement: true);
</code>```

Is there anywhere that, formally, discusses whether or not to explicitly specify optional parameters when the compiler doesn't need you to?

The following article discusses certain coding conventions: https://msdn.microsoft.com/en-gb/library/ff926074.aspx

Something similar to the article above would be great.

答:
There aren't any super clear reasons as why to use this type of syntax in the first place.

In general, try to avoid having having boolean arguments that at a distance may look arbitrary. includeManagement will (most likely) affect the result greatly. But the argument looks like it carries "little weight".

The use of an enum has been discussed, not only will it look like the argument "carries more weight", but it will also provide scalability to the method. This might however not be the best solution in all cases, since your ReturnEmployeeIds-method will have to scale alongside the WhatToInclude-enum (see NiklasJ's answer). This might give you a headache later.

Consider this: If you scale the WhatToInclude-enum, but not the ReturnEmployeeIds-method. It might then throw a ArgumentOutOfRangeException (best case) or return something completely unwanted (null or an empty List<Guid>). Which in some cases might confuse the programmer, especially if your ReturnEmployeeIds is in a class-library, where the source-code is not readily available.

One will assume that WhatToInclude.Trainees will work if WhatToInclude.All does, seeing that trainees is a "subset" of all.

This does (of course), depend on how ReturnEmployeeIds is implemented.

In cases where a boolean argument could be passed in, I try to instead break it up into two methods (or more, if needed), in your case; one might extract ReturnAllEmployeeIds, ReturnManagementIds and ReturnRegularEmployeeIds. This covers all bases and is absolutely self-explanatory to whoever implements it. This will also not have the "scaling"-issue, mentioned above.

Since there are only ever two outcomes for something that has a boolean argument. Implementing two methods, takes very little extra effort.

Less code, is seldom better.

With this said, there are some cases where explicitly declaring the argument improves readability. Consider for instance. GetLatestNews(max: 10). GetLatestNews(10) is still pretty self-explanatory, the explicit declaration of max will help clear up any confusion.

And if you absolutely must have a boolean argument, which usage cannot be inferred by just reading true or false. Then I would say that:

```<code>var ids = ReturnEmployeeIds(includeManagement: true);
</code>```

.. is absolutely better, and more readable than:

```<code>var ids = ReturnEmployeeIds(true);
</code>```

Since in the second example, the true might mean absolutely anything. But i would try to avoid this argument.

Body:
There aren't any super clear reasons as why to use this type of syntax in the first place.

In general, try to avoid having having boolean arguments that at a distance may look arbitrary. includeManagement will (most likely) affect the result greatly. But the argument looks like it carries "little weight".

The use of an enum has been discussed, not only will it look like the argument "carries more weight", but it will also provide scalability to the method. This might however not be the best solution in all cases, since your ReturnEmployeeIds-method will have to scale alongside the WhatToInclude-enum (see NiklasJ's answer). This might give you a headache later.

Consider this: If you scale the WhatToInclude-enum, but not the ReturnEmployeeIds-method. It might then throw a ArgumentOutOfRangeException (best case) or return something completely unwanted (null or an empty List<Guid>). Which in some cases might confuse the programmer, especially if your ReturnEmployeeIds is in a class-library, where the source-code is not readily available.

One will assume that WhatToInclude.Trainees will work if WhatToInclude.All does, seeing that trainees is a "subset" of all.

This does (of course), depend on how ReturnEmployeeIds is implemented.

In cases where a boolean argument could be passed in, I try to instead break it up into two methods (or more, if needed), in your case; one might extract ReturnAllEmployeeIds, ReturnManagementIds and ReturnRegularEmployeeIds. This covers all bases and is absolutely self-explanatory to whoever implements it. This will also not have the "scaling"-issue, mentioned above.

Since there are only ever two outcomes for something that has a boolean argument. Implementing two methods, takes very little extra effort.

Less code, is seldom better.

With this said, there are some cases where explicitly declaring the argument improves readability. Consider for instance. GetLatestNews(max: 10). GetLatestNews(10) is still pretty self-explanatory, the explicit declaration of max will help clear up any confusion.

And if you absolutely must have a boolean argument, which usage cannot be inferred by just reading true or false. Then I would say that:

var ids = ReturnEmployeeIds(includeManagement: true);

.. is absolutely better, and more readable than:

var ids = ReturnEmployeeIds(true);

Since in the second example, the true might mean absolutely anything. But i would try to avoid this argument.


问:
Design pattern for abstracting interaction between multiple resources
So far I've been building applications abstracting data entity operations behind the use of Repositories. Each of them would encapsulate the domain that corresponds to their defined entity. For instance: UserRepository would encapsulate domain logic regarding the User entity, such as changePassword(old,new), createAccount(email,password, retrieveAllFriendsForUser(id) and such.

But there are cases where you need multiple resources to interact and abstracting that logic in a repository from another entity feels smelly. For example: buying an Item would require you to create a Quotation, create a Payment, reducing the ItemQuantity from the Inventory and such; handling that operation in the ItemRepository would mean it's implementation would depend on QuotationRepository, PaymentRepository, etc...

I've read before about the Business Facade and the Unit of Work patterns, but having just read them again they seem not to be aimed at this specific multiple resource interaction issue, but rather aimed at simplified access to chunks of code and handling atomic operations, respectively.

What's a design pattern for handling multiple resource interaction and if possible a quick example code that complements it.

答:
What you're describing is business logic.  Purchasing an Item is a business transaction.  This belongs in the Service layer.

Remember that the Repository layer acts as a facade for persistence, and exists to abstract the underlying details of your persistence mechanism from the rest of your application.

The Service layer, by contrast, exposes business logic that uses your repositories.  The service layer should coordinate the different transactions from the different repositories


问:
Idiomatic way to write JavaScript class that maintains state and tells you when that state has changed
I am an experienced C++ developer but new to JavaScript. I want to write an ES6 JavaScript class that maintains state.

How do I tell when state has changed?

I can think of two ways to do this. One way is to inspect an instance of the class to see if it is "dirty" since the last time it was marked "clean". I.e. mark an instance object as clean and changing any data member of the class marks it as dirty. Or be able to compare two instances of the same class. If an incoming state does not equal a known state then state has changed. I know this is not built into JavaScript.

What is the best way to do this in JavaScript? I am working in Typescript if it makes a difference.

答:
Based on comments, here's a dirty-bit implementation that should work:</p>

```<code>class Dirtyable {
    private _isDirty:Boolean = false;
    get isDirty():Boolean {
        return _isDirty;
    }

    private _example:String;
    get example():String {
        return _example;
    }
    set example(val):String {
        if (val !== _example) _isDirty = true;
        _example = val;
    }
}
</code>```

Body:
Based on comments, here's a dirty-bit implementation that should work:

class Dirtyable {
    private _isDirty:Boolean = false;
    get isDirty():Boolean {
        return _isDirty;
    }

    private _example:String;
    get example():String {
        return _example;
    }
    set example(val):String {
        if (val !== _example) _isDirty = true;
        _example = val;
    }
}


答:
I think you are confusing a few different ideas here.

The repository is usually used an abstraction between the consuming code and the persistence component.  Typical methods on a UserRepository would be

```<code>interface UserRepository {
    void save(User user);
    User getById(UserId id);
}
</code>```

Operations to change the User would normally be implemented on the User itself

```<code>interface User {
    void changePassword(String newPassword);
}
</code>```

Objects that are used to coordinate concerns distributed among multiple components are usually constructed with references to the components.  You'll often find that a Factory is used to create the objects; including factories that call into other factories to get the individual parts.

When the specification of the object to be created is particularly complicated, you are likely to see a Builder enter the picture, as a mechanism for collecting the various arguments that are going to be needed to create the object graph.

Things get more complicated when you are dealing with objects that are stored in separate repositories.  What you are likely to see in this case are atomic operations on the objects, which send asynchronous messages to each other to communicate changes.

For instance: a customer places an order for some product.  The new state of the order is saved in the order repository.  A process manager observes the new order, and dispatches an asynchronous message to the warehouse component to ship the order.  The appropriate warehouse is loaded from the warehouse repository to update the inventory in stock, etc, and save that information off.  In removing the inventory from the stock, the warehouse observes that the available stock has dropped below the reserve limit, so another asynchronous message is dispatched to report this.  Yet another component picks up this message, and starts the work of ordering more stock from the supplier, etc.

Title: Design pattern for abstracting interaction between multiple resources

Body:
So far I've been building applications abstracting data entity operations behind the use of Repositories. Each of them would encapsulate the domain that corresponds to their defined entity. For instance: UserRepository would encapsulate domain logic regarding the User entity, such as changePassword(old,new), createAccount(email,password, retrieveAllFriendsForUser(id) and such.

But there are cases where you need multiple resources to interact and abstracting that logic in a repository from another entity feels smelly. For example: buying an Item would require you to create a Quotation, create a Payment, reducing the ItemQuantity from the Inventory and such; handling that operation in the ItemRepository would mean it's implementation would depend on QuotationRepository, PaymentRepository, etc...

I've read before about the Business Facade and the Unit of Work patterns, but having just read them again they seem not to be aimed at this specific multiple resource interaction issue, but rather aimed at simplified access to chunks of code and handling atomic operations, respectively.

What's a design pattern for handling multiple resource interaction and if possible a quick example code that complements it.

Body:
I think you are confusing a few different ideas here.

The repository is usually used an abstraction between the consuming code and the persistence component.  Typical methods on a UserRepository would be

interface UserRepository {
    void save(User user);
    User getById(UserId id);
}

Operations to change the User would normally be implemented on the User itself

interface User {
    void changePassword(String newPassword);
}

Objects that are used to coordinate concerns distributed among multiple components are usually constructed with references to the components.  You'll often find that a Factory is used to create the objects; including factories that call into other factories to get the individual parts.

When the specification of the object to be created is particularly complicated, you are likely to see a Builder enter the picture, as a mechanism for collecting the various arguments that are going to be needed to create the object graph.

Things get more complicated when you are dealing with objects that are stored in separate repositories.  What you are likely to see in this case are atomic operations on the objects, which send asynchronous messages to each other to communicate changes.

For instance: a customer places an order for some product.  The new state of the order is saved in the order repository.  A process manager observes the new order, and dispatches an asynchronous message to the warehouse component to ship the order.  The appropriate warehouse is loaded from the warehouse repository to update the inventory in stock, etc, and save that information off.  In removing the inventory from the stock, the warehouse observes that the available stock has dropped below the reserve limit, so another asynchronous message is dispatched to report this.  Yet another component picks up this message, and starts the work of ordering more stock from the supplier, etc.


问:
Parallel hierarchies - partly same, partly different
There are quite a few similar questions out there 1, 2, 3, 4, but non seems exactly the case in this question, nor do the solutions seem optimal.

This is a general OOP question, assuming polymorphism, generics, and mixins are available. The actual language to be used is OOP Javascript (Typescript), but it's the same problem in Java or C++.

I have parallel class hierarchies, that sometimes share the same behaviour (interface and implementation), but sometimes each has its own 'protected' behaviour. Illustrated like so:

This is for illustration purposes only; it isn't the actual class diagram. To read it:

Anything in the common hierarchy (centre) is shared between both the Canvas (left) and SVG (right) hierarchies. By share I mean both interface and implementation.

Anything only on the left or right columns means a behaviour (methods and members) specific to that hierarchy. For example:

Both the left and right hierarchies use exactly the same validation mechanisms, shown as a single method (Viewee.validate()) on the common hierarchy.

Only the canvas hierarchy has a method paint(). This method calls the paint method on all children.

The SVG hierarchy needs to override the addChild() method of Composite, but such is not the case with the canvas hierarchy.

The constructs from the two side hierarchies cannot be mixed. A factory ensures that.

Solution I - Tease Apart Inheritance

Fowler's Tease Apart Inheritance doesn't seem to do the job here, because there is some discrepancy between the two parallels.

Solution II - Mixins

This is the only one I can currently think of. The two hierarchies are develop separately, but at each level the classes mixin the common class, which are not part of a class hierarchy. Omitting the structural fork, will look like this:

Note that each column will be in its own namespace, so class names won't conflict.

The question

Can anyone see faults with this approach? Can anyone think of a better solution?

Addendum

Here is some sample code how this is to be used. The namespace svg may be replaced with canvas:

```<code>var iView        = document.getElementById( 'view' ),
    iKandinsky   = new svg.Kandinsky(),
    iEpigone     = new svg.Epigone(),
    iTonyBlair   = new svg.TonyBlair( iView, iKandinsky ),
    iLayer       = new svg.Layer(),
    iZoomer      = new svg.Zoomer(),
    iFace        = new svg.Rectangle( new Rect( 20, 20, 100, 60) ),
    iEyeL        = new svg.Rectangle( new Rect( 20, 20, 20, 20) ),
    iEyeR        = new svg.Rectangle( new Rect( 60, 20, 20, 20) );

iKandinsky.setContext( iTonyBlair.canvas.getContext( '2d' ) );
iEpigone.setContext( iTonyBlair.canvas.getContext( '2d' ) );

iFace.addChildren( iEyeL, iEyeR );
iZoomer.setZoom( new Point( 2, 2 ) );
iZoomer.addChild( iFace );
iLayer.addChild( iZoomer );
iTonyBlair.setContent( iLayer );
</code>```

Essentially, in run-time clients compose instances hierarchy of Viewee subclasses; like so:

Say all these viewees are from the canvas hierarchy, they are rendered by traversing the hierarchy can calling paint() on each viewee. If they are from the svg hierarchy, viewees know how to add themselves to the DOM, but there isn't paint() traversal.

答:
The second approach segregates interfaces better, following the interface segregation principle.

However, I would add a Paintable interface.

I would also change some names. No need to create confusion:

// common

public interface IComposite {
    public void addChild(Composite e);
}

public interface IViewee extends IComposite{
    public void validate();
    public List<IBound> getAbsoluteBouns();
}

public interface IVisual {
    public List<IBound> getBounds();
}

public interface IRec {
}

public interface IPaintable {
    public void paint();
}

// canvas

public interface ICanvasViewee extends IViewee, IPaintable {
}

public interface ICanvasVisual extends IViewee, IVisual {
}

public interface ICanvasRect extends ICanvasVisual, IRec {
}

// SVG

public interface ISVGViewee extends IViewee {
    public void element();
}

public interface ISVGVisual extends IVisual, ISVGViewee {
}

public interface ISVGRect extends ISVGVisual, IRect {
}
```


答:
Would this be an acceptable solution if the number of data members or fields of the class is large?

```<code>export class State {

    private _dirty: boolean = false;

    private _data1: string = '';
    private _data2: number = 0;

    constructor( d1: string, d2: number ) {
        this._data1 = d1;
        this._data2 = d2;
    }

    get dirty() {
        return this._dirty;
    }

    set dirty( value: boolean ) {
        this._dirty = value;
    }

    set( field: string, value: any ) {
        var theField: any = this[field];
        if ( theField != undefined ) {
            this[field] = value;
            this._dirty = true;
        }
        else {
            console.log( 'Field "' + field + '" is not defined' );
            throw 'Field "' + field + '" is not defined';
        }
    }
}
</code>```

Example usage:

```<code>var rs1: State = new State( "one", 1 );

var isDirty = rs1.dirty;
rs1.set( '_data1', "two" );
isDirty = rs1.dirty;
rs1.set( 'blah', "two" );
</code>```

Title: Idiomatic way to write JavaScript class that maintains state and tells you when that state has changed

Body:
I am an experienced C++ developer but new to JavaScript. I want to write an ES6 JavaScript class that maintains state.

How do I tell when state has changed?

I can think of two ways to do this. One way is to inspect an instance of the class to see if it is "dirty" since the last time it was marked "clean". I.e. mark an instance object as clean and changing any data member of the class marks it as dirty. Or be able to compare two instances of the same class. If an incoming state does not equal a known state then state has changed. I know this is not built into JavaScript.

What is the best way to do this in JavaScript? I am working in Typescript if it makes a difference.

Body:
Would this be an acceptable solution if the number of data members or fields of the class is large?

export class State {

    private _dirty: boolean = false;

    private _data1: string = '';
    private _data2: number = 0;

    constructor( d1: string, d2: number ) {
        this._data1 = d1;
        this._data2 = d2;
    }

    get dirty() {
        return this._dirty;
    }

    set dirty( value: boolean ) {
        this._dirty = value;
    }

    set( field: string, value: any ) {
        var theField: any = this[field];
        if ( theField != undefined ) {
            this[field] = value;
            this._dirty = true;
        }
        else {
            console.log( 'Field "' + field + '" is not defined' );
            throw 'Field "' + field + '" is not defined';
        }
    }
}

Example usage:

var rs1: State = new State( "one", 1 );

var isDirty = rs1.dirty;
rs1.set( '_data1', "two" );
isDirty = rs1.dirty;
rs1.set( 'blah', "two" );


问:
Passing in objects to __init__ or passing a common param to and constructing objects inside __init__?
I have a class Foo that creates instances of other classes A, B, and C in its constructor. A, B, and C share the same constructor parameter and are used in other parts of the codebase, not just in Foo. A, B, and C access an outside resource configured by the passed parameter. In unit tests, A, B, and C are mocked out with unittest.mock.patch.

```<code>class Foo(object):
    def __init__(self, param):
        self.a = A(param)
        self.b = B(param)
        self.c = C(param)

foo = Foo('param')
</code>```

Would the following be an improvement or just unnecessary code? Is passing in unittest.mock.Mock objects in tests preferred over using unittest.mock.patch? In practice, A, B, and C should always share the same parameter.

```<code>class Foo(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    @classmethod
    def from_param(cls, param):
        return cls(A(param), B(param), C(param))

foo = Foo.from_param('param')
</code>```

答:
This is a little hard to reason about in isolation but I generally like the second approach better. It gives you the flexibility to pass any three objects (including your mocks). If it is not a class invariant that they all be constructed with the same parameters, this seems to be a good thing. The classmethod you provide for the case that you want A, B, C constructed with the same parameters makes it still convenient to use in the common case. And you can add more convenience factory functions later shall there be a need.

Of course, you shouldn't over-abstract either but the fact that you think about mocking hints me that this is not the case here.


答:
This is a general OOP question, assuming polymorphism, generics, and
  mixins are available. The actual language to be used is OOP Javascript
  (Typescript), but it's the same problem in Java or C++.

That's actually not true at all. Typescript has a substantial advantage over Java- namely, structural typing. You can do something similar in C++ with duck typed templates, but it's a lot more effort.

Basically, define your classes, but do not bother extending or defining any interfaces. Then simply define the interface you need and take it as a parameter. Then, the objects can match that interface- they don't need to know to extend it in advance. Each function can declare exactly and only the bits they give a shit about, and the compiler will give you a pass if the final type meets it, even though the classes don't actually extend those interfaces explicitly.

This frees you from the need to actually define an interface hierarchy and define which classes should extend which interfaces.

Just define each class and forget about the interfaces- structural typing will take care of it.

For example:

```<code>class SVGViewee {
    validate() { /* stuff */ }
    addChild(svg: SVG) { /* stuff */ }
}
class CanvasViewee {
    validate() { /* stuff */ }
    paint() { /* stuff */ }
}
interface SVG {
    addChild: { (svg: SVG): void };
}
f(viewee: { validate: { (): boolean }; }) {
    viewee.validate();
}
g(svg: SVG) {
    svg.addChild(svg);
}
h(canvas: { paint: { (): void }; }) {
    canvas.paint();
}
f(SVGViewee());
f(CanvasViewee());
g(SVGViewee());
h(CanvasViewee());
</code>```

This is totally legitimate Typescript. Notice that the consuming functions don't know or give a single shit about the base classes or interfaces used in the definition of the classes.

It doesn't matter if the classes are related or not by inheritance. It doesn't matter if they extended your interface. Just define the interface as the parameter, and you're done- all classes that meet it are accepted.

Title: Parallel hierarchies - partly same, partly different

Body:
There are quite a few similar questions out there 1, 2, 3, 4, but non seems exactly the case in this question, nor do the solutions seem optimal.

This is a general OOP question, assuming polymorphism, generics, and mixins are available. The actual language to be used is OOP Javascript (Typescript), but it's the same problem in Java or C++.

I have parallel class hierarchies, that sometimes share the same behaviour (interface and implementation), but sometimes each has its own 'protected' behaviour. Illustrated like so:

This is for illustration purposes only; it isn't the actual class diagram. To read it:

Anything in the common hierarchy (centre) is shared between both the Canvas (left) and SVG (right) hierarchies. By share I mean both interface and implementation.

Anything only on the left or right columns means a behaviour (methods and members) specific to that hierarchy. For example:

Both the left and right hierarchies use exactly the same validation mechanisms, shown as a single method (Viewee.validate()) on the common hierarchy.

Only the canvas hierarchy has a method paint(). This method calls the paint method on all children.

The SVG hierarchy needs to override the addChild() method of Composite, but such is not the case with the canvas hierarchy.

The constructs from the two side hierarchies cannot be mixed. A factory ensures that.

Solution I - Tease Apart Inheritance

Fowler's Tease Apart Inheritance doesn't seem to do the job here, because there is some discrepancy between the two parallels.

Solution II - Mixins

This is the only one I can currently think of. The two hierarchies are develop separately, but at each level the classes mixin the common class, which are not part of a class hierarchy. Omitting the structural fork, will look like this:

Note that each column will be in its own namespace, so class names won't conflict.

The question

Can anyone see faults with this approach? Can anyone think of a better solution?

Addendum

Here is some sample code how this is to be used. The namespace svg may be replaced with canvas:

```<code>var iView        = document.getElementById( 'view' ),
    iKandinsky   = new svg.Kandinsky(),
    iEpigone     = new svg.Epigone(),
    iTonyBlair   = new svg.TonyBlair( iView, iKandinsky ),
    iLayer       = new svg.Layer(),
    iZoomer      = new svg.Zoomer(),
    iFace        = new svg.Rectangle( new Rect( 20, 20, 100, 60) ),
    iEyeL        = new svg.Rectangle( new Rect( 20, 20, 20, 20) ),
    iEyeR        = new svg.Rectangle( new Rect( 60, 20, 20, 20) );

iKandinsky.setContext( iTonyBlair.canvas.getContext( '2d' ) );
iEpigone.setContext( iTonyBlair.canvas.getContext( '2d' ) );

iFace.addChildren( iEyeL, iEyeR );
iZoomer.setZoom( new Point( 2, 2 ) );
iZoomer.addChild( iFace );
iLayer.addChild( iZoomer );
iTonyBlair.setContent( iLayer );
</code>```

Essentially, in run-time clients compose instances hierarchy of Viewee subclasses; like so:

Say all these viewees are from the canvas hierarchy, they are rendered by traversing the hierarchy can calling paint() on each viewee. If they are from the svg hierarchy, viewees know how to add themselves to the DOM, but there isn't paint() traversal.

Body:
This is a general OOP question, assuming polymorphism, generics, and
  mixins are available. The actual language to be used is OOP Javascript
  (Typescript), but it's the same problem in Java or C++.

That's actually not true at all. Typescript has a substantial advantage over Java- namely, structural typing. You can do something similar in C++ with duck typed templates, but it's a lot more effort.

Basically, define your classes, but do not bother extending or defining any interfaces. Then simply define the interface you need and take it as a parameter. Then, the objects can match that interface- they don't need to know to extend it in advance. Each function can declare exactly and only the bits they give a shit about, and the compiler will give you a pass if the final type meets it, even though the classes don't actually extend those interfaces explicitly.

This frees you from the need to actually define an interface hierarchy and define which classes should extend which interfaces.

Just define each class and forget about the interfaces- structural typing will take care of it.

For example:

class SVGViewee {
    validate() { /* stuff */ }
    addChild(svg: SVG) { /* stuff */ }
}
class CanvasViewee {
    validate() { /* stuff */ }
    paint() { /* stuff */ }
}
interface SVG {
    addChild: { (svg: SVG): void };
}
f(viewee: { validate: { (): boolean }; }) {
    viewee.validate();
}
g(svg: SVG) {
    svg.addChild(svg);
}
h(canvas: { paint: { (): void }; }) {
    canvas.paint();
}
f(SVGViewee());
f(CanvasViewee());
g(SVGViewee());
h(CanvasViewee());

This is totally legitimate Typescript. Notice that the consuming functions don't know or give a single shit about the base classes or interfaces used in the definition of the classes.

It doesn't matter if the classes are related or not by inheritance. It doesn't matter if they extended your interface. Just define the interface as the parameter, and you're done- all classes that meet it are accepted.


答:
Quick Overview

Solution 3: The "Parallel Class Hierarchy" Software Design Pattern is your friend.

Long Extended Answer

Your design STARTED RIGHT. It can be optimized, some classes or members may be removed, but, the "parallel hierarchy" idea you are applying to solve a problem IS RIGHT.

Have deal with the same concept several times, usually in control hierarchies.

After a while, I ENDED DOING THE SAME SOLUTION THAN OTHER DEVELOPERS, that is called sometimes the "Parallel Hierarchy" Design Pattern or "Dual Hierarchy" Design Pattern.

(1) Have you ever split a single class into a single hierarchy of classes ?

(2) Have you ever split a single class into several classes, without a hierarchy ?

If you have applied these previous solutions, separately, then they are a way to solve some problems.

But, what if we combine these two solutions, simultaneously ?

Combine them, and, you'll get this "Design Pattern" .

Implementation

Now, let's apply the "Parallel Class Hierarchy" Software Design Pattern,
to your case.

You currently have 2 or more independent hierarchies of classes,
that are very similar, have similar associations or purpouse,
have similar properties or methods.

You wish to avoid having duplicated code or members ("consistency"),
yet, you can't merge this classes directly into a single one,
due to the differences among them.

So, your hierarchies are very similar to this figure,
but, yet, there are more than one:

```<code>................................................
...............+----------------+...............
...............|     Common::   |...............
...............|    Composite   |...............
...............+----------------+...............
...............|      ...       |...............
...............+-------+--------+...............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
...............+-------+--------+...............
...............|     Common::   |...............
...............|     Viewee     |...............
...............+----------------+...............
...............|      ...       |...............
...............+-------+--------+...............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
..........+------------+------------+...........
..........|.........................|...........
..+-------+--------+........+-------+--------+..
..|     Common::   |........|     Common::   |..
..|     Visual     |........|   Structural   |..
..+----------------+........+----------------+..
..|      ...       |........|      ...       |..
..+----------------+........+----------------+..
................................................

Figure 1
</code>```

In this, not yet certified, Design Pattern,
SEVERAL SIMILAR HIERARCHIES, ARE MERGED, INTO A SINGLE HIERARCHY,
and each shared or common class is extended by subclassing.

Note, that this solution is complex,
because you are already dealing with several hierarchies,
therefore is a complex scenario.

1 The Root Class

In each hierarchy there is a shared "root" class.

In your case, there is an independent "Composite" class,
for each hierarchy, that can have some similar properties,
and some similar methods.

Some of those member can be merged,
some of those members can not be merged.

So, what a developer can do, is to make a base root class,
and subclass the equivalent case for each hierarchy.

In Figure 2, you can see a diagram just for this class,
in which each class, keeps it namespace.

The members, are omitted, by now.

```<code>................................................
...............+-------+--------+...............
...............|     Common::   |...............
...............|    Composite   |...............
...............+----------------+...............
...............|      ...       |...............
...............+-------+--------+...............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
..........+------------+------------+...........
..........|.........................|...........
..+-------+--------+........+-------+--------+..
..|     Canvas::   |........|      SVG::     |..
..|    Composite   |........|    Composite   |..
..+----------------+........+----------------+..
..|      ...       |........|      ...       |..
..+----------------+........+----------------+..
................................................

Figure 2
</code>```

As, you may note, each "Composite" classe is no longer in a separate hierarchy, but, merged into a single shared or common hierarchy.

Then, let's add the members, those that are the same,
can be move to the superclass, and those that are different,
to each base class.

And as you already know, "virtual" or "overloaded" methods are defined in the base class,
but, replaced in the subclasses. Like Figure 3.

```<code>................................................
.............+--------------------+.............
.............|       Common::     |.............
.............|      Composite     |.............
.............+--------------------+.............
.............| [+] void AddChild()|.............
.............+---------+----------+.............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
..........+------------+------------+...........
..........|.........................|...........
..+-------+--------+........+-------+--------+..
..|     Canvas::   |........|      SVG::     |..
..|    Composite   |........|    Composite   |..
..+----------------+........+----------------+..
..|      ...       |........|      ...       |..
..+----------------+........+----------------+..
................................................

Figure 3
</code>```

Note that there are maybe some classes without members,
and, you may be tempted to remove those classes,
DONT. They are called "Hollow Classes", "Enumerative Classes",
and other names.

2 The Subclasses

Let's go back to to the first diagram.
Each "Composite" class, had a "Viewee" subclass,
in each hierarchy.

The process is repeated for each class. Note than Figure 4,
the "Common::Viewee" class descend from the "Common::Composite",
but, for simplicity, the "Common::Composite" class is omitted,
from the diagram.

```<code>................................................
.............+--------------------+.............
.............|       Common::     |.............
.............|       Viewee       |.............
.............+--------------------+.............
.............|        ...         |.............
.............+---------+----------+.............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
..........+------------+------------+...........
..........|.........................|...........
..+-------+--------+........+-------+--------+..
..|     Canvas::   |........|      SVG::     |..
..|     Viewee     |........|     Viewee     |..
..+----------------+........+----------------+..
..|      ...       |........|      ...       |..
..+----------------+........+----------------+..
................................................

Figure 4
</code>```

You will note, that "Canvas::Viewee" and "SVG::Viewee",
DOES NOT LONGER descend from its respective "Composite",
but, from the common "Common::Viewee", instead.

You can add the members, now.

```<code>......................................................
.........+------------------------------+.............
.........|            Common::          |.............
.........|            Viewee            |.............
.........+------------------------------+.............
.........| [+] bool Validate()          |.............
.........| [+] Rect GetAbsoluteBounds() |.............
.........+-------------+----------------+.............
.......................|..............................
.......................^..............................
....................../.\.............................
.....................+-+-+............................
.......................|..............................
..........+------------+----------------+.............
..........|.............................|.............
..+-------+---------+........+----------+----------+..
..|      Canvas::   |........|         SVG::       |..
..|      Viewee     |........|        Viewee       |..
..+-----------------+........+---------------------+..
..|                 |........| [+] Viewee Element  |..
..+-----------------+........+---------------------+..
..| [+] void Paint()|........| [+] void addChild() |..
..+-----------------+........+---------------------+..
......................................................

Figure 5
</code>```

3 Repeat the Process

The process will continue, for each class,
"Canvas::Visual" will not descend from "Canvas::Viewee",
buit from "Commons::Visual",
"Canvas::Structural" will not descend from "Canvas::Viewee",
buit from "Commons::Structural",  and so on.

4 The 3D Hierarchy Diagram

You will finish getting sort of a 3D diagram,
with several layers, the top layer, has the "Common" hierarchy
and the bottom layers, has each additional hierarchy.

Your original independent class hierarchies, where something similar to this (Figure 6) :

```<code>.................................................
..+-----------------+.......+-----------------+..
..|      Common::   |.......|       SVG::     |..
..|     Composite   |.......|     Composite   |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+--------+--------+..
...........|.........................|...........
...........^.........................^...........
........../.\......................./.\..........
.........+-+-+.....................+-+-+.........
...........|.........................|...........
..+--------+--------+.......+--------+--------+..
..|      Common::   |.......|       SVG::     |..
..|      Viewee     |.......|      Viewee     |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+--------+--------+..
...........|.........................|...........
...........^.........................^...........
........../.\......................./.\..........
.........+-+-+.....................+-+-+.........
...........|.........................|...........
..+--------+--------+.......+--------+--------+..
..|      Common::   |.......|       SVG::     |..
..|      Visual     |.......|      Visual     |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+--------+--------+..
...........|.........................|...........
...........^.........................^...........
........../.\......................./.\..........
.........+-+-+.....................+-+-+.........
...........|.........................|...........
..+--------+--------+.......+--------+--------+..
..|      Common::   |.......|       SVG::     |..
..|       Rect      |.......|       Rect      |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+-----------------+.......+-----------------+..
.................................................

Figure 6
</code>```

Note that some classes are omitted, and the whole "Canvas" hierarchy is omitted, for simplicitly.

The final integrated class hierarchy may be something similar to this:

```<code>.................................................
..+-----------------+.../+..+-----------------+..
..|      Common::   +--<.+--+       SVG::     |..
..|     Composite   |...\+..|     Composite   |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+-----------------+..
...........|.....................................
...........^.....................................
........../.\....................................
.........+-+-+...................................
...........|.....................................
..+--------+--------+.../+..+-----------------+..
..|      Common::   +--<.+--+       SVG::     |..
..|      Viewee     |...\+..|      Viewee     |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+-----------------+..
...........|.....................................
...........^.....................................
........../.\....................................
.........+-+-+...................................
...........|.....................................
..+--------+--------+.../+..+-----------------+..
..|      Common::   +--<.+--+       SVG::     |..
..|      Visual     |...\+..|      Visual     |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+-----------------+..
...........|.....................................
...........^.....................................
........../.\....................................
.........+-+-+...................................
...........|.....................................
..+--------+--------+.../+..+-----------------+..
..|      Common::   +--<.+--+       SVG::     |..
..|       Rect      |...\+..|       Rect      |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+-----------------+.......+-----------------+..
.................................................
Figure 7
</code>```

Note that some classes are omitted, and the whole "Canvas" classes are omitted, for simplicitly, but, will be similar to the "SVG" classes.

The "Common" classes could be represented as a single layer of a 3D diagram, the "SVG" classes in another layer, and the "Canvas" classes, in a third layer.

Check, that each layer is related to the first one,
in which, each class has a parent class of the "Common" hierarchy.

The code implementation may require to use either,
interface inheritance, class inheritance, or "mixins",
depending in what your Programming Language supports.

Summary

As any programming solution, do not rush into optimization, optimization is very important, yet, a bad optimization, may become a bigger problem, than the original problem.

I do not recommend apply either "Solution 1" or "Solution 2".

In "Solution 1" does not apply, because, the inheritance, is required in each case.

"Solution 2", "Mixins" may be applied, but, after designing the classes and hierarchies.

Mixins, are an alternative for interface-based inheritance,
or class-based multiple inheritance.

My proposed, Solution 3, is called sometimes the "Parallel Hierarchy" Design Pattern or "Dual Hierarchy" Design Pattern.

Many developers / designers won't agree with it, and believe it shouldn't exist. But, I have used by miself, and other developers, as a common solution for problems, like the one of your question.

Another missing thing. In your previous solutions, the main issue was not wheter to use "mixins" or "interfaces", but, to refine, first, the model of your classes, and later use an existing Programming Language feature.

Body:
Quick Overview

Solution 3: The "Parallel Class Hierarchy" Software Design Pattern is your friend.

Long Extended Answer

Your design STARTED RIGHT. It can be optimized, some classes or members may be removed, but, the "parallel hierarchy" idea you are applying to solve a problem IS RIGHT.

Have deal with the same concept several times, usually in control hierarchies.

After a while, I ENDED DOING THE SAME SOLUTION THAN OTHER DEVELOPERS, that is called sometimes the "Parallel Hierarchy" Design Pattern or "Dual Hierarchy" Design Pattern.

(1) Have you ever split a single class into a single hierarchy of classes ?

(2) Have you ever split a single class into several classes, without a hierarchy ?

If you have applied these previous solutions, separately, then they are a way to solve some problems.

But, what if we combine these two solutions, simultaneously ?

Combine them, and, you'll get this "Design Pattern" .

Implementation

Now, let's apply the "Parallel Class Hierarchy" Software Design Pattern,
to your case.

You currently have 2 or more independent hierarchies of classes,
that are very similar, have similar associations or purpouse,
have similar properties or methods.

You wish to avoid having duplicated code or members ("consistency"),
yet, you can't merge this classes directly into a single one,
due to the differences among them.

So, your hierarchies are very similar to this figure,
but, yet, there are more than one:

................................................
...............+----------------+...............
...............|     Common::   |...............
...............|    Composite   |...............
...............+----------------+...............
...............|      ...       |...............
...............+-------+--------+...............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
...............+-------+--------+...............
...............|     Common::   |...............
...............|     Viewee     |...............
...............+----------------+...............
...............|      ...       |...............
...............+-------+--------+...............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
..........+------------+------------+...........
..........|.........................|...........
..+-------+--------+........+-------+--------+..
..|     Common::   |........|     Common::   |..
..|     Visual     |........|   Structural   |..
..+----------------+........+----------------+..
..|      ...       |........|      ...       |..
..+----------------+........+----------------+..
................................................

Figure 1

In this, not yet certified, Design Pattern,
SEVERAL SIMILAR HIERARCHIES, ARE MERGED, INTO A SINGLE HIERARCHY,
and each shared or common class is extended by subclassing.

Note, that this solution is complex,
because you are already dealing with several hierarchies,
therefore is a complex scenario.

1 The Root Class

In each hierarchy there is a shared "root" class.

In your case, there is an independent "Composite" class,
for each hierarchy, that can have some similar properties,
and some similar methods.

Some of those member can be merged,
some of those members can not be merged.

So, what a developer can do, is to make a base root class,
and subclass the equivalent case for each hierarchy.

In Figure 2, you can see a diagram just for this class,
in which each class, keeps it namespace.

The members, are omitted, by now.

................................................
...............+-------+--------+...............
...............|     Common::   |...............
...............|    Composite   |...............
...............+----------------+...............
...............|      ...       |...............
...............+-------+--------+...............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
..........+------------+------------+...........
..........|.........................|...........
..+-------+--------+........+-------+--------+..
..|     Canvas::   |........|      SVG::     |..
..|    Composite   |........|    Composite   |..
..+----------------+........+----------------+..
..|      ...       |........|      ...       |..
..+----------------+........+----------------+..
................................................

Figure 2

As, you may note, each "Composite" classe is no longer in a separate hierarchy, but, merged into a single shared or common hierarchy.

Then, let's add the members, those that are the same,
can be move to the superclass, and those that are different,
to each base class.

And as you already know, "virtual" or "overloaded" methods are defined in the base class,
but, replaced in the subclasses. Like Figure 3.

................................................
.............+--------------------+.............
.............|       Common::     |.............
.............|      Composite     |.............
.............+--------------------+.............
.............| [+] void AddChild()|.............
.............+---------+----------+.............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
..........+------------+------------+...........
..........|.........................|...........
..+-------+--------+........+-------+--------+..
..|     Canvas::   |........|      SVG::     |..
..|    Composite   |........|    Composite   |..
..+----------------+........+----------------+..
..|      ...       |........|      ...       |..
..+----------------+........+----------------+..
................................................

Figure 3

Note that there are maybe some classes without members,
and, you may be tempted to remove those classes,
DONT. They are called "Hollow Classes", "Enumerative Classes",
and other names.

2 The Subclasses

Let's go back to to the first diagram.
Each "Composite" class, had a "Viewee" subclass,
in each hierarchy.

The process is repeated for each class. Note than Figure 4,
the "Common::Viewee" class descend from the "Common::Composite",
but, for simplicity, the "Common::Composite" class is omitted,
from the diagram.

................................................
.............+--------------------+.............
.............|       Common::     |.............
.............|       Viewee       |.............
.............+--------------------+.............
.............|        ...         |.............
.............+---------+----------+.............
.......................|........................
.......................^........................
....................../.\.......................
.....................+-+-+......................
.......................|........................
..........+------------+------------+...........
..........|.........................|...........
..+-------+--------+........+-------+--------+..
..|     Canvas::   |........|      SVG::     |..
..|     Viewee     |........|     Viewee     |..
..+----------------+........+----------------+..
..|      ...       |........|      ...       |..
..+----------------+........+----------------+..
................................................

Figure 4

You will note, that "Canvas::Viewee" and "SVG::Viewee",
DOES NOT LONGER descend from its respective "Composite",
but, from the common "Common::Viewee", instead.

You can add the members, now.

......................................................
.........+------------------------------+.............
.........|            Common::          |.............
.........|            Viewee            |.............
.........+------------------------------+.............
.........| [+] bool Validate()          |.............
.........| [+] Rect GetAbsoluteBounds() |.............
.........+-------------+----------------+.............
.......................|..............................
.......................^..............................
....................../.\.............................
.....................+-+-+............................
.......................|..............................
..........+------------+----------------+.............
..........|.............................|.............
..+-------+---------+........+----------+----------+..
..|      Canvas::   |........|         SVG::       |..
..|      Viewee     |........|        Viewee       |..
..+-----------------+........+---------------------+..
..|                 |........| [+] Viewee Element  |..
..+-----------------+........+---------------------+..
..| [+] void Paint()|........| [+] void addChild() |..
..+-----------------+........+---------------------+..
......................................................

Figure 5

3 Repeat the Process

The process will continue, for each class,
"Canvas::Visual" will not descend from "Canvas::Viewee",
buit from "Commons::Visual",
"Canvas::Structural" will not descend from "Canvas::Viewee",
buit from "Commons::Structural",  and so on.

4 The 3D Hierarchy Diagram

You will finish getting sort of a 3D diagram,
with several layers, the top layer, has the "Common" hierarchy
and the bottom layers, has each additional hierarchy.

Your original independent class hierarchies, where something similar to this (Figure 6) :

.................................................
..+-----------------+.......+-----------------+..
..|      Common::   |.......|       SVG::     |..
..|     Composite   |.......|     Composite   |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+--------+--------+..
...........|.........................|...........
...........^.........................^...........
........../.\......................./.\..........
.........+-+-+.....................+-+-+.........
...........|.........................|...........
..+--------+--------+.......+--------+--------+..
..|      Common::   |.......|       SVG::     |..
..|      Viewee     |.......|      Viewee     |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+--------+--------+..
...........|.........................|...........
...........^.........................^...........
........../.\......................./.\..........
.........+-+-+.....................+-+-+.........
...........|.........................|...........
..+--------+--------+.......+--------+--------+..
..|      Common::   |.......|       SVG::     |..
..|      Visual     |.......|      Visual     |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+--------+--------+..
...........|.........................|...........
...........^.........................^...........
........../.\......................./.\..........
.........+-+-+.....................+-+-+.........
...........|.........................|...........
..+--------+--------+.......+--------+--------+..
..|      Common::   |.......|       SVG::     |..
..|       Rect      |.......|       Rect      |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+-----------------+.......+-----------------+..
.................................................

Figure 6

Note that some classes are omitted, and the whole "Canvas" hierarchy is omitted, for simplicitly.

The final integrated class hierarchy may be something similar to this:

.................................................
..+-----------------+.../+..+-----------------+..
..|      Common::   +--<.+--+       SVG::     |..
..|     Composite   |...\+..|     Composite   |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+-----------------+..
...........|.....................................
...........^.....................................
........../.\....................................
.........+-+-+...................................
...........|.....................................
..+--------+--------+.../+..+-----------------+..
..|      Common::   +--<.+--+       SVG::     |..
..|      Viewee     |...\+..|      Viewee     |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+-----------------+..
...........|.....................................
...........^.....................................
........../.\....................................
.........+-+-+...................................
...........|.....................................
..+--------+--------+.../+..+-----------------+..
..|      Common::   +--<.+--+       SVG::     |..
..|      Visual     |...\+..|      Visual     |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+--------+--------+.......+-----------------+..
...........|.....................................
...........^.....................................
........../.\....................................
.........+-+-+...................................
...........|.....................................
..+--------+--------+.../+..+-----------------+..
..|      Common::   +--<.+--+       SVG::     |..
..|       Rect      |...\+..|       Rect      |..
..+-----------------+.......+-----------------+..
..|       ...       |.......|       ...       |..
..+-----------------+.......+-----------------+..
.................................................
Figure 7

Note that some classes are omitted, and the whole "Canvas" classes are omitted, for simplicitly, but, will be similar to the "SVG" classes.

The "Common" classes could be represented as a single layer of a 3D diagram, the "SVG" classes in another layer, and the "Canvas" classes, in a third layer.

Check, that each layer is related to the first one,
in which, each class has a parent class of the "Common" hierarchy.

The code implementation may require to use either,
interface inheritance, class inheritance, or "mixins",
depending in what your Programming Language supports.

Summary

As any programming solution, do not rush into optimization, optimization is very important, yet, a bad optimization, may become a bigger problem, than the original problem.

I do not recommend apply either "Solution 1" or "Solution 2".

In "Solution 1" does not apply, because, the inheritance, is required in each case.

"Solution 2", "Mixins" may be applied, but, after designing the classes and hierarchies.

Mixins, are an alternative for interface-based inheritance,
or class-based multiple inheritance.

My proposed, Solution 3, is called sometimes the "Parallel Hierarchy" Design Pattern or "Dual Hierarchy" Design Pattern.

Many developers / designers won't agree with it, and believe it shouldn't exist. But, I have used by miself, and other developers, as a common solution for problems, like the one of your question.

Another missing thing. In your previous solutions, the main issue was not wheter to use "mixins" or "interfaces", but, to refine, first, the model of your classes, and later use an existing Programming Language feature.


问:
In a byte, each additional bit doubles the representable states, but does it double memory?
A friend asked me whether adding a single bit more memory doubles the amount of memory you have, as the bit doubles the amount of representable states.

My brain got stuck thinking about it.

Doubling the amount of bits doubles the amount of states we can simultaneously represent.

Am I performing a category error. What does it mean to double memory?

答:
Look at your hands.

With the five fingers on one hand you can represent 32 different numbers using a binary encoding.

With the ten fingers on both hands you can represent 32 x 32 = 1,024 different numbers.

Double the memory means the number of possible states is squared.

And I'd love to see you trying to represent a million numbers using fingers and toes.


问:
Is the purpose behind code being 'idiomatic' to reduce cognitive overhead?
I'm trying to explain to someone that the way they've written the code makes it hard to understand, and if you refactor it then it's easier to read. This style of code I'm driving at is commonly called 'idiomatic' code'.

But the phrase idiomatic code brings with it baggage of moral correctness, which is not a great motivator to get people to change their coding style. A more positive way of saying this is code that follows the common style - but to a critical thinker that comes across as herd mentality reasoning.

The way I've come up with explaining this idea in a way that motivates people to change their code is:

writing the code in such a way that it reduces the cognitive overhead of the reader (eg I can't remember if this is the first kind of vector - or the 5th kind of vector)

code that makes it easier to understand the intent (eg what is this vector for?)

(As an aside, I'm aware the book The Joy of Clojure, prior to its first publishing, had the draft title Idiomatic Clojure. So it would seem a reason for making code 'idiomatic', to 'bring joy' to the reader).

My question is: Is the purpose behind code being 'idiomatic' to reduce cognitive overhead?

答:
First, I'm not sure that there is any sort of "moral correctness" in the term "idiomatic".  The plain dictionary definition is simply

peculiar to or characteristic of a particular language or dialect:
  idiomatic French.

Yes, idiomatic code generally reduces cognitive overhead, particularly at interface definitions where the standard libraries and any third-party libraries the project needs are (virtually) all idiomatic.

As a selling point, though, I'd focus on what reducing cognitive overhead does for you.  It makes it easier for programmers to spot mistakes because they're not attempting to unravel code written in a unique style to figure out where it is subtly off by one or mishandling an edge case.  It makes it easier to review other people's code which makes it more likely that the team will do real reviews that identify real issues rather than arguing about syntax.

Beyond reducing cognitive overhead, idiomatic code is generally more efficient code.  Most idioms in a particular language evolve because the language is designed to approach problems in a particular way.  The compilers or interpreters that you're using will focus their optimizations on idiomatic code.  If you use a language where recursion is the idiomatic way to structure a piece of code, for example, you can be all but certain that your compiler implements tail recursion.  If you use a language where recursion is non-idiomatic, that is much less likely.  It's unlikely that tail recursion can't be implemented everywhere but most compiler writers aren't going to be focused on things that don't happen commonly.


答:
I'm not sure where you get the idea that idioms have any moral connotations. Idioms are just a way to express things. They are patterns at a scale larger than individual words or phrases.

If I told you that one must howl with the wolves, you wouldn't know what I meant, even though that is a well-known German idiom. If, OTOH, I told you, when in Rome, do as the Romans do, you'd know immediately what I am talking about, because I used the proper English idiom.

Computer languages are no different.

Actually, an alternative name for "idiom" in the programming world is "implementation pattern". This relates the idea to the idea of patterns, which comes from the architect (brick-and-mortar not bits-and-bytes) Christopher Alexander. Most programmers know about Design Patterns, some know about Architecture Patterns, which are patterns on a scale larger than Design Patterns. Idioms are patterns on a scale smaller than design patterns.

Body:
I'm trying to explain to someone that the way they've written the code makes it hard to understand, and if you refactor it then it's easier to read. This style of code I'm driving at is commonly called 'idiomatic' code'.

But the phrase idiomatic code brings with it baggage of moral correctness, which is not a great motivator to get people to change their coding style. A more positive way of saying this is code that follows the common style - but to a critical thinker that comes across as herd mentality reasoning.

The way I've come up with explaining this idea in a way that motivates people to change their code is:

writing the code in such a way that it reduces the cognitive overhead of the reader (eg I can't remember if this is the first kind of vector - or the 5th kind of vector)

code that makes it easier to understand the intent (eg what is this vector for?)

(As an aside, I'm aware the book The Joy of Clojure, prior to its first publishing, had the draft title Idiomatic Clojure. So it would seem a reason for making code 'idiomatic', to 'bring joy' to the reader).

My question is: Is the purpose behind code being 'idiomatic' to reduce cognitive overhead?


问:
Should I notify my colleagues when I find a bug in their code?
If I am assigned a bug, I sometimes check version control to see when it was introduced. Should I notify the developer that introduced the bug, even if I already fixed it? The advantage is that it could help learning but the disadvantage is it could seem like criticism</p>

答: Just make sure it is constructive criticism, and tell him how you fixed the bug, so he doesn't make the bug again.</p>


答:
If it's part of your process, then yes. If it's specifically not part of your process, then no.

If it's not specified, the best thing is to ask the developers if they would like you to notify them if you fix bugs in their code and to respect their individual wishes.

If you don't want to do that or it's too complicated, you can let them know that you found a bug. If you think that they will feel criticized, you can pitch it as "I fixed this thing that you had worked on before, and I am now appealing to your prior knowledge to make sure that I have considered all the subtleties in doing so." In other words, you're not saying their code was screwed up, but that you respect that their deeply-thought solution might be more complex than your own superficial understanding, and you want their expert consideration for the repair work you undertook. This has the advantage of making sure that they are aware of the code defect (and subsequent learning opportunity) without being affronted.

Title: Should I notify my colleagues when I find a bug in their code?

Body: If I am assigned a bug, I sometimes check version control to see when it was introduced. Should I notify the developer that introduced the bug, even if I already fixed it? The advantage is that it could help learning but the disadvantage is it could seem like criticism</p>


问:
Is it possible to mock and inject traits in PHPUnit?
I need to extend a third party class I cannot modify. The class's dependencies are for the most part injected through the constructor, making them easy to mock. However the class also uses methods from a trait that call global services directly, destroying test isolation. Here's a code sample that illustrates the problem:

```<code>trait SomeTrait {
  public function irrelevantTraitMethod() {
    throw new \Exception('Some undesirable behavior.');
  }
}

class SomeSystemUnderTest {
  use SomeTrait;
  public function methodToTest($input) {
    $this->irrelevantTraitMethod();
    return $input;
  }
}

class MockWithTraitTest extends \PHPUnit_Framework_TestCase {
  public function testMethodToTest() {
    $sut = new SomeSystemUnderTest();
    $this->assertSame(123, $sut->methodToTest(123)); // Unexpected exception!
  }
}
</code>```

How does one deal with a situation like this in PHPUnit? Can traits be mocked and injected somehow? The only solution I've found is to mock the SUT itself and just nullify the troublesome methods from the trait, leaving the actual SUT methods intact. But that doesn't feel right.

答:
Hopefully someone will provide a better answer at some point, but in the meantime--in case anyone else is dealing with the same issue--here's the workaround I referred to in the question. Given the same trait and SUT, the below test will pass. It creates a "partial mock" of the SUT, replacing only the trait method and leaving the rest intact to exercise and assert on.

```<code>class MockWithTraitTest extends \PHPUnit_Framework_TestCase {
  public function testMethodToTest() {
    /** @var \SomeSystemUnderTest|\PHPUnit_Framework_MockObject_MockObject $sut */
    $sut = $this->getMockBuilder('\SomeSystemUnderTest')
      ->setMethods(array('irrelevantTraitMethod'))
      ->getMock();
    $this->assertSame(123, $sut->methodToTest(123)); // OK.
  }
}
</code>```

This approach works, but I dislike it because I'm afraid it requires too tight coupling to the implementation and could lead to fragile tests. (What if I add another method to the trait, say for logging, and use it in the SUT? It will cause irrelevant test failures until I update all my mocks.) I would much prefer to be able to mock the whole trait.

Body:
Hopefully someone will provide a better answer at some point, but in the meantime--in case anyone else is dealing with the same issue--here's the workaround I referred to in the question. Given the same trait and SUT, the below test will pass. It creates a "partial mock" of the SUT, replacing only the trait method and leaving the rest intact to exercise and assert on.

class MockWithTraitTest extends \PHPUnit_Framework_TestCase {
  public function testMethodToTest() {
    /** @var \SomeSystemUnderTest|\PHPUnit_Framework_MockObject_MockObject $sut */
    $sut = $this->getMockBuilder('\SomeSystemUnderTest')
      ->setMethods(array('irrelevantTraitMethod'))
      ->getMock();
    $this->assertSame(123, $sut->methodToTest(123)); // OK.
  }
}

This approach works, but I dislike it because I'm afraid it requires too tight coupling to the implementation and could lead to fragile tests. (What if I add another method to the trait, say for logging, and use it in the SUT? It will cause irrelevant test failures until I update all my mocks.) I would much prefer to be able to mock the whole trait.


问:
(Re)structuring a Qt Project
A PySide project I've been working on for a while now has started to grow to a point where it's becoming large enough that I've had to step back and re-think the overall design.

I've spent some time with both Flask and Django, so I'm familiar with the MVC design pattern conceptually, but had the advantage (or maybe disadvantage!) of so many great examples of how to structure and layout Flask/Django projects that I didn't really have to give it a lot of thought. Now that I’m trying to slot my own project into this type of design pattern for the first time, I’m finding it tough to envision how everything should be laid out. Spending some time reading about the MVC pattern I was a little pleased to see that I had partly gone down that path without consciously trying, but had made things unnecessarily complicated and coupled.

There is nothing particularly special about my program  – a user interacts with a UI which retrieves data from a database for either viewing or processing.

Trying to map this to a MVC structure, I came up with:

Controller: Most of the actual application functionality – user interacts with a widget on the UI, the controller takes this input and actions the appropriate operations – retrieve data from the model and send it to the View to display on the UI, run operations on it and send back to the model to update in the database, etc. In Qt speak, widget signals connected to Controller methods involving pulling data from the model (usually) for processing, or view via the View.

Model: Insert/updates/selects data from the database as directed by the Controller.

View: The actual UI work is done here – updating widget stylesheets (core function of the program) and also formatting data passed to the View by the Controller (from the Model) as specified by the Controller (taken from various options the user has selected on the UI) to then display to the user via display widgets. This is where most my individual object classes would come into play.

The main difference between what I’ve listed above and how I’ve been structuring my program currently is the Model/View components were more or less overlapping, with the Model retrieving data but also doing most of the formatting of the data as well.

So, am I on the right track here?

答: Yes, you are on the right track. Especially if you remove all presentation/formatting logic from the Model into the View.</p>

Title: (Re)structuring a Qt Project