mehso
mehso

Reputation: 1

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.

Upvotes: 0

Views: 42

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

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>();
}

Upvotes: 1

Related Questions