DEV Community

Thinkster
Thinkster

Posted on • Updated on

Code Smell: Side Effects

When people say the term “side effects” we immediately think of functional programming. Having no side effects is a well-known rule of good functional programming. But the “No Side Effects” advice actually applies just as much to typical Object-Oriented Programming. It just requires a more nuanced definition of what a side effect is.

Let’s look at a few examples of functions. Just glance at this list and see if you can determine from the name what the functions actually do.

image

Those functions are fairly straightforward. They give us a description that we can interpret and make some pretty reasonable assumptions about what they do.

Now let’s imagine an implementation of one of these. We’ll use loadUser:

image

Now look closely at this function. There’s something fishy going on. Let’s break it down. First, it sets user data. Exactly what a loadUser function should do. Then it sets a loaded status of some kind on the user. Ok, we just loaded our user, so that makes sense as well. But THEN it empties out the cart. That’s our problem.

When we just look at the function name loadUser, and if we saw it being called somewhere, knowing that it empties out the shopping cart is not in any way communicated. Sure, where it’s called, it may be completely reasonable that we empty out the cart because in that call we are loading a new user. But the function doesn’t communicate that. That opens us up to some insidious problems.

What if we later on call loadUser to refresh the user data from the server? Or for some other reason, but we DON’T want the cart to be emptied when we do. Since we don’t know it’s doing that, we won’t know that we caused this problem possibly until it shows up in production with users complaining that every so often their cart just gets emptied out.

THAT is a side effect. In OO programming, side effects are when a function does something it doesn’t communicate, something that might not be anticipated. Those are side effects.

Good functions don’t have side effects, whether you’re doing OO or functional. Good functions communicate what they do so that you don’t have to dig in and read them to know what’s going on. Cognitive load is one of the biggest hurdles to programmer productivity. This practice helps keep that in check.

So keep your eyes out for this code smell, and fix it where you find it.

Signup for my newsletter at here.
Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster

Top comments (0)