Initialize class fields in constructor or at declaration?

前端 未结 15 2067
南旧
南旧 2020-11-22 01:16

I\'ve been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:



        
15条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 02:06

    My rules:

    1. Don't initialize with the default values in declaration (null, false, 0, 0.0…).
    2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
    3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
    4. Be consistent in your practice (the most important rule).

提交回复
热议问题