Every class or method should have only one reason to change.
/**
* Primes counting App ...
*
* Multiple responsibilities: counting & checking
*
* A prime number is a natural number greater than 1 ...
* that is not a product of two smaller natural numbers.
*/package com.minte9.lambdas.single_responsibility;
importstatic org.junit.Assert.assertEquals;
publicclassPrimes{
publicstaticvoidmain(String[] args){
assertEquals(4, noOfPrimes(10)); // pass
}
publicstaticlongnoOfPrimes(int limit){
int n = 0;
for (int i=2; i<limit; i++) { // counting responsibilityfor (int j=2; j<i; j++) { // checking responsibilityif (i%j == 0) { // is prime
n++; break;
}
}
}
return n;
}
}
Encapsulation
According to SR principle this responsability should also be encapsulated.
/**
* A class or method should have only one reason to change.
* Also, this responsability should be encapsulated.
*
* Counting prime numbers - no looping encapsuation!
*/package com.minte9.lambdas.single_responsibility;
importstatic org.junit.Assert.assertEquals;
publicclassEncapsulation{
publicstaticvoidmain(String[] args){
assertEquals(4, countPrimes(10)); // pass
}
publicstaticlongcountPrimes(int limit){
int n = 0;
for (int i=2; i<limit; i++) { // counting loop - no encapsulation! if (isPrime(i)) n++;
}
return n;
}
privatestaticbooleanisPrime(int n){ // checkfor (int i=2; i<n; i++) {
if (n%i == 0) returnfalse;
}
returntrue;
}
}
Lambdas
Lambda expressions make it a lot more easier to implement SR principle.
/**
* With lambdas you can easily make methods that are inline with SRP ...
* one responsability and encapsulation.
*
* Later, we can speeed up the time by using more CPU resources ...
* with parallel method, without changing any other code.
*/package com.minte9.lambdas.single_responsibility;
importstatic org.junit.Assert.assertEquals;
import java.util.stream.IntStream;
publicclassLambdas{
publicstaticvoidmain(String[] args){
assertEquals(25, MyNumbers.countPrimes(100)); // pass
System.out.println(
MyNumbers.countBigPrimes(200000) // 17984
);
}
}
classMyNumbers{
publicstaticlongcountPrimes(int limit){
return IntStream.range(2, limit)
.filter(MyNumbers::isPrime)
.count()
;
}
privatestaticbooleanisPrime(int number){
return IntStream.range(2, number)
.allMatch(x -> number % x != 0)
;
}
publicstaticlongcountBigPrimes(int limit){
return IntStream.range(2, limit)
.parallel() // Look Here
.filter(MyNumbers::isPrime)
.count()
;
}
}