Responsibility
Every class or method should have only
one reason to change.
package com.minte9.lambdas.single_responsibility;
import static org.junit.Assert.assertEquals;
public class Primes {
public static void main(String[] args) {
assertEquals(4, noOfPrimes(10));
}
public static long noOfPrimes(int limit) {
int n = 0;
for (int i=2; i<limit; i++) {
for (int j=2; j<i; j++) {
if (i%j == 0) {
n++; break;
}
}
}
return n;
}
}
Encapsulation
According to SR principle this responsability should also be
encapsulated.
package com.minte9.lambdas.single_responsibility;
import static org.junit.Assert.assertEquals;
public class Encapsulation {
public static void main(String[] args) {
assertEquals(4, countPrimes(10));
}
public static long countPrimes(int limit) {
int n = 0;
for (int i=2; i<limit; i++) {
if (isPrime(i)) n++;
}
return n;
}
private static boolean isPrime(int n) {
for (int i=2; i<n; i++) {
if (n%i == 0) return false;
}
return true;
}
}
Lambdas
Lambda expressions make it
a lot more easier to implement SR principle.
package com.minte9.lambdas.single_responsibility;
import static org.junit.Assert.assertEquals;
import java.util.stream.IntStream;
public class Lambdas {
public static void main(String[] args) {
assertEquals(25, MyNumbers.countPrimes(100));
System.out.println(
MyNumbers.countBigPrimes(200000)
);
}
}
class MyNumbers {
public static long countPrimes(int limit) {
return IntStream.range(2, limit)
.filter(MyNumbers::isPrime)
.count()
;
}
private static boolean isPrime(int number) {
return IntStream.range(2, number)
.allMatch(x -> number % x != 0)
;
}
public static long countBigPrimes(int limit) {
return IntStream.range(2, limit)
.parallel()
.filter(MyNumbers::isPrime)
.count()
;
}
}