DEV Community

dna2me
dna2me

Posted on

物件導向 - 減少重複的程式碼 Inheritance v.s. Composition

Composition over inheritance

有個題目是這樣的:
我有兩個類別,在類別裡面有相同(實作內容一模一樣)的方法method。為了減少重複的程式碼,我為這兩個類別創造了一個共同父類別,並且把相同的方法method放在父類別,這樣好嗎?
Alt Text

Top comments (3)

Collapse
 
thefern profile image
Fernando B 🚀

If the method is the same for both categories then a parent class might make more sense to avoid code duplication. If the method isn't the same, an interface class or abstract class/method might be better and let subclasses implement them.

Collapse
 
dna2me profile image
dna2me

Wow, thanks for your reply. Actually I am still modifying my article. It's an accident that I published this.

Collapse
 
thefern profile image
Fernando B 🚀

I think my answer still applies.