SlideShare a Scribd company logo
1 of 12
Favor Composition over
Inheritance
Kochih Wu
Based on Item 16 from Effective Java, 2nd ed.
Use case
Count how many elements have been added to a HashSet
InstrumentedHashSet implementation
public class InstrumentedHashSet<E> extends HashSet<E> {
// The number of attempted element insertions
private int addCount = 0;
public InstrumentedHashSet() { }
public InstrumentedHashSet(int initCap, float loadFactor) { super(initCap, loadFactor); }
@Override public boolean add(E e) {
addCount++;
return super.add(e);
}
@Override public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c);
}
public int getAddCount() {
return addCount;
}
}
Let’s run it
InstrumentedHashSet<String> s = new InstrumentedHashSet<String>();
s.addAll(Arrays.asList("Snap", "Crackle", "Pop"));
assertEquals(3, s.getAddCount());
Output
java.lang.AssertionError:
Expected :3
Actual :6
Issues with inheritance
● Inheritance violates encapsulation
○ Internally HashSet.addAll() calls add()
● Reimplement addAll() using add(), instead of calling super.addAll()?
○ Not reusing code
○ Not always possible without access to private fields
○ New methods can be added to the superclass
Take 2 using composition
// Wrapper class - uses composition in place of inheritance
public class InstrumentedSet<E> extends ForwardingSet<E> {
private int addCount = 0;
public InstrumentedSet(Set<E> s) {
super(s);
}
@Override public boolean add(E e) {
addCount++;
return super.add(e);
}
@Override public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c);
}
public int getAddCount() {
return addCount;
}
}
Forwarding class
public class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
public ForwardingSet(Set<E> s) { this.s = s; }
public void clear() { s.clear(); }
public boolean contains(Object o) { return s.contains(o); }
public boolean isEmpty() { return s.isEmpty(); }
public int size() { return s.size(); }
public Iterator<E> iterator() { return s.iterator(); }
public boolean add(E e) { return s.add(e); }
public boolean remove(Object o) { return s.remove(o); }
public boolean containsAll(Collection<?> c) { return s.containsAll(c); }
public boolean addAll(Collection<? extends E> c) { return s.addAll(c); }
public boolean removeAll(Collection<?> c) { return s.removeAll(c); }
public boolean retainAll(Collection<?> c) { return s.retainAll(c); }
public Object[] toArray() { return s.toArray(); }
public <T> T[] toArray(T[] a) { return s.toArray(a); }
@Override public boolean equals(Object o) { return s.equals(o); }
@Override public int hashCode() { return s.hashCode(); }
@Override public String toString() { return s.toString(); }
}
Let’s run it again
Set<String> s = new InstrumentedHashSet<String>(new HashSet<String>(capacity));
s.addAll(Arrays.asList("Snap", "Crackle", "Pop"));
assertEquals(3, s.getAddCount());
Composition pros & cons
● The wrapper class can be used to instrument any Set implementation
○ Also known as the Decorator pattern
● Not suitable for callback frameworks
Takeaway
● Inheritance should only be used to represent an “is-a” relationship
● Inheritance propagates flaws in the API
● Law of Demeter (or principle of least knowledge)
Discussion

More Related Content

What's hot

Lessons learned from functional programming
Lessons learned from functional programmingLessons learned from functional programming
Lessons learned from functional programmingBryceLohr
 
Goの時刻に関するテスト
Goの時刻に関するテストGoの時刻に関するテスト
Goの時刻に関するテストKentaro Kawano
 
1 borland c++ 5.02 by aramse
1   borland c++ 5.02 by aramse1   borland c++ 5.02 by aramse
1 borland c++ 5.02 by aramseAram SE
 
Image magick++
Image magick++Image magick++
Image magick++Yubin Lim
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++Bharat Kalia
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.jsNoritada Shimizu
 
Real world scala
Real world scalaReal world scala
Real world scalalunfu zhong
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event LoopDesignveloper
 
Pig TPC-H Benchmark and Performance Tuning
Pig TPC-H Benchmark and Performance TuningPig TPC-H Benchmark and Performance Tuning
Pig TPC-H Benchmark and Performance TuningJie Li
 
Watch out: Observables are here to stay
Watch out: Observables are here to stayWatch out: Observables are here to stay
Watch out: Observables are here to stayGuilherme Ventura
 
C- Programs - Harsh
C- Programs - HarshC- Programs - Harsh
C- Programs - HarshHarsh Sharma
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleChristopher Curtin
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805t k
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8InnovationM
 
関数ぷログラミング紹介
関数ぷログラミング紹介関数ぷログラミング紹介
関数ぷログラミング紹介Yoshinori Kohyama
 

What's hot (19)

Lessons learned from functional programming
Lessons learned from functional programmingLessons learned from functional programming
Lessons learned from functional programming
 
Sorter
SorterSorter
Sorter
 
Goの時刻に関するテスト
Goの時刻に関するテストGoの時刻に関するテスト
Goの時刻に関するテスト
 
Document
DocumentDocument
Document
 
1 borland c++ 5.02 by aramse
1   borland c++ 5.02 by aramse1   borland c++ 5.02 by aramse
1 borland c++ 5.02 by aramse
 
Image magick++
Image magick++Image magick++
Image magick++
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
Real world scala
Real world scalaReal world scala
Real world scala
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Pig TPC-H Benchmark and Performance Tuning
Pig TPC-H Benchmark and Performance TuningPig TPC-H Benchmark and Performance Tuning
Pig TPC-H Benchmark and Performance Tuning
 
20151224-games
20151224-games20151224-games
20151224-games
 
Watch out: Observables are here to stay
Watch out: Observables are here to stayWatch out: Observables are here to stay
Watch out: Observables are here to stay
 
C- Programs - Harsh
C- Programs - HarshC- Programs - Harsh
C- Programs - Harsh
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
Concept of Stream API Java 1.8
Concept of Stream API Java 1.8Concept of Stream API Java 1.8
Concept of Stream API Java 1.8
 
関数ぷログラミング紹介
関数ぷログラミング紹介関数ぷログラミング紹介
関数ぷログラミング紹介
 

Similar to Favor composition over inheritance

import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdfasarudheen07
 
output and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfoutput and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfaccess2future1
 
Please use Java to solve the following So.pdf
Please use Java to solve the following So.pdfPlease use Java to solve the following So.pdf
Please use Java to solve the following So.pdfcronkwurphyb44502
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
import java.util.ArrayList;public class Checkout{private.docx
import java.util.ArrayList;public class Checkout{private.docximport java.util.ArrayList;public class Checkout{private.docx
import java.util.ArrayList;public class Checkout{private.docxAbhinav816839
 
can you add a delete button and a add button to the below program. j.pdf
can you add a delete button and a add button to the below program. j.pdfcan you add a delete button and a add button to the below program. j.pdf
can you add a delete button and a add button to the below program. j.pdfsales88
 
sumOfSquaresimport java.util.;public class Arraylistoperation.pdf
sumOfSquaresimport java.util.;public class Arraylistoperation.pdfsumOfSquaresimport java.util.;public class Arraylistoperation.pdf
sumOfSquaresimport java.util.;public class Arraylistoperation.pdfankit482504
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
 
can do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfcan do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfakshpatil4
 
Infinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtilInfinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtilInfinum
 
Hi, Please find my code##### Sequence.java ##############import.pdf
Hi, Please find my code##### Sequence.java ##############import.pdfHi, Please find my code##### Sequence.java ##############import.pdf
Hi, Please find my code##### Sequence.java ##############import.pdfanandmobile
 
i am looking for help on the method AddSorted and the method Copy only.pdf
i am looking for help on the method AddSorted and the method Copy only.pdfi am looking for help on the method AddSorted and the method Copy only.pdf
i am looking for help on the method AddSorted and the method Copy only.pdfsonunotwani
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfNicholasflqStewartl
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdffathimafancyjeweller
 
ios,objective tutorial
ios,objective tutorial ios,objective tutorial
ios,objective tutorial Bhavik Patel
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFabio Collini
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Waytdc-globalcode
 

Similar to Favor composition over inheritance (20)

import java-util--- public class MyLinkedList{ public static void.pdf
import java-util---  public class MyLinkedList{    public static void.pdfimport java-util---  public class MyLinkedList{    public static void.pdf
import java-util--- public class MyLinkedList{ public static void.pdf
 
output and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfoutput and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdf
 
Please use Java to solve the following So.pdf
Please use Java to solve the following So.pdfPlease use Java to solve the following So.pdf
Please use Java to solve the following So.pdf
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
import java.util.ArrayList;public class Checkout{private.docx
import java.util.ArrayList;public class Checkout{private.docximport java.util.ArrayList;public class Checkout{private.docx
import java.util.ArrayList;public class Checkout{private.docx
 
can you add a delete button and a add button to the below program. j.pdf
can you add a delete button and a add button to the below program. j.pdfcan you add a delete button and a add button to the below program. j.pdf
can you add a delete button and a add button to the below program. j.pdf
 
sumOfSquaresimport java.util.;public class Arraylistoperation.pdf
sumOfSquaresimport java.util.;public class Arraylistoperation.pdfsumOfSquaresimport java.util.;public class Arraylistoperation.pdf
sumOfSquaresimport java.util.;public class Arraylistoperation.pdf
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
can do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfcan do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdf
 
C++ programs
C++ programsC++ programs
C++ programs
 
Infinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtilInfinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - DiffUtil
 
Hi, Please find my code##### Sequence.java ##############import.pdf
Hi, Please find my code##### Sequence.java ##############import.pdfHi, Please find my code##### Sequence.java ##############import.pdf
Hi, Please find my code##### Sequence.java ##############import.pdf
 
i am looking for help on the method AddSorted and the method Copy only.pdf
i am looking for help on the method AddSorted and the method Copy only.pdfi am looking for help on the method AddSorted and the method Copy only.pdf
i am looking for help on the method AddSorted and the method Copy only.pdf
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
 
Java generics
Java genericsJava generics
Java generics
 
CSharp v1.0.2
CSharp v1.0.2CSharp v1.0.2
CSharp v1.0.2
 
ios,objective tutorial
ios,objective tutorial ios,objective tutorial
ios,objective tutorial
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+k
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 

Recently uploaded

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

Favor composition over inheritance

  • 1. Favor Composition over Inheritance Kochih Wu Based on Item 16 from Effective Java, 2nd ed.
  • 2. Use case Count how many elements have been added to a HashSet
  • 3. InstrumentedHashSet implementation public class InstrumentedHashSet<E> extends HashSet<E> { // The number of attempted element insertions private int addCount = 0; public InstrumentedHashSet() { } public InstrumentedHashSet(int initCap, float loadFactor) { super(initCap, loadFactor); } @Override public boolean add(E e) { addCount++; return super.add(e); } @Override public boolean addAll(Collection<? extends E> c) { addCount += c.size(); return super.addAll(c); } public int getAddCount() { return addCount; } }
  • 4. Let’s run it InstrumentedHashSet<String> s = new InstrumentedHashSet<String>(); s.addAll(Arrays.asList("Snap", "Crackle", "Pop")); assertEquals(3, s.getAddCount());
  • 6. Issues with inheritance ● Inheritance violates encapsulation ○ Internally HashSet.addAll() calls add() ● Reimplement addAll() using add(), instead of calling super.addAll()? ○ Not reusing code ○ Not always possible without access to private fields ○ New methods can be added to the superclass
  • 7. Take 2 using composition // Wrapper class - uses composition in place of inheritance public class InstrumentedSet<E> extends ForwardingSet<E> { private int addCount = 0; public InstrumentedSet(Set<E> s) { super(s); } @Override public boolean add(E e) { addCount++; return super.add(e); } @Override public boolean addAll(Collection<? extends E> c) { addCount += c.size(); return super.addAll(c); } public int getAddCount() { return addCount; } }
  • 8. Forwarding class public class ForwardingSet<E> implements Set<E> { private final Set<E> s; public ForwardingSet(Set<E> s) { this.s = s; } public void clear() { s.clear(); } public boolean contains(Object o) { return s.contains(o); } public boolean isEmpty() { return s.isEmpty(); } public int size() { return s.size(); } public Iterator<E> iterator() { return s.iterator(); } public boolean add(E e) { return s.add(e); } public boolean remove(Object o) { return s.remove(o); } public boolean containsAll(Collection<?> c) { return s.containsAll(c); } public boolean addAll(Collection<? extends E> c) { return s.addAll(c); } public boolean removeAll(Collection<?> c) { return s.removeAll(c); } public boolean retainAll(Collection<?> c) { return s.retainAll(c); } public Object[] toArray() { return s.toArray(); } public <T> T[] toArray(T[] a) { return s.toArray(a); } @Override public boolean equals(Object o) { return s.equals(o); } @Override public int hashCode() { return s.hashCode(); } @Override public String toString() { return s.toString(); } }
  • 9. Let’s run it again Set<String> s = new InstrumentedHashSet<String>(new HashSet<String>(capacity)); s.addAll(Arrays.asList("Snap", "Crackle", "Pop")); assertEquals(3, s.getAddCount());
  • 10. Composition pros & cons ● The wrapper class can be used to instrument any Set implementation ○ Also known as the Decorator pattern ● Not suitable for callback frameworks
  • 11. Takeaway ● Inheritance should only be used to represent an “is-a” relationship ● Inheritance propagates flaws in the API ● Law of Demeter (or principle of least knowledge)