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.

  • 1
    Myself, I tend to do this in C++, but not in C#. Never really thought about why, though. – Joey Jul 13 '14 at 20:28
  • 1
    Maybe it's because in C++, many types (like int) have undefined default value? This is not a problem in C#. – svick Jul 14 '14 at 10:05

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.

  • 1
    I understand the note, its just an example though. I guess a buffer where the initial position is 0 is more realistic. – Leopold Asperger Jul 13 '14 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 skills – mattnz Jul 13 '14 at 23:34
  • Intern or not, any developer must understand default values. – Leopold Asperger Jul 14 '14 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 Jul 14 '14 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.