Is there an OOP principle against a concrete class extending another concrete class? - oop

I have read that this should be avoided, though I can't recall the source. Inheritance should used with abstract classes in the middle of the hierarchy, and concrete classes showing only as leaves.
Where can I find a good explanation of the reasoning behind this? (Opposite opinions are also welcome)

This shouldn't be taken too strictly.
I think the underlying idea is more to focus on programming to an interface, either a pure interface or an abstract class, as this enables looser coupling of your design, polymorphism, encapsulation,...
Also mind to not violate the Liskov substitution principle

Related

Can i use inheritance instead of implement an interface in strategy pattern?

From a picture, Can i use inheritance instead of implement an interface?
I mean change from "ConcreteStrategyA and ConcreteStrategyB implements Strategy Interface" to "ConcreteStrategyA and ConcreteStrategyB extends Strategy Class"
Is it still work well or have some problem?
If it still work well my next question is "Why most people prefer to use interface?"
Well technically from a Design pattern perspective with the Strategy pattern, the concrete Strategies need to implement (I mean write code for, not the interface implements thing) a common contract which the Strategy Context is aware of. This is the primary backbone of Strategy pattern philosophy. The adherence to the common contract is what allows the Strategy context to replace the concrete strategies based on some runtime feature. This pattern ideology is what we loosely call Polymorphism in OOP parlance.
Now in Java you can implement his polymorphic strategy either as an interface or as inheritance. For interface you have given the example in the question itself. For inheritance as long as the contract holds between subclasses (something like a base abstract class with an abstract contract which subclasses implement to provide concrete strategy implementations) you can implement Strategy pattern in inheritance as well.
Now thinking about it from OOP perspective. For OOP inheritance is something which a subclass inherits from a super class. The subclass automatically owns and thus demonstrates that inherited generic behavior but it has a choice to make that behavior more specific to its own type. Thus multiple subclasses can override the same behavior and make bits of it more specific to their use. But this chain becomes cumbersome to manage when it gets too long or when subclasses try to inherit the behaviors which don't apply to them logically.
Thus it makes more sense to implement Strategy pattern using interfaces as against inheritance.
Absolutely. Inheritance is most often used with an abstract base class, when you want your derived strategies to share some common code.
People prefer to use interfaces or abstract classes over concrete base classes because :
With a Dependency Inversion approach, a class needs loose coupling to its Strategy. It only needs to know that the Strategy fulfills a contract, but doesn't want to know about its implementation details. Interfaces and abstract classes are an elegant and minimal way to define a contract without specifying the implementation.
It doesn't make sense to instantiate the base Strategy class most of the time, because it's a general, abstract concept -- in fact, it's better if you forbid instantiating it.
There are no technical problems.
However, a class can only extend one base class but it can implement multiple interfaces. So if you want to, let's say, change your inheritance structure in the future it is easier if you choose to implement an interface instead.
As you know a design pattern is "a general solution to a commonly occurring problem". It just describe a general solution without indications concerning implementation details.
If your problem requires a class in place of the interface, there is nothing wrong replacing it with a concrete (or abstract) class.
Using an interface in the pattern UML is a way to say: "you have to expose this set of public methods".
So, no problem using your approach. As an alternative you could leave the Strategy interface and implement it in a StrategyImpl class, then you can inherit this class in your ConcreteStrategyA and ConcreteStrategyB classes.

Why is the key idea behind OOP polymorphism?

In the book C++ Primer, the author wrote: "The key idea behind OOP is polymorphism". I am not sure I understand what the author meant. What about other important stuff: Abstract, Inheritance, etc.
Can anyone elaborate on that, please?
Edit:
I do not ask "What is polymorphism". I am asking "Why polymorphism is the key behind OOP"? Why not inheritance is the key?
I'm not sure that it's the key to OOP. That's just someone's opinion.
I think there are four keys: abstract data types, encapsulation, inheritance, and polymorphism. They belong together.
Each idea depends on the previous ones. ADT is the only one that stands on its own. Encapsulation needs ADT. Polymorphism requires inheritance.
Polymorphism helps to eliminate if, switch, and case statements. You don't have to write code to figure out what to do based on object type; the virtual table simply calls the right method for you behind the scenes.
The Author may be saying this because :
When class B inherits from A then class B can be typecasted to A ----> Which is also called as polymorohism. So Inheritance directly allows polymorphism.
When A implements interface I*something* then A can rome around as I*something* which is also called as polymorphism. So Interfaces makes polymorphism come true.
Abstract : Abstract class is just another class which cannt be instantiated and act as base class (generally). Non abstract Child classes can be type casted to Abstract class and hence polymorphism.
So infact its seen that most concept of OOP can be seen as polymorphism and due to this Author might have said that.
Generally it's the idea of creating objects (with their fields, methods, etc) which can have more than one form - derived (abstract) classes, implemented interfaces and so on.
And you would have had your answer in few seconds only, if you would've had asked google, wikipedia and so on, first ;)

Are interfaces redundant if using abstracts as an interface?

I'm reading through Design Patterns by GoF and I'm starting to wonder. Are interfaces redundant if you're using an abstract as the interface in languages like C#? Let's put multiple inheritance aside for a moment, as I understand you can only achieve that (in C#) through interfaces.
I'm trying to apply this logic to DDD in C#. Almost every example and implementation I've ever seen uses interfaces. I'm starting to wonder why. Could the abstract class be used instead? It seems to me that this would be a more robust solution, but then again I could be missing something, which is why I'm asking here.
Summary:
Question 1: In the context of OOP with a language that only supports single inheritance, if designed properly what are some uses
of interfaces over the abstract class?
Question 2: In the context of DDD, if designed properly what are the uses of interfaces over the abstract class?
Note:
I've read through all the similar questions listed, but none seem to give me an answer. If I missed one, please let me know.
For question 1: regardless of support for multiple inheritance interfaces are contract specifications, abstract classes are base classes.
Interfaces provide a way for a class to specify a set of capabilities ( think IDisposable, IEnumerable, etc ) and it's recommended that they obey the Interface Segregation Principle.
Abstract classes should implement a concept that can be extended, or that can have different implementations depending on the context ( think HttpContextBase, AbstractButton etc ).
The biggest difference between interfaces and abstract classes is conceptual. You can argue that, except inheritance, an interface is the same as an abstract class with only abstract methods, but conceptually they represent different things.
As for question 2: in the context of DDD interfaces are implementations details. I dare say you can do DDD and not use interfaces or abstract classes, or even inheritance. As long as you have your bounded contexts, aggregates, entities and VOs well defined.
In conclusion, when you try to express a contract use an interface, when you want to indicate that your class has some capability, implement an interface. When you have a concept for which you can provide more implementations depending on context, use a base class ( abstract or not ).
When you think about it like this, the decision of the language makers ( c# ) to allow only single inheritance, but allow implementation of multiple interfaces makes a lot of sense.
The advantage of Interfaces is precisely that there is no multiple-inheritance. By using an Interface you can allow classes like Forms, UserControls, Components, etc to participate in interactions that would otherwise be diffucult/impossible.
I recommend doing both. I usually create an interface, and (if possible) then create an abstract class that inherits that interface to provde any common or default implementaion of that interface. This gives you the best of both worlds.
interfaces are not redundant. an interface is independent of implementation while abstract classes are implementation. code that uses an interface does not have to be changed or recompiled if some implementation class changes.
the advantage is above. if you are doing ddd, start out with concrete classes and write some tests. refactor common stuff into base classes (some will be abstract). if there is a reason to make an interface go ahead and do so. repeat until done.

How to move away from Inheritance

I've searched in here and other forums and couldn't find a good answer..
I kind of know that Extending classes isn't the best of practices. And that I should use Interfaces more. my problem is that usually I start creating Interfaces and then move to Abstract classes because there's always some functionality that I want implemented on a super class so that I don't have to replicate it in every child classes.
For instance, I have a Vehicle class and the Car and Bike child classes. a lot of functionality could be implemented on the Vehicle class, such as Move() and Stop(), so what would be the best practice to keep the architecture clean, avoid code repetition and use Interfaces instead of Inheritance?
Thanks a lot!
(if you have no idea why I'm asking this you may read this interesting article: http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html)
Inheritance ('extending classes') imposes significant limitations on class design and I'm not sure the use of interfaces as a replacement for inheritance is the best idea since it fails the DRY test.
These days, Composition is favored over Inheritance, so you might consider this post: Prefer composition over inheritance?
Interesting question. Everyone has different approaches. But it all based on personal experience and choice.
Usually, i start with an interface, then let an abstract class inherit that interface. And implement common actions there, and let others to be implemented by who ever inherits this class.
This give few advantageous based on by experience,
1.During function calls you can pass the elements as interface type or abstract class type.
2.Common variables such as ID, Names etc can be put on abstract class.
3.Easy for maintenance. For example, if you want to implement a new interface, then just implement in the abstract quickly.
If you keep in mind fundamental difference between interfaces and classes it will make it easier to decide which one to use. The difference is that interfaces represent just a protocol (usually behavioral) between objects involved, while abstract classes represent some unfinished constructions that involve some parts (data). In car example, interface is essentially a blueprint for the generic car. And abstract class would be like prefabricated specific model car body that needs to be filled with remaining parts to get final product. Interfaces don't even have to be in Java - it will not change anything - still blueprint.
Typically you would use abstract class within your specific implementation framework to provide its consumers with some basic functionality. If you just state that you never use abstract class in favor of interface - it's plain wrong from practical standpoint. What if you need 10 implementations of the same interface with 90% of the same code. Replicate code 10 times? Ok, may be you would use abstract class here but put interface on top of it. But why would you do that if you never intend to offer your class hierarchy to external consumers?
I am using word external in very wide sense - it can be just different package in your project or remote consumer.
Ultimately, many of those things are preferences and personal experiences, but I disagree with most blanket statements like extends is evil. I also prefer not to use extra classes (interfaces or abstract) unless it is required by specific parts of the design.
Just my two cents.
Inheritance allows code reuse and substitutability, but restricts polymorphism. Composition allows code reuse but not substitutability. Interfaces allow substitutability but not code reuse.
The decision of whether to use inheritance, composition, or interfaces, boils down to a few simple principles:
If one needs both code reuse and substitutability, and the restrictions imposed on polymorphism aren't too bad, use inheritance.
If one needs code reuse, but not substitutability, use composition.
If one needs substitutability, but not code reuse, or if the restrictions inheritance would impose upon polymorphism would be worse than duplicated code, use interfaces.
If one needs substitutability and code reuse, but the restrictions imposed by polymorphism would be unacceptable, use interfaces to wrap encapsulated objects.
If one needs substitutability and code reuse, and the restrictions imposed by polymorphism would not pose any immediate problem but might be problematic for future substitutable classes, derive a model base class which implements an interface, and have those classes that can derive from it do so. Avoid using variables and parameters of the class type, though--use the interface instead. If you do that, and there is a need for a substitutable class which cannot very well derive from the model base class, the new class can implement the interface without having to inherit from the base; if desired, it may implement the interface by wrapping an encapsulated instance of a derivative of the model type.
Judgment may be required in deciding whether future substitutable classes may have difficulty deriving from a base class. I tend to think approach #5 often offers the best of all worlds, though, when substitutability is required. It's often cheaper than using interfaces alone, and not much more expensive than using inheritance alone. If there is a need for future classes which are substitutable but cannot be derived from the base, it may be necessary to convert the code to use approach #5. Using approach #5 from the get-go would avoid having to refactor the code later. (Of course, if it's never necessary to substitute a class that can't derive from the base, the extra cost--slight as it may be--may end up being unnecessary).
Agree with tofutim - in your current example, move and stop on Vehicle is reasonable.
Having read the article - I think it's using powerful language to push a point... remember - inheritance is a tool to help get a job done.
But if we go with the assumption that for whatever reasons you can't / won't use the tool in this case, you can start by breaking it down into small interfaces with helper objects and/or visitors...
For example -
Vehicle types include submarine, boat, plane, car and bike. You could break it down into interfaces...
IMoveable
+ Forward()
+ Backward()
+ Left()
+ Right()
IFloatable
+ Dock()
ISink()
+ BlowAir()
IFly()
+ Takeoff()
+ Land()
And then your classes can aggregate the plethora of interfaces you've just defined.
The problem is though that you may end up duplicating some code in the car / bike class for IMoveable.Left() and IMoveable.Right(). You could factor this into a helper method and aggregate the helper... but if you follow it to its logical conclusion, you would still end up refactoring many things back into base classes.
Inheritance and Aggregation are tools... neither of which are "evil".
Hope that helps.
Do you want an answer for your specific case, or in general? In the case you described, there is nothing wrong with using an Abstract class. It doesn't make sense use an interface when all of the clients would need to implement the exact same code for Move() and Stop().
Don't believe all you read
Many times, inheritance is not bad, in fact, for data-hiding, it may be a good idea.
Basically, only use the policy of "interfaces only" when you're making a very small tree of classes, otherwise, I promise it will be a pain. Suppose you have a Person "class" (has eat() and sleep), and there are two subclasses, Mathematician (has doProblem() ) and Engineer ( buildSomething() ), then go with interfaces. If you need something like a Car class and then 56 bazillion types of cars, then go with inheritance.
IMHO.
I think, that Interfaces sometime also evil. They could be as avoidance of multiple inheritance.
But if we compare interface with abstract class, then abstract class is always more than interface. Interface is always some aspect of the class -- some viewpoint, and not whole as a class.
So I don't think you should avoid inheritance and use iterfaces everywhere -- there should be balance.

Maintainability in a class

How to ensure maintainability in a class? Can it simply be done by creating class using design patterns or is there something else involved? Also, what are the characteristics of a good method?
You won't do badly by following the SOLID and DRY principles.
SOLID is:
SRP Single responsibility principle
the notion that an object should have only a single responsibility.
OCP
Open/closed principle
the notion that “software entities … should be open for extension, but closed for modification”.
LSP
Liskov substitution principle
the notion that “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”. See also design by contract.
ISP
Interface segregation principle
the notion that “many client specific interfaces are better than one general purpose interface.”[5]
DIP
Dependency inversion principle
the notion that one should “Depend upon Abstractions. Do not depend upon concretions.”[5]
Dependency injection is one method of following this principle.
And DRY stands for Don't Repeat Yourself, meaning you should strive to remove any duplication in your code.
Put in a lot of effort to make sure you have a good interface. Once you have that, you can completely rewrite the class, if you want, without affecting any other code in the project. If your class is so big that you can't easily rewrite it, then that is an issue too.
Although Oded's answer is good for ensuring the maintainability of a program or library, this question is about class maintainability and for that, there are only two requirements... a good interface, and strong cohesion.