Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to initialize a variable to a dummy value?

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;
}

)

like image 399
froadie Avatar asked May 05 '10 14:05

froadie


People also ask

Is it good practice to initialize variables?

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.

What happens if I use a variable before initializing it to a value?

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.

Why is it a good idea to initialize variables as they are declared?

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.

Should you initialize variables in Python?

Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type.


1 Answers

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.

like image 61
Adam Lear Avatar answered Oct 05 '22 06:10

Adam Lear