A developer usually creates a subclass of an existing class by extending it.  Normally they will use the code in the parent class

General rules for extending:

  • The subclass must use a significant part of the superclass, such as code and, if there are any, variables.

  • The subclass must be the same kind of “thing” as the parent class.  For example, if the superclass is a BinaryStreamingController, the subclass could be a more specific VideoStreamingController.

Don't extend classes just to get lazy access to its static methods:

public class ValidationUtil extends StringUtils
{
   public static String validateOrder(Order order)
   {
       if (!isAlphanumeric(order.getDescription())
       {
           return “Description contains invalid characters”;
       }
       if (isBlank(order.getProductCode())
       {
           return “Missing product code”;
       }
   }   
}

The ValidationUtil class is not a kind of StringUtils class and therefore should not extend from it.  But the developer has subclassed from it to be able to access the isAlphanumeric() and isBlank() methods directly.

public class ValidationUtil
{
   public static String validateOrder(Order order)
   {
       if (!StringUtils.isAlphanumeric(order.getDescription())
       {
           return “Description contains invalid characters”;
       }
       if (StringUtils.isBlank(order.getProductCode())
       {
           return “Missing product code”;
       }
   }    
}

Tip: As a general rule, class names that end in 'Utils' are full of static methods and are not designed to be extended.  Static methods are one of the ideas remaining from procedural computing despite the trend towards object orientation.  They're great – they require no scope, generally have no dependencies and can be completely self contained in function.  But think before you create if it should be related to an instance of a class rather than a static method.


blog comments powered by Disqus