Open-closed principle and Java “final” modifier

后端 未结 7 1236
灰色年华
灰色年华 2020-12-29 04:37

The open-closed principle states that \"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification\".

However, J

7条回答
  •  我在风中等你
    2020-12-29 05:18

    Nowadays I use the final modifier by default, almost reflexively as part of the boilerplate. It makes things easier to reason about, when you know that a given method will always function as seen in the code you're looking at right now.

    Of course, sometimes there are situations where a class hierarchy is exactly what you want, and it would be silly not to use one then. But be scared of hierarchies of more than two levels, or ones where non-abstract classes are further subclassed. A class should be either abstract or final.

    Most of the time, using composition is the way to go. Put all the common machinery into one class, put the the different cases into different classes, then composit instances to have working whole.

    You can call this "dependency injection", or "strategy pattern" or "visitor pattern" or whatever, but what it boils down to is using composition instead of inheritance to avoid repetition.

提交回复
热议问题