Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 205
froadie Avatar asked Feb 28 '23 15:02

froadie


2 Answers

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.

like image 148
Pascal MARTIN Avatar answered Mar 02 '23 05:03

Pascal MARTIN


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();
    }
    
like image 29
Bozho Avatar answered Mar 02 '23 05:03

Bozho