Models don't have a sense of smell

Pepijn KrijnsenPepijn Krijnsen
2 min read

Modern IDEs are great at highlighting errors as soon as you type them. AI assistants improve on this by spotting antipatterns and suggesting alternatives. Neither of them identify the root cause that led to the antipattern in the first place. Human developers add value by interpreting the information provided by their tools.

One of the ways we do this is by recognising and investigating code smells.

The smell test

A code smell is an easy-to-spot indication that something may be wrong. Common examples include:

  • Long parameter lists
  • Very large methods or classes
  • Classes without methods
  • Feature envy

While none of these are particularly harmful, the reason that the smelly code was written in the first place may point to a deeper problem.

Let's take a look at a practical example.

Follow your nose

Imagine a Contractor class with fields name: str and hourly_rate: float, and a method calculate_value_of_worked_hours(self, hours: float) -> float. Expressive names, straightforward attributes.

Now the business asks for a way to prepare a full invoice for a contractor. This new feature should take into account:

  • Period to be billed
  • Maximum number of permitted hours per a given period
  • Overtime rate for hours over the permitted number

This is implemented by naively adding three more parameters to the existing function.

def calculate_value_of_worked_hours(
        self,
        hours: float,
        period: tuple[datetime.date, datetime.date],
        max_hours: float,
        overtime_rate: float
        ):

The smell is having a method with four parameters -- five if you count self. It's easy to spot and not by itself a problem.

The problem is in the design. The number of permitted hours per given period should not be coupled to behaviour on a class named Contractor: that's an attribute of the applicable labour laws. A better solution would be to create a new Invoice class that uses instances of Contractor and data from other modules.

Why AI can't smell

Your AI assistant can refactor a large method into a new class in seconds, but they can't come up with that strategy without explicit direction. AI excels at the "how" of refactoring. Humans excel at the "why" and "when".

Recognising and acting on smells remains a crucial skill for any developer working in moderately complex systems. Start by asking: "What does this smell tell me about the design?"

What code smell led you to discover a deeper design problem? Share your story in the comments.

Resources

0
Subscribe to my newsletter

Read articles from Pepijn Krijnsen directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pepijn Krijnsen
Pepijn Krijnsen