是否有必要始终使用mutator方法重新分配字段?

时间:2016-12-15 20:10:05

标签: java security exception

我正在尝试尽可能正确地编写此代码,并且我不确定是否需要捕获 NumberOutOFBoundsException

public Car(String make, String model, String year, int topSpeed, int fuelCapacity, int milesPerGallon) throws NumberOutOfBoundsException{
  this.make = make;
  this.model = model;
  this.year = year;
  this.topSpeed = topSpeed;
  this.fuelCapacity = fuelCapacity;
  this.milesPerGallon = milesPerGallon;

  try{
     setSpeed(0);
     setMileage(0);
     setFuel(0);
  }catch(NumberOutOfBoundsException ex){
     throw ex;
  }
}

这是另一个例子:

//this method will attempt to simulate traveling in a car
//given the time traveled, mileage and remaining fuel should be affected
//if there is not enough fuel, then this method will fail
public void travel(int hours) throws NumberOutOfBoundsException{
  //save rollback values
  double fuel = getFuel();
  int mileage = getMileage();
  int miles = speed * hours;
  double fuelUsage = calculateFuelUsage(miles, milesPerGallon);
  //line 7
  try{

     move(miles);
  }catch(NumberOutOfBoundsException ex){
     try{
        setFuel(fuel);
        setMileage(mileage);
        throw ex;
     }catch(NumberOutOfBoundsException ex1){
        throw ex1;
     }
  }
}

以及我的一个变异者的例子:

public void setSpeed(int speed) throws NumberOutOfBoundsException{
  if(speed > topSpeed || speed < 0)
     throw new NumberOutOfBoundsException();

  this.speed = speed;
}

对于travel(),我认为嵌套的try-catch可能是多余的,也可能不是多余的。

我认为这可能是必要的原因是出于安全原因。如果我只是将字段 fuel 设置为回滚值而不调用setFuel(fuel)(第13行),如果黑客在第7行的travel()暂停了我的代码,然后更改了小时的值,以强制捕获异常,然后更改本地燃料的值,为自己提供尽可能多的燃料?我是否考虑过太多,或者这是一个真正的安全问题?

0 个答案:

没有答案