fix humidity to handle unexpected data (#62)

Co-authored-by: «pmartinot» <«pmartinot@provatis.com»>
This commit is contained in:
pmartinot-tech 2026-02-09 10:50:47 +01:00 committed by GitHub
parent a47386fd8f
commit ec4f6af6b6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 18 deletions

View File

@ -44,15 +44,13 @@ public class Humidity {
}
/**
* Creates {@link Humidity} object with correctness check.
* Creates {@link Humidity} object with safeguard to have min 0 and max 100 as value
* @param value humidity
* @return created {@link Humidity} object
*/
public static Humidity withValue(byte value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("Humidity value must be in [0, 100] range.");
}
return new Humidity(value);
int v = Math.max(0, Math.min(100, value));
return new Humidity((byte) v);
}
/**
@ -68,13 +66,10 @@ public class Humidity {
* Sets humidity percentage value.
*
* @param value new humidity value.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
* Rounds to 0 or 100 if provided value isn't in allowed range.
*/
public void setValue(int value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("Humidity value must be in [0, 100] range.");
}
this.value = value;
this.value = Math.max(0, Math.min(100, value));
}
/**

View File

@ -37,13 +37,15 @@ public class HumidityUnitTest {
}
@Test
public void whenCreateHumidityByConstructorWithInvalidDataAboveHundred_thenThrowAnException() {
assertThrows(IllegalArgumentException.class, () -> Humidity.withValue((byte) 112));
public void whenCreateHumidityByConstructorWithInvalidDataAboveHundred_thenValueIsMaxHundred() {
Humidity h = Humidity.withValue((byte) 112);
assertEquals(100, h.getValue());
}
@Test
public void whenCreateHumidityByConstructorWithInvalidDataNegative_thenThrowAnException() {
assertThrows(IllegalArgumentException.class, () -> Humidity.withValue((byte) -33));
public void whenCreateHumidityByConstructorWithInvalidDataNegative_thenValueIsMinZero() {
Humidity h = Humidity.withValue((byte) -33);
assertEquals(0, h.getValue());
}
@Test
@ -59,15 +61,17 @@ public class HumidityUnitTest {
}
@Test
public void whenCreateHumidityAndSetInvalidDataAboveHundred_thenThrowAnException() {
public void whenCreateHumidityAndSetInvalidDataAboveHundred_thenValueIsMaxHundred() {
Humidity humidity = Humidity.withValue((byte) 12);
assertThrows(IllegalArgumentException.class, () -> humidity.setValue((byte) 112));
humidity.setValue(112);
assertEquals(100, humidity.getValue());
}
@Test
public void whenCreateHumidityAndSetInvalidDataNegative_thenThrowAnException() {
public void whenCreateHumidityAndSetInvalidDataNegative_thenValueIsMinZero() {
Humidity humidity = Humidity.withValue((byte) 88);
assertThrows(IllegalArgumentException.class, () -> humidity.setValue((byte) -89));
humidity.setValue(-89);
assertEquals(0, humidity.getValue());
}
@Test