Skip to content

Backend Pattern Delegation

Ferris Tseng edited this page Jan 2, 2020 · 6 revisions

[Pattern] Delegation

Description

Delegation is a pattern that reduces code repetition by allowing an object to pass calls for a method to another object, the delegate.

Location

N/A

Best Practices

There are a few common ways to delegate method calls that we use in Caseflow:

The delegate method

Rails provides a delegate method that allows you to delegate methods to a related object. This pattern is commonly used in our models to call methods on related objects and avoid declaring redundant methods.

class Hearing < ApplicationRecord
  ...
  delegate :available_hearing_locations, :closest_regional_office, :advanced_on_docket?, to: :appeal
  delegate :external_id, to: :appeal, prefix: true
  ...
end

The prefix parameter can be used to prefix the new method name to avoid method naming collisions. 1

The SimpleDelegator class

The SimpleDelegator class is an easy way to delegate all methods of an object to a second object. Using SimpleDelegator is a good way to add additional functionality onto a class without adding to the class itself.

Tradeoffs

delegate is preferred to SimpleDelegator when you only need to delegate a subset of methods to the second object.

Resources

Examples in Caseflow

Additional Reading

Related Patterns

Pattern Description
Clone this wiki locally