I was wondering if there was a way to remove this sort of duplicate code (it crops up all across my program)
public void pickUp(Cointainer in)
{
if(playerContainer.returnSomething() == null)
{
playerContainer.setSomething(in.returnSomething());
in.setSomething(null);
}
}
public void dropContainer (Container out)
{
if(out.returnSomething() == null)
{
out.setSomething(playerContainer.returnSomething());
playerContainer.setSomething(null);
}
}
As you can see from the example above, the two methods are essentially exactly the same, except for which container is tested to be null, and which container the object ends up in. Is there anyway to reduce something like this to one method? Another example occurs later in the code, where multiple objects are tested in a different order:
if (control = 1)
{
if(con1 == null)
return con1
else if (con2 == null)
return con2
else
return con3
}
else
{
if(con3 != null)
return con3
if(con2 != null)
return con2
else
return con1
}
Is there anyway for this type of statement to be reduced to one if?
Sorry if my question is really noobish/retarded, I might be a bit lacking on that side of things, specially considering the last question I asked here :/
Anyway, thanks for taking the time to read this :)
You can introduce a new method which actually does the job of moving from one to other and express the other two in terms of the common functionality.
pickup = move from in -> player
drop = move from player -> out
public void pickUp(Container in)
{
moveContainer(in, playerContainer);
}
public void dropContainer (Container out)
{
moveContainer(playerContainer, out);
}
public void moveContainer(Container from, Container to) {
if (to.returnSomething() == null) {
to.setSomething(from.returnSomething());
from.setSomething(null);
}
}