Memoization and DRY

Python logo

I just created an example Python repository, better_memoization, for applying the DRY (Don’t Repeat Yourself) principle to some code I found demonstrating memoization.

What is Memoization?

Memoization is a practice of storing previously calculated iterations of recursive function in a memory cache. Instead of calculating the results every time, cached results are returned when available.

The example cites a previous implementation that discusses how to add it to code, manually, then improves upon it by using a decorator. A decorator is a way to modify a function without changing the function body. This is a great example because the fib() function that is created looks identical to the original function at the beginning of the post.

Further, the memoize() function can be applied as a decorator to other recursive functions equally well. This is already some implementation of DRY.

What is DRY?

DRY, or Don’t Repeat Yourself, is a principle in programming that results in simpler code that has less potential for inconsistencies. In the cited example, the memoize() function has an if/else statement. Within each condition, the same return statement is used. Rather than having the identical return statement in each condition, move it outside of the condition. Further, get rid of the else statement and just negate the if statement.

The result? The same logic and outcome that is more efficient, easier to read, less redundant, and easier to update.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s