Skip to content

Commit

Permalink
Refactor test assertions and streamline code
Browse files Browse the repository at this point in the history
Switched to using AssertJ's assertThat assertion for improved readability and precision in SumBigDecimalsTest. Suppressing "unused" warning in SumBigDecimals class for unused method.

Significantly refactored the implementation of LoopsSortsAndIfs class. Replaced several for-loops, condition checks, and separate list sorting with a streamlined approach utilizing Java Streams API. This reduces redundancy and improves readability.
  • Loading branch information
kousen committed Nov 9, 2023
1 parent 35dd7ce commit 71f96df
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 22 deletions.
28 changes: 7 additions & 21 deletions src/main/java/refactoring/after/LoopsSortsAndIfs.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,16 @@
package refactoring.after;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class LoopsSortsAndIfs {
public static void main(String[] args) {
String[] strings = "this is an array of strings".split(" ");

List<String> evenLengths = new ArrayList<>();
for (String s : strings) {
if (s.length() % 2 == 0) {
evenLengths.add(s.toUpperCase());
}
}

Collections.sort(evenLengths, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});

for (String s : evenLengths) {
System.out.println(s);
}
Arrays.stream("this is an array of strings".split(" "))
.filter(s -> s.length() % 2 == 0)
.map(String::toUpperCase)
.sorted(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()))
.forEach(System.out::println);
}
}
1 change: 1 addition & 0 deletions src/main/java/streams/SumBigDecimals.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

public class SumBigDecimals {

@SuppressWarnings("unused")
public BigDecimal sumFirstN_asDoubles(int n) {
double total = Stream.iterate(BigDecimal.ONE, bd -> bd.add(BigDecimal.ONE))
.limit(n)
Expand Down
4 changes: 3 additions & 1 deletion src/test/java/streams/SumBigDecimalsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

import java.math.BigDecimal;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class SumBigDecimalsTest {
Expand All @@ -13,7 +15,7 @@ public class SumBigDecimalsTest {
@Test
public void sumFirstN_usingReduce() {
BigDecimal answer = summer.sumFirstN_usingReduce(10);
assertEquals(new BigDecimal("55"), answer);
assertThat(answer).isCloseTo(BigDecimal.valueOf(55), within(BigDecimal.valueOf(0.01)));
}

@Test @Disabled("disable until demo")
Expand Down

0 comments on commit 71f96df

Please sign in to comment.