Pregunta

I have a certain function that uses the same (few, 2-5 depending on how I may change it to accommodate possible future uses) lines of code 4 times.

I looked at this question, but it's not specific enough for me, and doesn't match the direction I'm going for.

Here's some pseudo:

function myFunction() {
  if (something) {
    // Code line 1
    // Code line 2
    // Code line 3
  }
  else if (somethingElse) {
    // Code line 1
    // Code line 2
    // Code line 3
  }
  else if (anotherThing) {
    // Code line 1
    // Code line 2
    // Code line 3
  }
  else if (theLastThing) {
    // Code line 1
    // Code line 2
    // Code line 3
  }
  else {
  // Not previously used code
  }
}

Those same 3 lines of code are copy/pasted (constructing the same object if any of these conditions are met). Is it a good practice to create a function that I can pass all this information to and return the necessary information when it's finished? All of these conditional statements are inside a loop that could run up to 1000 or so times.

I'm not sure if the cost of preparing the stack frame(?) by jumping into another function is more costly over 1000 iterations to be worth having ~15 lines of duplicated code. Obviously function-alizing it would make it more readable, however this is very specific functionality that is not used anywhere else. The function I could write to eliminate the copy/paste mentality would be something like:

function myHelperFunction(someParameter, someOtherParameter) {
  // Code line 1
  // Code line 2
  // Code line 3
  return usefulInformation;
}

And then call the function in all those conditional statements as 1 line per conditional statement:

myHelperFunction(myPassedParameter, myOtherPassedParameter);

Essentially turning those 12 lines into 4.

So the question - is this a good practice in general, to create a new function for a very small amount of code to save some space and readability? Or is the cost for jumping functions too impacting to be worth it? Should one always create a new function for any code that they might copy/paste in the future?

PS - I understand that if this bit of code were to be used in different (Classes) or source files that it would be logical to turn it into a function to avoid needing to find all the locations where it was copy/pasted in order to make changes. But I'm talking more or less single-file/single-Class or in-function kind of a dilemma. Also, feel free to fix my tags/title if I didn't do it correctly. I'm not really sure how to title/tag this post correctly.

¿Fue útil?

Solución

The answer to any optimization question that isn't also an algorithms/data structures question is: Profile your code! Only optimize things that show up as problem areas.

Which means you should find out if function call overhead is actually a performance problem in the specific program you're writing. If it is, inline the code. If it isn't, don't. Simple as that.

Otros consejos

You're approaching this the wrong way, in my opinion. In the first place, you shouldn't be using multiple (else)ifs that all execute the same code; use one with a compound or precomputed (in this case I recommend precomputed due to all the possible subconditions) condition. Something like this will probably make maintaining the code a lot easier.

function myFunction() {
  bool condition = something ||
                   somethingElse ||
                   anotherThing ||
                   theLastThing;

  if (condition) {
    // Code line 1
    // Code line 2
    // Code line 3
  }
  else {
  // Not previously used code
  }
}

Yes create a function, in general you should follow the DRY principal. Don't Repeat Yourself.

http://en.wikipedia.org/wiki/Don%27t_repeat_yourself

Your stack operations are going to be minimal for something like this. See Imre Kerr's comment on your question.

It's not just for readability. So many reasons. Maintainability is huge. If this code has to change, it will be a pain for someone else to come along and try to figure out every place to change it. It's a lot better to only have to change code in one place.

I don't know if this apply to the example that you provided, but factoring code is not the only reason to write a function, you can also think in term of tests

A function provides a programming unit that can be tested separately.

So it may happen that you decompose a complex operation into several simpler/more elementary units, even if those functions are only called once.

Since you asked the question for a few lines of code, you could ask yourself:

  • can I reasonnably name this function?
    ( justDoThis should be OK, doThisAndThatAndThenAnotherThing less so)
  • does it have a reasonnable number of parameters?
    (I would say two or three)
  • is it worth testing it as a separate unit?
    (does it simplify overall testing)
  • is the code more readable/understandable with such function call or not?
    (if answer to first two questions is no, it's not necessarily obvious)

This is a wonderful question, and the answer is: It depends.

Personally I would create a function for increased code readability, but If you are looking for efficiency maybe you would want to leave the code copied and pasted.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top