Is it a good pattern to use inheritance to define abstract class fields? - oop

Dart Example.
abstract class Figure{
final int numberOfCorners;
Figure(this.numberOfCorners);
}
class Square extends Figure{
Square():super(4);
}
class Triangle extends Figure{
Triangle():super(3);
}
It confuses me that this is actually a narrowing. Derived classes
finally define base class field. It is the opposite of extending (adding new methods\fields). But I see this pattern regularly.
Which architectural pattern would make more sense?

There are many opinions about declaration fields in base class. In my view, it makes very tight coupling between base and derived classes. It creates a fragile and rigid relationship between classes. So I would create these fields in classes and avoid inheritance here. Read more about when your inheritance is all about attributes.
Inheritance can be violated very easily. It works fine, if it is used appropriately.
Let me show an example where inheritance misused. For example, there is a base class called “Duck” and you have method “Fly()” in base class. But not all ducks can fly. But our derived class “NotFlyingDuck” inherits method “Fly()”. And by creating derived classes “NotFlyingDuck”, we violate Liskov substitution principle.
The general rule I met is that inheritance should be used to declare behaviour in base class and all derived classes should implement this behaviour. You can read more here. So if all public methods in derived classes should be taken from base class, then it means that it is possible to use inheritance.

Related

Inheritance from non abstract class

As far as I know, the base type of the inheritance hierarchy, continence the general fields and methods that will be the essential ones in order to consider the derived classes as same type of the base type. (correct me if I'm wrong please).
So the question is, since the base type contains generalization of the sub type, shouldn't we consider all the base classes as abstract? since they only describe how a type should behave and what essential elements it should contain in order to be considers from the specified type, isn't this the true essence of an abstraction ?
If my claims are correct, then why OOP languages didn't enforce the deceleration of a base class in the inheritance chain as an abstract? why they allow us to inherit from non abstract types?
Abstract class is used to inherit in the child class. An abstract class cannot be inherited by structures. It can contains constructors or destructors. It can implement functions with non-Abstract methods.

Is "composition over inheritance" simply mean "If parent class is never be used except in child class, it should be composition"?

I read some posts about "composition over inheritance","where to use composition/inheritance" , "Is-a relationship..." or "Liskov substitution principle" for some time, but I am not sure if I get the right idea about "composition over inheritance".
Alternatively, In my experience, "composition over inheritance" seems just mean "If parent class is never be used except by child class, it should be composition", for example:
public class Parent{
}
public class Child1 extends Parent{
}
public class Child2 extends Parent{
}
If class "Parent" is never appeared at my code other than in Child1 and Child2, then Child1 and Child2 should not be the child class of Parent.
Is that right?
Composition-over-inheritance means that instead of structuring your class hierarchy using a parent class and extending child classes, you should do something like this:
class Foo {
protected bar;
protected baz;
public function Foo(Bar _bar, Baz _baz) {
bar = _bar;
baz = _baz;
}
}
In other words, instead of inheriting a bunch of functionality from a base parent class, you get this same functionality from independent objects instead which you preferably dependency inject into your class.
Why? Because it provides more flexibility. In the case of Foo extends Bar, Bar provides some base functionality which is useful for a bunch of inheriting classes. Now, who says this functionality isn't also useful for a bunch of other, unrelated classes? Should all your classes inherit from Bar? Should all common functionality be stuffed into Bar because all classes inherit from it? Please no, that just leads to fat, monolithic, unmaintainable base classes.
Instead, implement any collection of useful common methods in their own independent class. Group only functionality which is closely related, separate into different classes as makes sense. Then inject those objects into other objects to compose a new object which can use all that shared functionality without inheriting monolithic base classes or defining an abstract strict class hierarchy.
You should only inherit a class if they share the same "business logic" hierarchy. E.g., Cat extends Pet extends Animal makes perfectly logical sense. Cat extends BaseConnectionManager less so.
If you're using class hierarchies for type hinting, interfaces can serve this purpose much better and more flexibly too.
I generally find that when re-use is the goal, inheritance is attractive. However, in this situation, composition always turns out to be the better solution. For me, inheritance is best used for its polymorphism.
Inheritance is a specific tool. Composition is a general tool. Both are useful, but in different contexts.
Inheritance is useful when you want to ensure that all objects of type Foo are also, in every respect, objects of type Bar. This means more than just implementing the same methods. It means Foo objects must perfectly emulate Bar objects in every outwardly-visible respect. If they do not, then the Liskov Substitution Principle is violated, and inheritance is a poor choice for the situation at hand.
Composition is much more general. It is used to divide responsibilities among multiple classes while still allowing for properly abstracted and defined interactions between them. It does not require the specific, Liskov-like relationship I just described.
"Composition over inheritance" is just the observation that composition is a more general technique than inheritance. Because of this, composition should be the tool we reach for first in most situations, rather than inheritance. This does not mean that every use of inheritance is wrong, or even that inheritance is inherently bad. It's a way of thinking, not a coding standard.

What the need for abstract class here?

One of the interview questions which they asked me very recently.
What is an abstract class in C#?
Abstract Class - is a class which cannot be instantiated & can include abstract or instance methods, constructors etc.
Instance methods can be used for implementing common functionality for all derived classes which inherits this abstract class.
Ok...Now the question is why we need an abstract class here for implementing the common functionality. The same common functionality i can put in a base class and let the derived class can access the base class methods..right?? if thats the case, instead of having an abstract class.. can i go for base class?? or to put the common functionality in abstract class and let the derive class do access those methods?
If my base class can solve the implementing of common functionality, then why do we need an abstract class for common functionality???
Need help in proper understanding....
An abstract class is a base class - but it's a base class which typically has some abstract members. This allows you to write code in the abstract class which calls those abstract members, but without any implementation... it then forces concrete classes deriving from the abstract class to implement those members.
The benefits of having an abstract class rather than just a concrete base class where some members throw NotImplementExceptions are:
Derived classes are forced (at compile-time) to implement the relevant members
Clients can't just create an instance of the base class; they have to use a concrete class which provides the appropriate "missing" members.
As an example, the other day I wrote an abstract class class extending JsonConverter in Json.NET. The aim was for it to be a base class for any converters for structs within my project - it would handle all the nullable type conversions (and deserializing empty JSON to a null value), leaving the derived classes free to just concentrate on the type-specific part. Have a look at it (NodaConverterBase) and see if it makes things any clearer.
An Abstract Class is used as a Base class. There are times when you may want to have common functionality be implemented but not directly instantiate an instance of your Base Class Type so you would use an Abstract Class instead.
Look at it this way, if you were writing an app to keep track of zoo animals you would have classes for Monkey, Elephant, Crocodile, etc... They are all animals, so you would have them inherit a base class of Animal (because they all need basic functionality like eating, breathing, etc...). But you would never have an animal that's just an animal, so you would make Animal abstract because you would never need an instance of it.
The tricky phrase is
"partial implementation."
In addition to what you mention in your post, the abstract class does not have to implement all the functions AND the children MUST implement the unimplemented functions or be themselves declared abstract.

Benefits of using an abstract classes vs. regular class

I have decided to start doing small coding projects on my own that focus on code quality instead of code quantity and have a question about the use of abstract classes.
Now I know the differences between abstract classes and interfaces with the biggest one (I think) being that interface allow you to only define methods that need to be implemented by classes using the interface and abstract classes allowing you to define both method and members along with default method implementation if you so desire. My question is what the the main benefit of use an abstract class vs a normal class? The only real difference between the two that I can think of is that you can not create an instance of an abstract class. Are there any other differences between the two?
Strictly from a design perspective, it is best to simplify things. I believe the best way to simplify things is to use a simple analogy. Let's use an analogy of birds...
Interface: use this when you want to enforce certain functions which need to be defined. e.g. IBird has a contract for ScreamLikeABird and Fly (interface functions). But you can get more specific and have an IOstrich that has a Run contract. You may also have an IHawk that has an Attack contract...etc.
Abstract: use this when you want to enforce base functions and have base properties. e.g. Avian could be a base class for birds which may have a function called LayEgg as well as propeties called Age, Species, NumberOfChicks...etc. These things don't/shouldn't change the behavior of a bird, since all birds lay eggs...etc. But not all birds sounds the same when it scream or flies the same way (some dont even fly)....etc.... hence they should be implemented via an interface(s).
In addition to not being able to create instances of abstract classes, some languages may support having abstract methods in abstract classes - similar to interfaces, an abstract method will have to be implemented by the class inheriting from the abstract class.
The main benefit of abstract classes in my opinion is if there is some code that has to be shared between classes of the same type. Usually you could use an interface for this, but sometimes the functionality of such classes may overlap and you would end up with code duplication. In this case you can use an abstract class and just put the code there.
In OO world, abstract classes used to impose some design & implementation constraints. Nothing more. You never have to use abstract classes in any case. But there might be cases that you better impose those constraints. So what are them? Let's look at by comparing it's oo-counterparts.
Abstract classes vs interfaces
As you know, these are two of the primary concepts of inheritance.
Basically, interface is used just to declare that you're willing to inherit the underlying service and that's it. Contains no implementation & has no functionality. In that sense, interface is abstract. That's why it's a more a design constraint than an implementation constraint. Think of a headphone jack on a speaker. Each headphone needs to implement the jack interface (with start, stop, listen, turnDown, turnUp methods). Each headphone should override this interface to inherit the functionality that the speaker provides and implement accordingly.
Abstract classes, on the other hand, may include methods with an implementation. That's the basic difference and in that sense it may utilize reusing more than an interface. Moreover, they may contain private, protected & non-static fields which you can't via interfaces. You may force subclasses to implement some must-have functionalities with abstract methods (those without implementations). Abstract classes more agile than interfaces.
Of course not to mention, you may only extend one class in java in where you may implement number of interfaces.
Abstract classes vs regular classes
So why not to use regular classes then. What's the benefit of using abstract class? This is pretty simple. If you use abstract classes, you force the core functionality to be implemented by the children. As a developer, you don't need to remember that you should implement the essential functions. This is where abstract classes imposing design constraints over regular classes. Plus by making the class abstract you avoid that (incomplete) class to be created accidentally.
The only reason for declaring a class as abstract is so that it can't be instantiated. There are situations where you will have common functionality that is shared between a number of classes, but by itself that common functionality does not represent an object or represents an incomplete object. In that case, you define the common functionality as abstract so that it can't be instantiated.
in my opinion abstract classes have more use in real projects as on books. some times project managers just provide the methods declaration and you have to write code for the methods without modify the core syntax provided by manager. so that is how an abstract class is use full. in simple class method define,declared and coded in same time but not in abstract classes.
for ex:-
abstract class Test
{
abstract void show();//method provided
}
class Child extends Test
{
void show()//coding
{
System.out.println("saurav");
}
}
class main
{
public static void main(String[] args)
{
Test c = new Child();
c.show();
}
}
Abstract Classes vs Regular Classes vs Interface.
Abstract class usually supports an idea of the generalisation and to contribute from programmers to keep a quite little brain disipline by designing multi-years projects because of they when include an abstract methods have to describe an implementation that abstract methods in subling classes, however, this feature is a disadvantage for a short-time projects when a developer have a zeitnot.
In automotive manufacturing terms, an Interface is a spec sheet for a "car" which says it has four wheels, five seats, an engine, etc, while an Abstract Class is a partially assembled car in a crate that you have to finish off to your own requirements. E.g. Subaru uses the same exact chassis for the Impreza, Forester and XV/Crosstrek. So the chassis is the "abstract class" which has common features and functions but isn't a "car" yet. The body and interior MUST be added after the fact before you can say you've built a car. The engine is also common among all three, though you can choose to swap it out for a turbocharged version IF you wish.
This might help you,
Lets consider traveler who may use any type of vehicle i.e car,cycle,bike etc...
but all vehicles moves in the same way with different speed constraints so we can have one
abstract class Avehicle
{
string fuel;
public void move()
{
sysout("moving");
}
}
but all vehicles breaking system is different
interface Ivehicle
{
public void breakorstop();
}
class Traveler
{
Ivehicle v;
//Settrers and getters
public drive()
{
v.move();
}
public break()
{
v.breakorstop();
}
}
So finally
Car or Cycle or Bike classes can extend Avehicle and can Implement Vehicle interface
Abstract classes can be used to store methods in an OOP-based "library"; since the class doesn't need to be instantiated, and would make little sense for it to be, keeping common static methods inside of an abstract class is a common practice.

Does the Liskov Substitution Principle apply to subtype which inherited from abstract class?

loosely speaking, Liskov Substitution Principle states that a derived class can be substitute in place of the base class without affecting the user.
In the case when the base class is an abstract class, which means no user is using an instance of the base class, does the Liskov inheritance restrictions still apply to the derived class?
Just because you can't instantiate a particular class does not mean that you can't use it. In this scenario, the calling code is using the abstract base class as the definition of the contract under which it operates. In that sense, every class that derives from the base class ought to be interchangable with respect to the interface defined by the base class, so yes Liskov still applies. In fact, this is one primary reason why you would want to have an abstract base class for a collection of classes that have some common behavior -- so you can define operations in terms of the base class interface and not care about which derived class that you are actually operating on.
Yes, because a caller can always do this:
BaseAbstractClass instance = new DerivedClass();
Abstract classes do not conflict with LSP at all. Many people consider using "new" directly from the client code to be a violation of the spirit of LSP. If you both instantiate and use an object, you're tightly-bound to that implementation, and you can't "substitute" it at all.
Consider having the object created via a factory or passed in as an argument or via dependency injection after being created by some kind of repository that can be focused on making decisions about what concrete types are needed in various circumstances.
In short, yes. The LSP applies to essentially all public inheritance. The fact that a base class is abstract doesn't change that. The base class defines an interface, and all legitimate derivatives must satisfy all the requirements of that interface.
Yes.
See the "A Real Example" section (page 7-8) of Uncle Bob's The Liskov Substitution Principle article.
Source: the Old Articles page of cleancoder.com