Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

The Introduce Assertion refactoring recommends that each method (and potentially each constructor) checks its preconditions using assertions.

This is a particular form of defensive programming. Some argue that if you have sufficient tests in place, you don't need to apply defensive programming. For the small extra performance penalty, it seems like a small price to pay for extra resilience in our system.

Example

Suppose we have the following method:

If we call it with valid parameters, everything is fine. If we call it with null we will receive a NullPointerException during the method's execution. This can sometimes be difficult to track down.

Applying this refactoring gives us the following code:

This is better because we become aware of any problems straight away.

  • No labels