Josh Hepworth

Service Objects: Keeping It Simple

While jargon allows people familiar with the subject matter to easily talk about more complex ideas, it also makes it hard to come in from the outside. I often come across new idioms in programming that already have their own name, but no simple explanation or example available for me to quickly understand what someone is talking about.

Something I struggled with for a while was the idea of a "Service" layer. It turns out my initial ideas about it were very overthought. Here's a service layer for a Rails project:

#app/services/greeter.rb
class Greeter
  def self.call(user, mailer = WelcomeMailer)
    mailer.sign_up(user).deliver
    user.update(:greeting_message, "Hi there!")
  end
end

#app/controllers/registrations_controller.rb
class RegistrationsController < ApplicationController
  def create
    user = User.create(params[:user].permit(:email))
    Greeter.call(user)
    render :show
  end
end

It's just a class that does something. Don't overthink it. Use a service layer to simplify complex actions elsewhere in your code, and don't worry about some huge complex idea that sounds intimidating to implement.