0

I have my constructor like this

    public Name(String firstName, String lastName)
{
    setFirstName(firstName);
    setLastName(lastName);        
}

public Name(String firstName, String lastName, String middleName)
{
    setFirstName(firstName);
    setLastName(lastName);
    setMiddleName(middleName);
}

And I want to override my toString() method like this

    @Override
    public String toString()
    {
        if(no middle name)
        {return  getFirstName() + " " + getLastName();}
        else if(has a middle name)
        {return  getFirstName() + " " + getMiddleName() + " " + getLastName();}
    }

What should I do?

Lenic
  • 33
  • 7
  • 3
    Sounds like you should check whether `middleName` is null or empty... – Jon Skeet Mar 26 '15 at 20:22
  • Yeah, I'm with Jon Skeet. Your pseudocode works, you just have to implement it? If you want to check which constructor was used, you could also set a private field `constructorUsed` with an identifier for the constructor used, but I can't think of a real use-case for that. – James G. Mar 26 '15 at 21:22

1 Answers1

2
@Override
public String toString()
{
    if(middleName == null)
    {return  getFirstName() + " " + getLastName();}
    else
    {return  getFirstName() + " " + getMiddleName() + " " + getLastName();}
}

You might want to check out Guava's Strings for isNullOrEmpty(), e.g. (and with only a single return which, as riccardo.cardin points out, is better practice):

@Override
public String toString()
{
    String nameString = null;

    if (Strings.isNullOrEmpty(middleName))
    {
        nameString = getFirstName() + " " + getLastName();
    }
    else
    {
        nameString = getFirstName() + " " + getMiddleName() + " " + getLastName();
    }

    return nameString;
}
jbrown
  • 7,518
  • 16
  • 69
  • 117
  • Thank you, did not know I can check in this way. – Lenic Mar 26 '15 at 20:52
  • @jbrown, please do not have multiple `return`s in a single method. And do not use `String` concatenation (`+` operator): use a `StringBuilder` or the method `String.format(...)`. – riccardo.cardin Mar 26 '15 at 21:28
  • @riccardo.cardin According to other SO answers, compilers will optimise concatenation into StringBuilders automatically, so concatenation gives more readable code with the same benefits. If the code was in a loop a StringBuilder would be more efficient, but here it's unnecessary. – jbrown Mar 27 '15 at 08:02
  • @jbrown, sorry you're right. But the story about multiple `return` statements remains ;) – riccardo.cardin Mar 27 '15 at 08:31
  • I think the code is more readable with two return statements. I see no reason to avoid it in this case. Also see http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement for a lot of discussion on this topic. – K Erlandsson Mar 27 '15 at 09:59
  • Bikeshedding, but I generally agree that fewer returns are a better habit to get into. – jbrown Mar 27 '15 at 13:45