Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to have an empty subclass that extends an abstract class?

Consider the following:

  public abstract class Item {
     String name;
     String description;
     //concrete getters and setters follow
  }

   public class InventoryItem extends Item {
     //empty subclass of Item 
   }

  public class CartItem extends Item {
     int quantity;
     int tax;
     //getters and setters for quantity and tax follow
  }

InventoryItem represents an item that is available for sale whereas CartItem represents an item that is added to the cart so it has additional properties such as quantity and tax. Is it alright to have an empty subclass of the abstract class Item in this scenario?

Option 2 : We could have an empty Item interface. InventoryItem will implement Item and define name and description properties and have getters and setters. CartItem will extend from InventoryItem and will define quantity and tax as properties and have getters and setters.

Option 3 : Would it be better to have an Item interface. InventoryItem would implement Item. We could then have a CartItem class that 'has-an' Item and two properties namely tax and quantity

like image 799
Chetan Kinger Avatar asked Aug 02 '12 17:08

Chetan Kinger


1 Answers

I think there is nothing wrong with this design: it clearly designates Item as a base, and InventoryItem / CartItem as instantiable classes. I would rename Item to AbstractItem (Java class libraries do this) to underscore the fact that the intended use for the class is to be used as a base for other classes.

There are C++ - specific issues, such as assignment through the base pointer, that make it very desirable to make all "non-leaf" classes abstract. Although the rule does not translate to Java literally, I think it is still a good idea to make non-leaf classes abstract, even when the class is self-sufficient. This helps you make explicit separation between classes intended for direct instantiation and classes intended for extending, which is good for maintenance by people who are not familiar with your code base.

Taking the rule a step further, it is a common practice in Java to make all leaf classes final. This is a good defensive rule, especially when your classes are immutable.

EDIT : As far as modeling items in the cart goes, inheriting is not the best option. In fact, I think it is a wrong thing to do. I would make my CartItem own an Item, rather than extending it, because the item does not become another kind of entity by being placed in a cart. Here is how I think it should be modeled:

public class Item {
    String name;
    String description;
    ...
}

public class CartItem {
   Item item;
   int quantity;
   int tax;
   ...
}
like image 102
Sergey Kalinichenko Avatar answered Sep 24 '22 07:09

Sergey Kalinichenko