← Graph

Null Object Pattern

concept 4 connections

Pattern Ivan Nemytchenko recommends as the cure for `if current_user` checks scattered across views and controllers. Instead of returning nil (or a fake OpenStruct in a helper), implement a plain Ruby object (e.g. Guest) that responds to every method on the real type (admin? → false, moderator? → false, name → 'Guest'). The controller tries to find a real user; if absent, returns the guest object, so views use it polymorphically with no conditionals. More broadly: different types of entities (e.g. users under 18 behaving differently from regular users) should also be separate models — not necessarily null, but distinct polymorphic types. Yields polymorphic behavior 'for free' and logic-less controllers and views.

category
pattern
about
Null Object Pattern concept
Proposes Guest-style null objects as the cure for `if current_user` checks in views and controllers.
tool Mimic
about
Null Object Pattern concept
Mimic implements the null-object pattern: given a class, it returns an inert implementation of that class's interface.
about
Null Object Pattern concept
Identifies Mimic substitutes as an implementation of the null-object pattern.
recommends
Null Object Pattern concept
Ivan Nemytchenko recommends null objects (e.g. Guest) to eliminate current_user conditionals.

Provenance

Read by
8 extractions