Are empty abstract classes a bad practice, and why?

后端 未结 11 2031
南方客
南方客 2021-01-02 01:17

We have several empty abstract class in our codebase. I find that ugly. But besides this very stupid reason (ugliness), should I refactor it (into empty interface e.g.) ?

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 01:53

    If you have the following pattern you will find it to be the most flexible:

    interface Fooable
    {
       void foo();
       void bar();
    }
    
    abstract class AbstractFoo
        implements Fooable
    {
    }
    
    class Foo
        extends AbstractFoo
    {
       public void foo()
       {
       }
    
       public void bar()
       {
       }
    }
    

    This way you can always pass by the interface but if you later find that you have code that can be common you can put it in the abstract class without having to make changes to all of the classes.

    Unless you have a good reason for not doing that pattern (and I suspect you don't in this case) I would suggest using it. This can wind up with empty abstract classes but I think it is ok (a little odd, but ok).

    If there truly are no methods in the interface or only one then I would skip the abstract class.

    From a compiler/functional point of view there is no real difference between an interface and an abstract class where all method are abstract. The interface will be more flexible than the abstract class, and the interface + abstract class will be the most flexible of all.

    If it were my code I'd make the change to them being interfaces...

提交回复
热议问题