Skip to content
Advertisement

Java – Using Validators to implement variable numbers of “if” statements

According to the solution presented here by daniu, the Composite pattern can be used to maintain a list of Validators to test all the needed conditional tests. But I didn’t understand how to use it. Below are my conditional tests and the provided code that he made available.

My conditional tests:

JavaScript

Validator interface:

JavaScript

Interface implementation:

JavaScript

Use of implementation:

JavaScript

Thank you in advance.

Advertisement

Answer

For simplicity, lets assume that we have an InfoObject object with the fields.

JavaScript

And our task is to validate that this InfoObject input is correct. One approach was to use the if-else condition, but if the number of validations required increases then the if-else code might become messy.

Next, we can directly use the ValidatorComposite class and define our custom validators.

JavaScript

And we can define the following functions. Sorry for the functions name, I didn’t know the actual use case, so used some dummy names:

JavaScript

How does this code work?

We defined a list of validators. The validate() function will call all the validators one by one, and it will stop when one of the validators returns the NOT_OK result.

In addValidator function, we have a lambda function infoObject -> fourthCheck(infoObject) ? Result.NOT_OK : Result.OK, which returns a functional interface.

There are a lot of concepts involved in this example, to learn about more concepts please refer to:

  1. Composite pattern
  2. Lambda Expressions
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement