0

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;
    }

}

2
  • Can you give us an example of the kind of data you mean?
    – pdr
    May 3, 2013 at 21:55
  • I think the whole point of an abstract Class is that everything can and should be overridden. You can't really override anything static, though I guess you could override whatever is using it to ignore it. May 4, 2013 at 17:37

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.