KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have to handle two classes with identical methods but they don't implement the same interface, nor do they extend the same superclass. I'm not able / not allowed to change this classes and I don't construct instances of this classes I only get objects of this. What is the best way to avoid lots of code duplication? One of the class: package faa; public class SomethingA { private String valueOne = null; private String valueTwo = null; public String getValueOne() { return valueOne; } public void setValueOne(String valueOne) { this.valueOne = valueOne; } public String getValueTwo() { return valueTwo; } public void setValueTwo(String valueTwo) { this.valueTwo = valueTwo; } } And the other... package foo; public class SomethingB { private String valueOne; private String valueTwo; public String getValueOne() { return valueOne; } public void setValueOne(String valueOne) { this.valueOne = valueOne; } public String getValueTwo() { return valueTwo; } public void setValueTwo(String valueTwo) { this.valueTwo = valueTwo; } } (In reality these classes are larger) My only idea is now to create a wrapper class in this was: public class SomethingWrapper { private SomethingA someA; private SomethingB someB; public SomethingWrapper(SomethingA someA) { //null check.. this.someA = someA; } public SomethingWrapper(SomethingB someB) { //null check.. this.someB = someB; } public String getValueOne() { if (this.someA != null) { return this.someA.getValueOne(); } else { return this.someB.getValueOne(); } } public void setValueOne(String valueOne) { if (this.someA != null) { this.someA.setValueOne(valueOne); } else { this.someB.setValueOne(valueOne); } } publ
Tags (comma-separated)
Save Edits
Cancel