0

This is my constructor. And i have this conflict(. I must check input argument in set method?

public Car(int maxSpeed, String manufacturer, String model, String carType) {
    super(maxSpeed, manufacturer, model);
    if (carType == null || carType.isEmpty()) {
        throw new IllegalArgumentException();
    }
    this.carType = carType;
}


public void setCarType(String carType) {

    this.carType = carType;
}
  • Well yes - if it's not valid in the constructor, why would you expect it to be valid when calling the setter later? – Jon Skeet Apr 09 '16 at 10:59
  • do you have `import java.lang.IllegalArgumentException;` ? – Jose Luis Apr 09 '16 at 11:00
  • I dont have import java.lang.IllegalArgumentException; – Myrat Arazgeldiev Apr 09 '16 at 11:02
  • If you have a compile time error saying that there is not this Exception, you need to add this import line at the beggining of you class file. Or change the throw for `throw new java.lang.IllegalArgumentException();` – Jose Luis Apr 09 '16 at 11:05
  • It not a good idea to throw exceptions in constructors. It is best to put the throw in the `setCarType()` – Jose Luis Apr 09 '16 at 11:07
  • Ok) What you think about set method? Am I must to add check input parameter? – Myrat Arazgeldiev Apr 09 '16 at 11:08
  • Or i am must delete set method? – Myrat Arazgeldiev Apr 09 '16 at 11:11
  • 1
    @JoseLuis - He >>does not<< need to import it. `java.lang.IllegalArgumentException` is in `java.lang`. It will be imported on demand. – Stephen C Apr 09 '16 at 11:35
  • @stephen-c I undertood that he can't compile because there was not this exception class, that's because I said to add the import. – Jose Luis Apr 09 '16 at 11:41
  • @myrat-arazgeldiev You need that `carType` never gets null values. This question could help to you: http://stackoverflow.com/questions/2997768/java-constructor-style-check-parameters-arent-null – Jose Luis Apr 09 '16 at 11:45
  • And your documentation has to say that this parameter don't accept null values. – Jose Luis Apr 09 '16 at 11:47
  • @myrat-arazgeldiev In this post http://stackoverflow.com/questions/6086334/is-it-good-practice-to-make-the-constructor-throw-an-exception the first answer by Stephen C says that yes, it's correct to throw this exception. – Jose Luis Apr 09 '16 at 12:02

0 Answers0