DEV Community

Cover image for Modularizing Code
Paul Ngugi
Paul Ngugi

Posted on

Modularizing Code

Modularizing makes the code easy to maintain and debug and enables the code to be reused. Methods can be used to reduce redundant code and enable code reuse. Methods can also be used to modularize code and improve the quality of the program.

Here's a programs that are rewritten using a method:

Case Study: Greatest Common Divisor

Image description

By encapsulating the code for obtaining the gcd in a method, this program has several advantages:

  1. It isolates the problem for computing the gcd from the rest of the code in the main method. Thus, the logic becomes clear and the program is easier to read.
  2. The errors on computing the gcd are confined in the gcd method, which narrows the scope of debugging.
  3. The gcd method now can be reused by other programs.

Case Study: Prime Numbers

package demo;

public class PrimeNumberMethod {

    public static void main(String[] args) {
        System.out.println("The first 50 prime numbers are \n");
        printPrimeNumbers(50);
    }

    public static void printPrimeNumbers(int numberOfPrimes) {
        final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
        int count = 0; // COunt the number of prime numbers
        int number = 2; // A number to be tested for primeness

        // Repeatedly find prime numbers
        while(count < numberOfPrimes) {
            // Print the number and increase the count
            if(isPrime(number)) {
                count++; // Increase the count
                if(count % NUMBER_OF_PRIMES_PER_LINE == 0) {
                    // Print the number and advance to the new line
                    System.out.printf("%-5s\n", number);
                }
                else
                    System.out.printf("%-5s", number);
            }

            // Check whether the next number is prime
            number++;
        }
    }

    /** Check whether number is prime */
    public static boolean isPrime(int number) {
        for(int divisor = 2; divisor <= number / 2; divisor++) {
            if(number % divisor == 0) { // If true, number is not prime
                return false; // Number is not prime
            }
        }

        return true; // Number is prime
    }

}

Enter fullscreen mode Exit fullscreen mode

We divided a large problem into two subproblems: determining whether a number is a prime and printing the prime numbers. As a result, the new program is easier to read and easier to debug. Moreover, the methods printPrimeNumbers and isPrime can be reused by other programs.

Case Study: Converting Hexadecimals to Decimals

How would you convert a hex number into a decimal?
The Horner’s algorithm will leads to the following efficient code for converting a hex string to a decimal number:

int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
 decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}
Enter fullscreen mode Exit fullscreen mode

Here is a trace of the algorithm for hex number AB8C:

Image description

The program will prompt the user to enter a hex number as a string and convert it into a decimal using the following method:

public static int hexToDecimal(String hex)
Enter fullscreen mode Exit fullscreen mode

Here's the complete program:

Image description

The program reads a string from the console (line 12), and invokes the hexToDecimal method to convert a hex string to decimal number (line 14). The characters can be in either lowercase or uppercase. They are converted to uppercase before invoking the hexToDecimal method.

The hexToDecimal method is defined in lines 17–25 to return an integer. The length of the string is determined by invoking hex.length() in line 19.

The hexCharToDecimal method is defined in lines 27–32 to return a decimal value for a hex character. The character can be in either lowercase or uppercase. Recall that to subtract two characters is to subtract their Unicodes. For example, '5' – '0' is 5.

Case Study: Generating Random Characters

A character is coded using an integer. Generating a random character is to generate an integer. Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them. This section presents an example of generating random characters.

Every character has a unique Unicode between 0 and FFFF in
hexadecimal (65535 in decimal). To generate a random character is to generate a random integer between 0 and 65535 using the following expression (note that since 0 <= Math.random() < 1.0, you have to add 1 to 65535):

(int)(Math.random() * (65535 + 1))
Enter fullscreen mode Exit fullscreen mode

Now let’s consider how to generate a random lowercase letter. The Unicodes for lowercase letters are consecutive integers starting from the Unicode for a, then that for b, c, . . . , and z.
The Unicode for a is

(int)'a'
Enter fullscreen mode Exit fullscreen mode

Thus, a random integer between (int)'a' and (int)'z' is

(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1))
Enter fullscreen mode Exit fullscreen mode

all numeric operators can be applied to the char operands. The char operand is cast into a number if the other operand is a number or a character. Therefore, the preceding expression can be simplified as follows:

'a' + Math.random() * ('z' - 'a' + 1)
Enter fullscreen mode Exit fullscreen mode

and a random lowercase letter is

(char)('a' + Math.random() * ('z' - 'a' + 1))
Enter fullscreen mode Exit fullscreen mode

Hence, a random character between any two characters ch1 and ch2 with ch1 < ch2 can be generated as follows:

(char)(ch1 + Math.random() * (ch2 – ch1 + 1))
Enter fullscreen mode Exit fullscreen mode

This is a simple but useful discovery. Below code defines a class named RandomCharacter with five overloaded methods to get a certain type of character randomly. You can use these methods in your future projects.

Image description

The following code gives a test program that displays 175 random lowercase letters.

Image description

Line 11 invokes getRandomLowerCaseLetter() defined in the RandomCharacter class. Note that getRandomLowerCaseLetter() does not have any parameters, but you still have to use the parentheses when defining and invoking the method.

Top comments (0)