Last week I upgraded Rubocop to 0.53. I ran the test suite and noticed a new warning called
Naming/MemoizedInstanceVariableName, which targets methods that use an instance variable for memoization. Here is an example that would trigger the warning:
@hello ||= user_greeting
Rubocop raises an error because the method name is different from the name of the instance variable, used for memoization. This seems sensible so I started working through the failing tests and fixing them. As I fixed tests I began to find bugs. I realised that the
Naming/MemoizedInstanceVariableName warning is super useful. Here’s an example of a bug that I uncovered:
@user ||= User.create!
@user ||= Admin.create!
This bug occurred in my test code, probably due to careless copy/pasting. It could occur in application code just as easily. The bug is that calling the
user method will create a
User and memoize it. When
admin is called, instead of creating an
User object is returned.
Upgrading ensures that this type of bug will never occur again. Thanks Rubocop!
Subscribe to get articles like this in your inbox, every week.
You'll get my latest blog posts as well as article, book and podcast recommendations. All about tech.