emer
emer

Reputation: 55

Choice between less duplicate code or efficient but duplicate code

I'm trying the exercises in CodingBat.

Java > String-1 > seeColor: Given a string, if the string begins with "red" or "blue" return that color string, otherwise return the empty string.

My running code is:

public String seeColor(String str) {
  int len = str.length();

  if (len >= 3 && str.substring(0, 3).equals("red")) {
   return str.substring(0, 3);
  } else if (len >= 4 && str.substring(0, 4).equals("blue")) {
     return str.substring(0, 4);
    }
  return "";

}

But I found this other answer all over the web:

public String seeColor(String str) {
    int len = str.length();

    if(len >= 4) {
         if(str.substring(0, 4).equals("blue"))
            return "blue";
         else if(str.substring(0, 3).equals("red"))
            return "red";
        else
            return "";
    }   

    else if(len == 3) {
        if(str.substring(0, 3).equals("red"))
            return "red";
        else
            return "";
    }

    else
        return "";
}

My solution has less duplicate code (or it's what I think). But the other solution looks more efficient. It starts from large Strings, and evaluating only the strings with length of 3 characters at the end. Probably this last solution is more able to make easy changes in the future. I would like to read someone's opinion. Thanks.

Edited: I add an apologize, I haven't formatted my code appropriately at first as suggested by @MikeDunlavey.

Upvotes: 0

Views: 128

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533560

I wouldn't do either. I wouldn't assume the second one is more efficient, though it is more complicated. Both create objects needlessly.

public String seeColor(String str) {
    return str.startsWith("red") ? "red" :
           str.startsWith("blue")? "blue" : "";
}

Every time you call substring this creates two objects which is really expensive for what this function is doing.

Upvotes: 6

Related Questions