Is it better to assign variables in a class itself or in the class' constructor? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this questionThis 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?
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.
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(); }
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.
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.
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.
精彩评论