cft

Improve Your Software Design with The CheckAndDo Pattern ๐Ÿ“‹

Improve Your Software Design with The CheckAndDo Pattern ๐Ÿ“‹


user

Abdulcelil Cercenazi

3 years ago | 1 min read

Why another design pattern? ๐Ÿ˜ 

It is a widely common task in Software to perform tests on an object and obtain the result of this process.

In Other Words โš™๏ธ

Letโ€™s imagine a pipeline of checks that an entity has to pass before being persisted to a database.
On every step, we want to return the reason for the check failure, if it does. Otherwise, we want to proceed to the next check.

A Real Life Example

Letโ€™s write a function to verify that a given password ๐Ÿ— meets certain criteria.
Length should be between 8 and 14 characters.
Should have at least one upper case character and one lower case character.
Should have at least 2 digits.
Should have at least one special character.

Typical Solution ๐ŸŸก

Letโ€™s do it using Java code

What was wrong with it? ๐Ÿšฉ

The implementation above has many flaws, however, the most important two are:
Breaks the single responsibility principle, as this function does more than one check (six ones to be exact).
The function checkPasswordAndSubmit is about 20 lines long, which can be shorter if implemented correctly.

H3he checkAndDo pattern way ๐ŸŸข

We add a chain of check functions, each one tests a single aspect.
Note the naming convention of the functions check_*And_ where:

  • * is the current check we are performing.
  • ** is the final action we want to be done. For example checkPassWordLengthAndSubmit checkPassWordCaseSensitivityAndSubmit checkThatTwoDigitsAreGivenAndSubmit checkThatSpecialCharactersAreGivenAndSubmit

So, should you use this pattern? โ”โ“

if you have a lot of tests to run over an object, and if you want to run a specific action for each testโ€™s result, then this pattern will provide you with a clear, plug-like design to ensure that you wonโ€™t get lost while trying to understand what goes where.

Code on GitHub๐Ÿ–Š

Upvote


user
Created by

Abdulcelil Cercenazi

I love to learn and teach. Follow me for Software development/Clean coding topics :)


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles