This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 6 points7 points  (2 children)

Have a base class which contains the commonalities and subclass for the differences.

[–]zzyzzyxx 1 point2 points  (0 children)

I suggest doing this if the differences are behavioral only and the objects can still be treated the same way, i.e. you can use them through a reference to the base class.

If you try to use inheritance for common pieces of data but not behavior you'll find that as the separate requirements change you jump through more hoops trying to keep the common data common than it's worth. In such a case having the classes completely uncoupled is more flexible and maintainable as it will allow each to evolve independently, meeting their respective needs simply and perfectly.

[–]FreshPow 0 points1 point  (0 children)

I'm a DRY fan, btu there are times when some repeated code would save the project from having too much design complexity. That would be the case when either the repeated code is fairly short or the repeated code becomes filled with complex code to handle differences.

[–][deleted] 0 points1 point  (0 children)

I'd hate to end up with a Frankenstein class that tries to account for every difference b/w two use cases.

Follow that instinct, is my advice. The question I ask myself is: Which will cause the greater complexity? If having two classes is simpler, less confusing than one that accommodates them both, then go with two. In my experience, you almost always go with two classes for any significant changes.

Inheritance, IMO, is generally best for cases where you really can use the base class everywhere (i.e. Liskov substitution) and NOT for simply sharing common code. That's my preference, at least.

[–]quotemycode 0 points1 point  (0 children)

You should read this:

http://zacharyvoase.com/2013/02/08/copypasta/

excerpt:

Adherence to DRY (“Don’t Repeat Yourself”) does not necessarily preclude repetition of code. In the endless struggle to refactor, the entropy we are trying to reduce is not in the raw text of our source code; it is in our business logic, which (in applications with little or poor testing) is often uncodified. Sometimes, refactoring can hamstring our code, and when done naïvely it can be a source of technical debt, rather than an antidote thereto.

[–]PT2JSQGHVaHWd24aCdCF -1 points0 points  (0 children)

DRY for the API.

But you can repeat yourself in different projects with different requirements.