3

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().

nettek
  • 213
  • 1
  • 3
  • 13
  • 2
    Why don't you try inheritance? – Naman Gala Sep 04 '15 at 11:44
  • What is `addNumber`? Are you trying to assign a function to a function? Btw, generally speaking, having Boolean flags to do one thing or another are not very clean. A method should do one thing and one thing only. – Manu Sep 04 '15 at 11:45

3 Answers3

5

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.

Soggiorno
  • 760
  • 9
  • 17
3

You could have a method in myClass called add(boolean One) such as:

public double add(boolean one) {
    return (one) ? addOne() : addTwo();
}

You can call that method via:

myClass.add(adding.oneOrTwo);

(you may need the relevant getter method if the field oneOrTwo is private.)

McNultyyy
  • 992
  • 7
  • 12
1

That's what the ternary operatior is for:

addNumber = oneOrTwo? addOne : addTwo;
Luis Sieira
  • 29,926
  • 3
  • 31
  • 53