I have three objects; Action, Issue and Risk. These all contain a nunber of common variables/attributes (for example: Description, title, Due date, Raised by etc.) and some specific fields (risk has probability). The question is:
Should I create 3 separate classes Action, Risk and Issue each containing the repeat fields.
Create a parent class "Abstract_Item" containing these fields and operations on them and then have Action, Risk and Issue subclass Abstract_Item. This would adhere to DRY principal.
Subclassing : If we want to modify state as well as behaviour of any class or override any methods to alter the behaviour of the parent class then we go for subclassing. For example : We subclass UIView to alter its state and behaviour in our iOS code. Save this answer.
Using subclasses has several advantages: Reuse of code: Through inheritance, a subclass can reuse methods that already exist in a superclass. Specialization: In a subclass you can add new methods to handle cases that the superclass does not handle. You can also add new data items that the superclass does not need.
A subclass is a class derived from the superclass. It inherits the properties of the superclass and also contains attributes of its own. An example is: Car, Truck and Motorcycle are all subclasses of the superclass Vehicle.
A subclass is the same as an inherited class. In example A, bar is an inner class.
My Perspective
Let's say, if you used inheritance. Over a period you have new attributes that are common to only Action and Issue but not Risk. How will you handle this? If you put them under parent then Risk is inheriting stuff that is irrelevant (Liskov Substituon Principle knocking?). If you put then in Action and Risk separately then you are breaking DRY, the initial reason why you started inheritance. Point is Inhertence for re-use is bad. If there is no "is-a" then better not use it and when you are in doubt then there is no real "is-a".
My Preference
There are other ways of achieving DRY as shown in below example code. With this addition of new properties my be another Common2, addition of new behavior is new CommonBehavior2 if they are not applicable to all 3 classes; if they are then just change existing Common and CommonBehavior
public class Common implements CommonBehavior
{
String Description;
String title;
public void f() {}
}
public interface CommonBehavior
{
void f();
}
public class Action implements CommonBehavior
{
private Common delegate;
public void f()
{
delegate.f();
}
}
Also look at my answer to a similar question with another practical example Design pattern to add a new class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With