Code functionality
The following code tests whether the values that a user specifies for a lower bound and upper bound on two properties:
- The lower bound is smaller than the upper bound.
- The values are larger than 0 (positive).
Since it first checks whether the lower bound is smaller than the upper bound, it implicitly verifies the upper bound is larger than 0, if it tests whether the lower bound is larger than 0. Therefore, my consideration is: I can make the code more compact by omitting the check for "is the upper bound larger than 0".
Code
# Object getting labels class Get_labels: def __init__(self,lower_bound,upper_bound,configuration_name): self.lower_bound = lower_bound self.upper_bound = upper_bound self.configuration_name = configuration_name self.check_threshold_validity() # Verifies if the chosen thresholds are valid values. def check_threshold_validity(self): if self.lower_bound>=self.upper_bound: raise Exception(f'Sorry, the lower threshold={self.lower_bound} should be smaller than the upper bound={self.upper_bound} for configuration={self.configuration_name}') # checks if lower bound (and implicitly upper bound) are above zero if self.lower_bound<=0: raise Exception(f'Sorry, the lower threshold={self.lower_bound} should be larger than 0 for configuration={self.configuration_name}') if __name__ == '__main__': get_labels = Get_labels(-1,25,"first")
Design choice
However, if the code is modified it might not be obvious the upper bound also needs to be checked because that is done implicitly. That might result in the edge case with upper bound below zero is not being caught after modifications. Hence to prevent this scenario, I can implement two unit test that check if an error is raised for:
- The lower bound negative, upper bound negative
- The lower bound zero, upper bound negative
- The lower bound positive, upper bound negative
Question
Is it recommended to include the explicit check in the main code anyways, even though it is tested in the unit tests?