Have consistent return values for an object type

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the object-oriented-programming category.

Last Updated: 2024-03-28

In many Rails applications, there are service objects everywhere, it being a bit of an overused pattern. A major point of inconsistency in many codebases is the return values from these objects. Here's an example from a codebase I worked on:

# Returns nil no matter what
User::NotifyAdminsService.call(args)

# Returns {lat: x, long: y} if success, false if fail
User::GeocoderService.call(args)

Due to these inconsistencies, its difficult to predict, from API and method signatures alone, what is expected in terms of return values from these service objects. It would be better if clear expectations about return values where made.

What are one's options?

  1. In certain object categories, consider always returning nil.

  2. Consider having a separate method for when the return value matters

    • e.g. User::GeocoderService.calculate(), which has has clearer semantics. .call() might here be reserved be expected to return nil.
  3. OR, have service's call method always return a value, but use enqueuing or event publishing in situations where no return value should be given.

Lesson

Consider the shared API across entire categories of objects as a holistic unit and establish consistent semantics about return values (and perhaps input method signatures too)