Programs

Modularity in Java Explained With Step by Step Example [2022]

When you set out to be a Java programmer, there are ample amount of opportunities. On average, a Java programmer earns around $69,722 per month, which is a handsome payout. Learn more about Java developer salary in India. If you plan to have a sound career in Java programming, then modularity is something you should learn first. It is one of the vital parts of modern software programming. So, let’s first understand what a module is?

What is Modularity in Java?

A module is more like an independent partition of software that is communicated through an interface. Modularity explores the creation of a program by using different modules than a single legacy architecture. It is more like microservices in an MVC architecture, where the entire system is a suite of independent services. 

With modularity, the partitioning of the software environment in different modules makes the entire process more optimized and reduces the coupling effect. It helps Java developers to perform functionality testing on the go while the development process is ongoing simultaneously.

Modularity in Java makes sure that the development time is reduced with testing and debugging on the fly. 

Now that we know about modularity let’s understand why you need it?

Read: Java Interview Questions & Answers

Enroll in Software Engineering Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Why do we need Java modularity?

Modularity helps a Java developer in three ways,

Reusability: Reusability can help developers save time using the same code while creating a newer version of the software or app. With modularity in Java, you can reuse the modules elsewhere than the developed software initially. 

Stability: Modularity helps sustain the stability of software while making changes in individual sections of the code. It means that the new modifications remain hidden from consumers and can be easily tested without affecting the existing software. 

Parallel development: Java developers can quickly develop modules parallel to each other. Once all the modules are developed, they can be combined through an interface to create a suite. Using parallel development can save time. 

Now let’s explore different aspects of modularity in Java.

Though modularity was introduced in Java 9, we will explore the concept for Java 11 with a simple example of creating a calculator. We will create a simple and yet advanced calculator that checks on prime numbers, calculates their sum, whether a number is even or not. 

Step 1: Creating the module

The first step is to create modules, and you can choose to create multiple modules as per the complexity. Here, we are creating two distinct modules,

  1. Math. util module
  2. Calculator module

The first module has an API or Application Program Interface for executing mathematical calculations. At the same time, the second module launches the calculator.

Step 2: Executing the modules

We will execute the API module in the browser by implementing it in com.upgrad.math.MathUtil class,

public static Boolean isPrime(Integer number){

          if ( number == 1 ) { return false; }

          return IntStream.range(2,num).noneMatch(i -> num % i == 0 );

        }

We can check the module with a function.

public static Boolean isEven(Integer number){

          return number % 2 == 0;

        }

If you are thinking about checking the numbers for whether they are even or odd, we can execute another function.

public static Integer sumOfFirstNEvens(Integer count){

          return IntStream.iterate(1,i -> i+1)

                          .filter(j -> isEven(j))

                          .limit(count).sum();

        }

public static Integer sumOfFirstNOdds(Integer count){ return IntStream.iterate(1,i -> i+1) .filter(j -> !isEven(j)) .limit(count).sum(); }

So, far we executed two functions on the API models and made the following observations.

  • There is an infinite sequence starting from number 1 
  • Filtration of numbers is repeated.
  • The stream of numbers is limited.
  • Finding the sum of numbers

Based on these observations, a developer can refactor the API and execute it.

Integer computeFirstNSum(Integer count,

                                 IntPredicate filter){

  return IntStream.iterate(1,i -> i+1)

                  .filter(filter)

                  .limit(count).sum();

 }

Here, we need to find the sum of numbers that is limited by the count. We will also need to find the filter for numbers in conditions for which summing will be executed.

Let’s recreate the APIs based on the new conditions we explored.

public static Integer sumOfFirstNPrimes(Integer count){

  return computeFirstNSum(count, (i -> isPrime(i)));

}

public static Integer sumOfFirstNEvens(Integer count){ return computeFirstNSum(count, (i -> isEven(i))); }

public static Integer sumOfFirstNOdds(Integer count){ return computeFirstNSum(count, (i -> !isEven(i)));

Now that we have tested the APIs, and refactored them, let’s place the com.upgrad.math.MathUtil class in a module.

Step 3: Inserting utility class in a module

To insert a small utility class into the module named math. util, you need to follow some conventions like

  • Put all the code related to the API module in a directory of the same name, and use it as a root directory.
  • Insert module-info.java in the root folder
  • Place all the packages and codes in the root directory. 

Step 4: Creating a module definition for calculator

We will create a module of a calculator that requires math.utl.

module calculator{

  requires math.util;

}

We can compile the code by following,

javac -d mods –module-source-path . $(find . -name “*.java”)

Once we compile the codes from the calculator and math.utl modules in the mods directory, A single command will include dependencies between these two modules, which is done through a compiler. There is no need to create dedicated tools to create dependencies between calculator and maths.utl.

Step 5: Execute the code

Once you have both the modules in the mods directory and dependencies in place, now is the time to execute the code. The execution will bring our simple and advanced calculator into action. 

java –module-path mods -m calculator/com.upgrad.calculator.Calculator

Must Read: Interesting Java Projects & Topics

Conclusion

According to a survey, Java is the second-highest preferred language in terms of a new job posting, which makes it a great choice for beginners.

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Is using projects from GitHub legal?

GitHub is a web-based hosting service for Git-based software development projects. It has a graphical web interface as well as a command-line interface. There are both paid and free plans available. Private repositories are available in the expensive plans, while public repositories are available in the free plans. Many software development projects, such as the Linux kernel, Ruby on Rails, and jQuery, use it. It is permissible to use GitHub projects. Users of GitHub are free to use the software for any purpose, including commercial ones, according to the terms of service. The contributor retains the copyright to their contribution, according to GitHub's terms of service for users who contribute to GitHub repositories.

Why is Ruby a good programming language?

Ruby is a programming language that emphasizes efficiency and simplicity. Ruby's concentration on simplicity is what sets it apart. It has an elegant syntax and a sophisticated meta-programming mechanism that makes customizing and extending it quick and simple. Ruby also has a sizable and active user base. The community is eager to share new ideas and developments, and there are numerous libraries and tools accessible. Ruby is a language that can be used in a variety of ways. It's suitable for everything from simple scripts to large-scale web applications.

How do I create a good web architecture?

Your website's ideal web architecture will differ depending on your individual needs and goals. However, you can try some of the suggestions below. Before you begin constructing your website, plan out its structure. This will assist with the organization and navigation of your website. Distinguish the content of your website from its framework so it will be easier to update your website's content without having to change its structure. Make use of a content management system (CMS). It makes it easier to manage the content and structure of your website.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Contact Form

Our Popular Software Engineering Courses

Leave a comment

Your email address will not be published. Required fields are marked *

×