Often in code I get to scenarios I need a temporary variable – example:
String tempUserName = input.getUserName(); tempUserName = sanitzie(tempUserName); validate(tempUserName); // ... Do something else with tempUserName String tempUserNickName = input.getUserNickName(); tempUserNickName = sanitzie(tempUserNickName); validate(tempUserNickName); // ... Do something else with tempUserNickName ... ...
I know that some people use a single temp variable for these kind of things:
String temp = input.getUserName(); temp = sanitzie(temp); validate(temp); // ... Do something else with temp temp = input.getUserNickName(); temp = sanitzie(temp); validate(temp); // ... Do something else with temp ... ...
In my opinion – the way I write it is clearer and less error-prone.
My question is – are there any benefits for using the single temp variable from:
- Memory consumption perspective
- Performance perspective
- Any other perspective
Lets limit the scope of the question to String variables only – but I’ll be happy to get a more general feedback.
My main answer to this would be if you have a series of those sorts of statements, I’d break the groupings out into a separate function you call. (Which would have just the one temp variable.) E.g.:
Usage:
…where
handleInputmight returnnullfor invalid or dangerous input, etc. You may well have to parameterizehandleInputmore than above.Answer the perspectives you raised:
I suppose technically, if there were only one temp variable, the memory from earlier on would be eligible for garbage collection earlier (e.g., while the method was running rather than afterward). But I doubt it makes any real-world difference.
I can’t imagine so.
We probably come down to style here, which is mostly a matter of personal preference. Again, I’d split it off into a function, which is kind of an end-run around the question. 🙂