Should every single object have an interface and all objects loosely coupled?

后端 未结 7 1945
刺人心
刺人心 2020-12-24 05:23

From what I have read best practice is to have classes based on an interface and loosely couple the objects, in order to help code re-use and unit test.

Is this corr

7条回答
  •  一生所求
    2020-12-24 06:18

    I tried to take the advice of 'code to an interface' literally on a recent project. The end result was essentially duplication of the public interface (small i) of each class precisely once in an Interface (big I) implementation. This is pretty pointless in practice.

    A better strategy I feel is to confine your interface implementations to verbs:

    Print()
    Draw()
    Save()
    Serialize()
    Update()
    

    ...etc etc. This means that classes whose primary role is to store data - and if your code is well-designed they would usually only do that - don't want or need interface implementations. Anywhere you might want runtime-configurable behaviour, for example a variety of different graph styles representing the same data.

    It's better still when the thing asking for the work really doesn't want to know how the work is done. This means you can give it a macguffin that it can simply trust will do whatever its public interface says it does, and let the component in question simply choose when to do the work.

提交回复
热议问题