Crisp boundaries

by Jason Swett,

If you’re going to make a change to an area, you have to understand that area. If you don’t understand the area you’re changing very well, your lack of understanding might lead to you accidentally introducing a bug.

Well-written code is loosely coupled from the other pieces of code it touches. “Loosely coupled” means that if you have classes A and B which talk to each other, you can understand class A without having to know much about class B and vice versa.

Conversely, if A and B are tightly coupled, then you might have to understand both class A and class B just to understand class A. Tight coupling makes code harder to work with.

One aspect of loosely-coupled code is that it has crisp boundaries, which are the opposite of blurry boundaries. Here’s an example of a piece of code with blurry boundaries.

class Person
  def initialize(params)
    @name = params[:name]
  end
end

person = Person.new(params)

The only thing Person needs from the outside world is a name, but Person is accepting the broader params as an argument.

Looking outward from inside the Person class, we might wonder: what exactly is in params? Who knows! It could be anything.

The inclusion of params is a “leak” from the outside world into Person.

Looking the other direction, from outside Person inward, we might see Person.new(params) and wonder what exactly of params Person needs in order to do its job. Does Person need everything inside of params? Just some of it? Who knows! Could be anything.

Let’s contrast the blurry-boundary code above with the crisp-boundary code below.

class Person
  def initialize(name)
    @name = name
  end
end

person = Person.new(params[:name])

In this case, looking outward from inside the Person class, it’s clear that Person takes a name and that’s it.

And then looking in from outside, Person.new(params[:name]) makes it clear exactly what’s being sent to Person.

In order to make your classes and methods more understandable, keep your boundaries crisp by accepting the minimum amount of argument information necessary in order to get the job done.

Leave a Reply

Your email address will not be published. Required fields are marked *