Java – is this too much refactoring?
I try to refactor the code so that it will use a separate method to do some calculations Just to make it clear
What I want to know is, is it a good habit or a bad thing to write a separate method to find simple things like numbers, odd or even?
The original code is,
int n = 11; if (n % 2 == 0) { System.out.println("Not selected"); } else { boolean isPrime = true; if (n == 0 || n == 1) { isPrime = false; } else { int i = 2; double a = Math.sqrt(Math.abs(n)); while (i <= a) { if (n % i == 0) { isPrime = false; } ++i; } } if(isPrime){ System.out.println("Prime it is"); } }
The refactored code is,
int n = 11; if (isEven(n)) { System.out.println("Not selected"); } else { if (isPrime(n)) { System.out.println("Prime it is"); } } public static boolean isEven(int n) { return n % 2 == 0 ? true : false; } public static boolean isPrime(int n){ if(n==0 || n==1)return false; int i=2; double a = Math.sqrt(Math.abs(n)); while(i<=a){ if(n%i==0){ return false; } ++i; } return true; }
Solution
For readability, length, or cyclomatic complexity, it is often considered a good practice to break down the code into separate methods, especially if you don't change the way the code works
Boolean expressions, like what you extract, are usually a good choice for fast extraction function refactoring It allows readers of the code base to understand why Boolean expressions are important or what they do by being able to read Boolean mathematics related to descriptive function names and complex fields. They may not need to know the intricate details
A good book on Java best practices in code organization is a book called clean code This is a very simple and pleasant reading, I suggest it