# How to use the value of a method result based on a test?

I have some Java like this:

if (!fooclass.getInfoText().equals(""))
{
this.setInfoText(fooclass.getInfoText());
}


Is there a neater way of setting one value based on the test results of another value? It seems nasty to me that the method is run twice, but putting the result in a variable when it may be empty and not used at all seems equally messy.

In PHP I might do:

if (($foo =$bar->baz()) !== "")
{
$this->set_info_text =$foo;
}


But I know some people are quite strongly for and against this method, though I can't recall a good justification against it.

## 1 Answer

I believe fooclass is a reference of Foo class. I can only think about introducing a variable and check it to prevent the double-invokation of same method.

String fooInfo = fooclass.getInfoText();
if (!"".equals(fooInfo))
{
this.setInfoText(fooInfo);
}


NOTE

I'm using "".equals(fooInfo) to avoid NPE.

• Thanks for the advice on avoiding NPE. So is this your recommended method, using a variable? – deed02392 Aug 15 '13 at 10:57
• @deed02392 at this moment I can't think of another solution. – Anirban Nag 'tintinmj' Aug 15 '13 at 11:23
• Introducing a variable may be a form of premature optimization. Nevertheless an explaining variable may help readability. I usually do not introduce variables when it's about simple getters, as they are mostly self-explanatory. If setting infoTextshould always be a no-op then perhaps the setter could do the check, but then I'd be inclined to rename the setter to reflect this behavior. – bowmore Aug 15 '13 at 13:41
• @bowmore actually he was not happy with invoking same method twice. So I gave this solution & I'm not also very fond of introducing unwanted variables. – Anirban Nag 'tintinmj' Aug 15 '13 at 13:49
• @tintinmj I agree with your solution, it's basically what he'd do in php. I just wanted to clarify what would be a valid reason to introduce a variable, and what would not be. – bowmore Aug 15 '13 at 14:14