简体   繁体   中英

is it proper to initialize an instance variable in a constructor before preconditions in java

      `public Provider(String healthProvider) {
      if (this.healthProvider == null) {
        throw new IllegalArgumentException(PROVIDER_NULL);
      }
    
      if (this.healthProvider.isBlank()) {
        throw new IllegalArgumentException(PROVIDER_ISBLANK);
      }
      this.healthProvider = healthProvider;
       this.patients = new ArrayList<Patient>();
  }

`

   when placed like this, my preconditions for isBlank does pass but that of null passes

      public Provider(String healthProvider) {
      this.healthProvider = healthProvider;
          this.patients = new ArrayList<Patient>();
      if (this.healthProvider == null) {
        throw new IllegalArgumentException(PROVIDER_NULL);
      }
    
      if (this.healthProvider.isBlank()) {
        throw new IllegalArgumentException(PROVIDER_ISBLANK);
          }
    
   }

when i place the code like this my junit test passes but when i place the initialized data members after the preconditions, it doesnt pass.

Either would be fine, but your first should test the passed in healthProvider (since this.healthProvider isn't initialized yet, and when it is; it is using the passed healthProvider ). Like,

public Provider(String healthProvider) {
    if (healthProvider == null) {
        throw new IllegalArgumentException(PROVIDER_NULL);
    } 
    if (healthProvider.isBlank()) {
        throw new IllegalArgumentException(PROVIDER_ISBLANK);
    }
    this.healthProvider = healthProvider;
    this.patients = new ArrayList<Patient>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM