1
\$\begingroup\$

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.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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.

\$\endgroup\$
6
  • \$\begingroup\$ Thanks for the advice on avoiding NPE. So is this your recommended method, using a variable? \$\endgroup\$
    – deed02392
    Aug 15, 2013 at 10:57
  • \$\begingroup\$ @deed02392 at this moment I can't think of another solution. \$\endgroup\$ Aug 15, 2013 at 11:23
  • \$\begingroup\$ 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. \$\endgroup\$
    – bowmore
    Aug 15, 2013 at 13:41
  • \$\begingroup\$ @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. \$\endgroup\$ Aug 15, 2013 at 13:49
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – bowmore
    Aug 15, 2013 at 14:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.