1

I hava a function like this:

doSomething(){
  Object a = getA() //can return null
  // a lot of additional code
}

... but i want to add a possibility to give object a into method so i created a new method:

doSomething(){
  doSomething(null);
}

doSomething(Object a){
  if(a == null){
    a = getA()
  }  
}

but this is not correct because the object passed into method can also be null and then i wanto to it to null, not use getA() method so i did something like this:

doSomething(){
  doSomething(null, false);
}

doSomething(Object a, boolean useObject){
  if(!useObject){
    a = getA()
  } 

but this seems kind of ugly. Is there a better solution?

2 Answers 2

8

How about :

doSomething()
{
    Object a = getA();
    doSomething(a);
}

doSomething(Object a)
{

}

This way, if someone calls doSomething(null) you don't call getA().

Sign up to request clarification or add additional context in comments.

Comments

0

You can test if a is not null

doSomething(){
  doSomething(null);
}

doSomething(Object a){
  if(a != null){
    a = getA()
  }
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.