Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fix: handle Null Dereference in UnitsConverter
  • Loading branch information
vil02 committed Sep 22, 2024
commit 8cf21f7d66e264471eb8f94c8202e8aa9fcb7db1
1 change: 0 additions & 1 deletion .inferconfig
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"report-block-list-path-regex": [
"src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java",
"src/main/java/com/thealgorithms/conversions/RomanToInteger.java",
"src/main/java/com/thealgorithms/conversions/UnitsConverter.java",
"src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java",
"src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java",
"src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;

Expand Down Expand Up @@ -77,7 +78,7 @@ public double convert(final String inputUnit, final String outputUnit, final dou
throw new IllegalArgumentException("inputUnit must be different from outputUnit.");
}
final var conversionKey = Pair.of(inputUnit, outputUnit);
return conversions.get(conversionKey).convert(value);
return conversions.computeIfAbsent(conversionKey, k -> { throw new NoSuchElementException("No converter for: " + k); }).convert(value);
}

public Set<String> availableUnits() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.Map;
import java.util.NoSuchElementException;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Test;

Expand All @@ -15,4 +16,12 @@ void testConvertThrowsForSameUnits() {
assertThrows(IllegalArgumentException.class, () -> someConverter.convert("A", "A", 20.0));
assertThrows(IllegalArgumentException.class, () -> someConverter.convert("B", "B", 20.0));
}

@Test
void testConvertThrowsForUnknownUnits() {
final UnitsConverter someConverter = new UnitsConverter(Map.ofEntries(entry(Pair.of("A", "B"), new AffineConverter(10.0, -20.0))));
assertThrows(NoSuchElementException.class, () -> someConverter.convert("A", "X", 20.0));
assertThrows(NoSuchElementException.class, () -> someConverter.convert("X", "A", 20.0));
assertThrows(NoSuchElementException.class, () -> someConverter.convert("X", "Y", 20.0));
}
}