Java Design – Using Abstract Methods as Static Methods

designjava

In an attempt to write some generic code I find myself putting, in my abstract class, a method that returns some static information about how the class should be treated. This method doesn't use any state data and would be static, except that static abstract methods aren't allowed. Is this a code smell? is there something one should do to avoid this?

I haven't writtent he real code yet. Here is a quick example, conceptually. Little slopy programing wise to make to make it a quick read. basically a way for the code to return information to the model, in this case, about how it should be treated within the generic functions of the model. Assume the enum stored whatever configuration state in this case.

public abstract modelObject{

    public abstract ModelGroup getModelGroup;

    public final void addToModel(){
        Model.store(this.getModelGroup, this);
    }
}


public class myObject extends modelObject{
    public ModelGroup getModelGroup(){
        return ModelGroup.MyGroup;
    }
}

public class DifferentClass extends ModelObject{
    public ModelGroup getModelGroup(){
        return ModelGroup.differentGroup;
    }

}

Best Answer

Preferably, rather than providing properties that specify how the object should be treated, the class-dependent behavior should instead be encapsulated inside an abstract method. For example, use:

obj.doSomething(); // Abstract method - subclasses override with appropriate behavior

instead of:

if(obj.getModelGroup() == ModelGroup.MyGroup) {
    doSomethingWith(obj); // Behavior specific to one subclass
} else {
    doSomethingElseWith(obj); // Behavior specific to another subclass
}

Having said that, there are perfectly legitimate cases where implementers of a method might not use instance-specific state.

As an example, consider the java.sql.Driver interface (it's not an abstract class, but it easily could be). If you have a separate class for each type of driver, its methods probably don't require any instance-specific state. The jdbcCompliant, getMinorVersion, and getMajorVersion methods likely return hard-coded constants. The acceptsURL and connect methods likely have behavior that isn't instance-specific.

In short: it depends. Not using instance state in an abstract method implementation isn't inherently wrong; however, in some cases it may indicate that your code could benefit from being restructured.

Related Topic