Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize final variable within constructor in another method

Tags:

java

android

I have a problem which isn't really that big, but still gives me some thought as to how Java constructors and methods are used.

I have a constant representing a radius I declare final, and also make it public for everyone to see. I don't want my code littered with getRadius() methods when I'm never ever going to change the radius.

I want to initialize the constant within the constructor as I want to apply certain criteria before assigning the radius, certain conditions have to be met. However, these conditions do take up some space, and I'd like to put them in some other method, to make the constructor cleaner.

The whole thing would initially look like this

public MyProblematicClass {
   public final int radius;
   public MyProblematicClass(... variables ...) {
      if(... long criteria ...) {
         radius = n;
      }
   }
}

and I'd love it to end up like

public MyProblematicClass {
       public final int radius;
       public MyProblematicClass(... variables ...) {
          this.setRadiuswithCriteria(criteria);
}

private void setRadiuswithCriteria(criteria crit) {
   if(... crit ...) {
      radius = n;
   }

I understand that I could potentially use the method for other purposes and that's the reason for giving me a 'blank field RADIUS may not have been initialized, so I'd like to know if there is a way to add a method which will only be used in constructors, for cleanliness's sake.

like image 618
RedOrav Avatar asked Aug 01 '12 11:08

RedOrav


2 Answers

How about (using small caps for radius, because it is not a constant, as pointed out in the comments):

public MyProblematicClass(... variables ...) {
    radius = getRadiusWithCriteria(criteria);
}

private int getRadiusWithCriteria(criteria crit) {
   if(... crit ...) {
      return n;
   } else {
      return 0;
   }
}
like image 127
assylias Avatar answered Nov 15 '22 14:11

assylias


You cannot assign to final variable outside constructor. As you said, method:

setRadiuswithCriteria(criteria crit) {
   if(... crit ...) {
      RADIUS = n;
   }

Can be used outside constructor.

And you must set final variable to some value in constructor, not just after checking some criteria (always, not sometimes).

However, you might move the code outside the constructor, using the returned value of some function. Example:

class MyClass {
    private final double i;
    public MyClass() {
        i = someCalculation();
    }
    private double someCalculation() {
        return Math.random();
    }
}
like image 43
peenut Avatar answered Nov 15 '22 13:11

peenut