Home > Enterprise >  Class member variable validation
Class member variable validation

Time:11-13

What is the most elegant and/or idiomatic way to validate class member variables in dart?

This is what I have so far, and it works, but it seems like there should be a better way.

class Location {
  double longitude;
  double latitude;

  Location(this.longitude, this.latitude) {
    if (longitude < -180.0 || longitude > 180.0) {
      throw Exception("longitude must be between -180 and 180 degrees");
    }
  }
}

CodePudding user response:

the ideal and better way to ensure that the class is fine to continue working is using the assert keyword.

the condition in the assert should be true in order to allow continuation of the code, otherwise, it will throw an AssertException with the text written in it.

Note that I wrote the opposite of your condition (which it should be true so the code works fine ). in your case:

class Location {
  double longitude;
  double latitude;

 Location(this.longitude, this.latitude)
      : assert(
          longitude >= -180.0 && longitude <= 180.0,
          "longitude must be between -180 and 180 degrees",
        );
}
  • Related