Lets say I have a class, myClass that has two methods - addOne() and addTwo().
I have another class, adding. This class has an instance boolean variable, oneOrTwo. This variable decides whether to use addOne() or addTwo() on a myClass object.
I have already written all the lines of code that use the addOne() method and there are a lot of lines. What I don't want to do, is replicate them, something like this:
if (oneOrTwo)
{
// all lines of code for addOne()
}
else
{
//all lines of code for addTwo()
}
The lines of code for addOne() includes a lot of myClass.addOne() calling (of course I have created a new object and everything works perfectly, but I'm speaking generally here to avoid making this an unnecessarily big post). My question is if I can do something like:
if (oneOrTwo)
addNumber() = addOne();
else
addNumber() = addTwo();
And then, instead of using myClass.addOne() or myClass.addTwo(), I can use myClass.addNumber().
Consider inheritance and the strategy pattern.
Create an abstract superclass with one method, addNumber():
public abstract class AddNumber {
public abstract void addNumber();
}
Create two subclasses which each have their own implementation of addNumber():
public class AddOne extends AddNumber {
@Override
public void addNumber() {
// code to add one
}
}
public class AddTwo extends AddNumber {
@Override
public void addNumber() {
// code to add two
}
}
Create a method in your main class that takes an AddNumber object as parameter:
public class MyClass() {
public void add(AddNumber addNumber) {
addNumber.addNumber();
}
// other MyClass stuff
}
Then, if you need to add one to your class, you just call add() with an AddOne object as parameter. Similarly, if you need to add two instead, you call add() with an AddTwo object as parameter.
myClass.add(new AddOne());
myClass.add(new AddTwo());
This is called the strategy pattern and is a common design solution to a problem like this.