Java Reference
In-Depth Information
to implement the single responsibility principle at the method level. Let's take a look at some
code that counts the number of prime numbers up to a certain value ( Example 8-34 ) .
Example 8-34. Counting prime numbers with multiple responsibilities in a method
public
public long
long countPrimes ( int
int upTo ) {
long
long tally = 0 ;
for
for ( int
int i = 1 ; i < upTo ; i ++) {
boolean
boolean isPrime = true
true ;
for
for ( int
int j = 2 ; j < i ; j ++) {
iif ( i % j == 0 ) {
isPrime = false
false ;
}
}
iif ( isPrime ) {
tally ++;
}
}
return
return tally ;
}
It's pretty obvious that we're really doing two things in Example 8-34 : we're counting num-
bers with a certain property and we're checking whether a number is a prime. As shown in
Example 8-35 , we can easily refactor this to split apart these two responsibilities.
Example 8-35. Counting prime numbers after refactoring out the isPrime check
public
public long
long countPrimes ( int
int upTo ) {
long
long tally = 0 ;
for
for ( int
int i = 1 ; i < upTo ; i ++) {
iif ( isPrime ( i )) {
tally ++;
}
}
return
return tally ;
}
private
private boolean
boolean isPrime ( int
int number ) {
for
for ( int
int i = 2 ; i < number ; i ++) {
iif ( number % i == 0 ) {
return
return false
false ;
}
}
return
return true
true ;
}
Search WWH ::




Custom Search