2

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.

asked Jul 13, 2014 at 20:00
2
  • 1
    Myself, I tend to do this in C++, but not in C#. Never really thought about why, though. Commented Jul 13, 2014 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#. Commented Jul 14, 2014 at 10:05

2 Answers 2

1

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.

answered Jul 13, 2014 at 20:22
1
  • 1
    I understand the note, its just an example though. I guess a buffer where the initial position is 0 is more realistic. Commented Jul 13, 2014 at 20:25
5

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.

answered Jul 13, 2014 at 21:20
3
  • 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 Commented Jul 13, 2014 at 23:34
  • Intern or not, any developer must understand default values. Commented 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. Commented Jul 14, 2014 at 11:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.