When writing constructors, I regularly encounter a situation where some fields already have approperiate (default) values, such as false
for boolean values and 0
for integers. What are reasons to emphasize these values, for example like:
state = 0;
Do you appreciate it when reading someones code? On one side I feel like expressing implementation details explicitly, on the other side I find it pointless to set a field when I'm sure it is already correct.
2 Answers 2
I work in a projects company. I LOVE it when default values our explicitly defined in the code. This also implies: 1. Definition of the data - is the data type used correct ? 2. The semantic definition of a value - Like in your example, 0 is a clue for an initial state. In some cases I get no clue what 0 means.
Note : State MUST be defined somewhere, be it a CONST value, or an enumeration somewhere. The value 0 has no other meaning than initial state. A string literal might add some more value to it.
-
1I understand the note, its just an example though. I guess a buffer where the initial position is
0
is more realistic.Leopold Asperger– Leopold Asperger2014年07月13日 20:25:54 +00:00Commented Jul 13, 2014 at 20:25
Just because you're sure it is correct, that intern over in the other building has no idea. Giving objects a nice sane default is good. Being explicit is good.
And remember, code is there for humans, not computers.
-
1+1 : Also I don't have to wonder what you were thinking if you are explicit. I might be an expert programmer (yeh...I know.... some of my peers will debate that), I am not a mind reader. More importantly, I only have interest in succeeding at one of those skillsmattnz– mattnz2014年07月13日 23:34:01 +00:00Commented Jul 13, 2014 at 23:34
-
Intern or not, any developer must understand default values.Leopold Asperger– Leopold Asperger2014年07月14日 11:17:03 +00:00Commented Jul 14, 2014 at 11:17
-
@LeopoldAsperger - I heartily disagree. I'm pretty sure I couldn't tell you the default values for all of the different variable declarations for all of the different languages I use today, let alone know. It's trivia, because they shouldn't be counted on.Telastyn– Telastyn2014年07月14日 11:56:44 +00:00Commented Jul 14, 2014 at 11:56
int
) have undefined default value? This is not a problem in C#.