Is it better to assign variables in a class itself or in the class' constructor? [closed]

会有一股神秘感。 提交于 2019-12-10 09:24:44

问题


This is a sort of design question, and I'm sure there are people who do it both ways. But in your opinion, is it better to assign a variable in the class or in the constructor? For example (regardless of syntax or language, this is just to explain):

public class Example
{
   private final int TIME_STAMP = Now();
   private int num = 2;
}

OR

public class Example
{
   private readonly int TIME_STAMP;
   private int num;

   public Example()
   {
      TIME_STAMP = Now();
      num = 2;
   }
}

Please disregard the mix of different languages and syntax... Which is preferable and why?


回答1:


Inline (the first option):

  • it is more readable
  • you don't have to duplicate it in every constructor
  • if there is such thing in your language, you can use initializer blocks. They look like constructors, but don't need to be defined multiple times. In Java they look like this:

    {
        var1 = 5;
        varTime = now();
    }
    



回答2:


In tend to :

  • Set default, constant values in the class itself
  • And values that depends on something else (like the current time) in the constructor.


i.e., I tend to use something like this (merging your two examples) :

public class Example
{
   private readonly int TIME_STAMP;
   private int num = 2;

   public Example()
   {
      TIME_STAMP = Now();
   }
}

But my prefered language is PHP, and it doesn't allow me to set non-constant values in the class declaration itself, so my way might be a bit biased.




回答3:


The main idea here is that you put in any start up or initialization code for the class in the constructor. As opposed to this and logically, you put in any clean up code in the destructor.




回答4:


From a testability standpoint, both approaches are problematic. Except for constants, you should have a constructor which accepts these as arguments, or a property which allows you to set the backing field.
Typically, I would create a "full" constructor, which gives you complete control of the class, and an empty/default constructor, which calls the other one specifying the default arguments. That way, everything is in one place, and I don't have to go look into the backing fields to figure out what is going on at construction time.




回答5:


It really depends on which language you are using. For example, in PHP only constants can be defined immediately with in the class. However, if what you're going for cross-language compatibility, then it'd be best to assign values to all of your class variables in the constructor.



来源:https://stackoverflow.com/questions/2194198/is-it-better-to-assign-variables-in-a-class-itself-or-in-the-class-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!