상세 컨텐츠

본문 제목

Understanding the pitfalls of inheritance and interfaces

Java

by techbard 2017. 4. 28. 16:04

본문

반응형

Inheritance


- Inheritance is a core principle of OO programming.

- But we tend to overuse it.

- Often results in design and code that is inflexible.



Problems with Our Design


- We have code duplicated across classes.

- Hard to gain knowledge of all the ducks.

- Changes can affect other ducks.

- Runtime behavior changes are difficult.


What About Using Interfaces?


- Allow different classes to share similarities.

- Not all classes need to have the same behavior.

- Let us try moving duck behaviors into interfaces.


Implementing Ducks with Interfaces




Also Problematic


- Solves part of the problem, but...

- Absolutely destroys code reuse.

- Becomes a maintenance nightmare.

- Does not allow for runtime changes in behaviors other than flying or quacking.


Design Principle #1


- Identify the aspects of your code that vary and separate them from what stays the same.


"Encapsulate What Varies"


- If some aspect of code is changing,

That's a sign you should pull it out and separate it.


- By separating out the parts of your code that vary

You can extend or alter them without affecting the rest of your code.


- This principle is fundamental to almost every design pattern.



Design Principle #2


- Program to an interface, not an implementation.








The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.





반응형

관련글 더보기

댓글 영역