Skip to end of metadata
Go to start of metadata

The Bouncer Pattern describes usage of a method whose sole purpose is to either throw an exception (when particular conditions hold) or do nothing. Such methods are often used to defensively guard pre-conditions of a method.

When writing utility methods, you should always guard against faulty input arguments. When writing internal methods, you may be able to ensure that certain pre-conditions always hold by having sufficient unit tests in place. Under such circumstances, you may reduce the desirability to have guards on your methods.

Groovy differs from other languages in that you frequently use the assert method within your methods rather than having a large number of utility checker methods or classes.

Null Checking Example

We might have a utility method such as:

And we would use it like this:

But a more Groovy way to do this would simply be like this:

Validation Example

As an alternative example, we might have this utility method:

And we would use it like this:

But with Groovy we could just as easily use:

  • No labels

1 Comment

  1. Seems like a bad idea to replace meaningful exceptions with assertion errors. Someone using your api may use a try block, and even if they're lazy and catch all Exceptions, they won't catch Errors which should only be thrown if your code is really really broken, like from assertions during unit tests, but not in production. That's why Java assertions are disabled by default and testing frameworks like junit enable assertions.