Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use less local variables or bet on conciseness? [closed]

I was lately thinking on using local variables for example:

Should I prefer this:

String firstString = classString.getFirstString();
String secondString = classString.getSecondString();

ClassGlobal.execute(firstString, secondString);

or this;

ClassGlobal.execute(classString.getFirstString(), classString.getSecondString());

I personally would prefer the later as its more concise and doesn't require two extra instance variables. But is it a good thing to do ? Am I sacrificing code readability for conciseness ? Or is it just ok to use either one ?

like image 965
Sunil Avatar asked Oct 08 '13 16:10

Sunil


3 Answers

When in doubt, just remember this quote from Coding Horror:

Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.

The meaning of this quote is "make it as easy as possible to understand and read the code." Later on, if you need to maintain the program again 5 years down the road then it will be easier for yourself if you make it as readable as possible. This is a win-win for everyone.

like image 150
Domecraft Avatar answered Nov 16 '22 12:11

Domecraft


As for me, you should prioritize code readability against minimizing the number of variables. You may perfectly understand that line of code, but for any programmer that retake your code in the future, he'll appreciate the use of local variables (even better if you use good "self-defining" names).

like image 3
ssantos Avatar answered Nov 16 '22 12:11

ssantos


In this specific case it doesn't matter much. If your line is readable on its own, there is no need to separate out the variables. However, once you start adding any more logic than a getter, I would tend to split them out. Consider the following code:

ClassGlobal.execute(classString.getFirstString().toLowerCase().substring(0, 10),
   classString.getSecondString().toLowerCase().substring(0, 10));

This line would be much better if you separate out firstString and secondString and assign them meaningful names. As with most things in code, there's no "best" way. I would tend to err on the side of readability.

like image 3
Eric Andres Avatar answered Nov 16 '22 12:11

Eric Andres