O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.1. Validating Parameters Passed to a Method

Problem

You want to validate the parameters passed to a method.

Solution

Create an aspect that modularizes the parameter checking logic. Declare a pointcut to capture the execution of the method where the parameters are to be checked. The pointcut should expose the parameters to the corresponding advice so it can perform the checks.

Depending on the result of the parameter checking, the advice will proceed with the methods execution or safely override the method whenever the parameters are not suitable.

Discussion

Validation of method parameters is a chore every developer has to be concerned with whenever he has no control over how his clients will use a component. Even when the developer is writing the clients that will use a particular component, a useful practice would be to the values passed to a method are acceptable before working with those values.

This checking often confuses the logic within a method by introducing initial checking code that has little relationship to the job that the method is to complete. By using AspectJ, you can check a method’s parameters separately from the core business logic of a method to make the solution cleaner.

The main method on a Java application is a common place where the parameters being supplied cannot be controlled and have to be checked before the application can continue execution. The normal means of achieving these checks is to code the test logic using an if statement into the main method ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required