DEV Community

Don't initialize your variables

Idan Arye on August 05, 2018

Developers coming from C know that variables should always be initialized. Not initializing your variables means they contain junk, and this can ...
Collapse
 
voins profile image
Alexey Voinov

I'd say, that when you think you need some default value to initialise your variable, most probably what you need is a new method, that would return properly constructed value. It would most of the time result in a slightly more readable code. The same is valid for C. :)

Collapse
 
idanarye profile image
Idan Arye

I wouldn't get too dogmatic about it though. Extracting stuff to functions doesn't always improve the readability. As a rule of thumb, I find that it only increase the readability if you can find a good name for that function. If the name of the function is not simpler to understand than it's body, you will actually reduce the readability because now readers will have to derail their train of thought and look for the meaning of that function.

Also, it's not always possible. In C, for example, there is that rule of only being able to declare variables at the top of the block.

Consider, for example, this function:

int readOrDefault(char* filename, int default_) {
    FILE* file = fopen(filename, "r");
    int result = 0;
    if (NULL == file) {
        return default_;
    }
    if (1 != fscanf(file, "%d", &result)) {
        abort();
    }
    fclose(file);
    return result;
}

Even if we ignore the fact that we need to pass a pointer to fscanf instead of getting the result from it, we have the problem of the early return in case we couldn't open the file. We can only read the variable into result after that first if, but we can only declare result before that if. Extracting the initialization of result will not work here.

Collapse
 
voins profile image
Alexey Voinov

Yeah, you don't have to declare variables at the top of the block even in C, as was mentioned in another comment. And C99 is almost 20 years old now. :) And no, I never claimed, that it should always result in better code. That's way I always use a lot of 'maybe' or 'most probably'. It always leaves the space to back out. :)

But, that piece of code is a good challenge. I've just realized, that I never actually thought how should clean code look like in C. It's a good challenge, actually. I like it. I think I'll take a few days to think it over and then show my version of it (or admit, that it was impossible to write) :)

Collapse
 
txai profile image
Txai

Only a minor observation that, since C99 you can declare variables in any point in the function, not only at the top. You can even declare the variable inside the for clause

Collapse
 
idanarye profile image
Idan Arye

True, but old habits die hard.