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?
In tend to :
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):
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With