This question is a result of the answers to this question that I just asked.
It was claimed that this code is "ugly" because it initializes a variable to a value that will never be read:
String tempName = null;
try{
tempName = buildFileName();
}
catch(Exception e){
...
System.exit(1);
}
FILE_NAME = tempName;
Is this indeed bad practice? Should one avoid initializing variables to dummy values that will never actually be used?
(EDIT -
And what about initializing a String variable to ""
before a loop that will concatenate values to the String...? Or is this in a separate category?
e.g.
String whatever = "";
for(String str : someCollection){
whatever += str;
}
)
Initialize Variables When Declaring ThemIt's a good idea to initialize our variables or constants with values when declaring them. It prevents undefined value errors, and we can both declare the variable or constant and set an initial value to it all in one line.
Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.
To declare a variable that has been initialized in another file, the keyword extern is always used. By always initializing variables, instead of assigning values to them before they are first used, the code is made more efficient since no temporary objects are created for the initialization.
Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type.
I think there's no point in initializing variables to values that won't be used unless required by the language.
For example, in C#, the default value for a declared string variable is null, so you're not even gaining anything by explicitly writing it out. It's mostly a style choice, but since strings are immutable, initializing it to something else would actually allocate an extra string in memory that you'd just throw away anyway. Other languages may impose other considerations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With