Skip to main content

# 14.3: Method Composition

Once you define a new method, you can use it as part of an expression, or build new methods using existing methods. For example, suppose someone gave you two points, the center of the circle and a point on the perimeter, and asked for the area of the circle. Let’s say the center point is stored in the variables xc and yc, and the perimeter point is in xp and yp.

The first step is to find the radius of the circle, which is the distance between the two points. Fortunately, we have a method that does just that (distance).

double radius = distance(xc, yc, xp, yp);


The second step is to find the area of a circle with that radius. We have a method for that computation too (calculateArea).

double area = calculateArea(radius);
return area;


Putting everything together in a new method, we get:

public static double circleArea (double xc, double yc, double xp, double yp) {
double radius = distance(xc, yc, xp, yp);
double area = calculateArea(radius);
return area;
}


The temporary variables radius and area are useful for development and debugging, but once the program is working we can make it more concise by composing the method calls:

public static double circleArea (double xc, double yc, double xp, double yp) {
return calculateArea(distance(xc, yc, xp, yp));
} 

This example demonstrates a process called functional decomposition; that is, breaking a complex computation into simple methods, testing the methods in isolation, and then composing the methods to perform the computation. This process reduces debugging time and yields code that is more likely to be correct and easier to maintain.

• Was this article helpful?