Skip to content

Latest commit

 

History

History
13 lines (10 loc) · 1.08 KB

File metadata and controls

13 lines (10 loc) · 1.08 KB
rule_id 1002
rule_category class-design
title Only include parameters in a constructor that most or all members need

A constructor exists to put the object in a valid, usable state. If a value or dependency is only needed by a single method, consider passing it as a method parameter instead. This keeps the constructor focused and avoids forcing every caller to provide something that is barely relevant to the object as a whole.

For internal types, this is straightforward to apply: since callers are within the same codebase, moving a rarely-used parameter from the constructor to a method parameter is a low-risk refactoring.

For public types, be more conservative. Removing a constructor parameter is a breaking API change, so consider whether the dependency is likely to be needed by future members before deciding to keep it out of the constructor.

Important

Exception: Cross-cutting concerns such as logging or a clock abstraction (TimeProvider) are often needed broadly and may reasonably be injected through the constructor even if not every member uses them directly.