• JAVA – Need help with validation in constructor

    codewithc
    CWC Keymaster

    I have this constructor called MovablePoint with these fields (x:int, y:int, xSpeed:int, ySpeed:int).

    I also have an interface with 2 fields with the limits of a plain PLAIN_X_MAX = 1000 and PLAIN_X_MIN = -1000. Value X should be within these 2 when creating the object.

    How should I validate X in the constructor before constructing this.X , so that when instatiating the Object, it can only be instantiated if value of X is within the range of PLAIN_X_MAX and PLAIN_X_MIN ?

    I tried with checked exception created by me, PointOutOfBounds which extends Exceptions. Tried something, but whatever value I input for X when doing new MovablePoint( X, Y, xSpeed, ySpeed); I always get that exception.

  • codewithc
    CWC Keymaster

    I hope my pseudo code helps?

    if X > 1000 || X < -1000
    { S.O.P "Fail.. X Out of range"
    Exit }
    else
    { S.O.P "X Validated"}
    
  • codewithc
    CWC Keymaster

    If you call a constructor, you are already instanciating your object so, it is too late to avoid this fact. You should make a test on X before to decide if you can finally create your object. It can be like this

    
    MovablePoint A = null;
    if(X >= -1000 && X =< 1000)
        A = new  MovablePoint(X, Y, xSpeed, ySpeed);
    

    Or if you want use a class constructor, you can create a child class for MovablePoint which will call the mother constructor if the conditions are relevant...

    You can also use a static method inner the class MovablePoint to validate the condition

    
    
    public class MovablePoint
    {
      public MovablePoint(int X, int Y, int xsp, int ysp)
      {
         ....
      }
    
       public static boolean testOfValidation(int X)
       {
          if(X >= -1000 && X =< 1000)
             return true;
    
         return false;
       }
    }
    
    MovablePoint A = null;
    if(MovablePoint.testOfValidation(X))
        A = new  MovablePoint(X, Y, xSpeed, ySpeed);
    
    
    
    or make a mixed solution
    
    
    public class MovablePoint
    {
      public MovablePoint(int X, int Y, int xsp, int ysp)
      {
         ....
      }
    
       public static MovablePoint testOfValidation(int X, int Y, int xsp, int ysp)
       {
          if(X >= -1000 && X =< 1000)
             return new MovablePoint( X, Y, xsp, ysp);
    
          return null;
       }
    }
    
    MovablePoint A = MovablePoint.testOfValidation(X, Y, xSpeed, ySpeed);
    

    If you absolutely want to use the constructor, you can call the protected void finalize() method but, the object will be necessary created before to be destroyed and as you can not really decide when an object is effectively destroyed it will remain in memory until the garbage collector does the job.

Viewing 2 reply threads
  • You must be logged in to reply to this topic.