When should I use a component instead of a class in EK9?
← Code Quality · Ref: Q856
A class with 4+ service fields (traits/abstract types) and 0 data fields is architecturally a service coordinator — it should be a component, not a class.
COMPONENTS vs CLASSES
- Component: singleton lifecycle, service coordination, DI
- Class: multiple instances, data + behavior
THIS EXAMPLE
ServiceCoordinator uses 4 trait dependencies. It is correctly defined as a component. If it were a class, E11022 would fire.
See Q111 for components. See Q227 for DI.
Example
defines module qa.quality.class.vs.component defines trait ServiceA doA() abstract ServiceB doB() abstract ServiceC doC() abstract ServiceD doD() abstract defines class ImplA with trait of ServiceA override doA() require true ImplB with trait of ServiceB override doB() require true ImplC with trait of ServiceC override doC() require true ImplD with trait of ServiceD override doD() require true defines component ServiceCoordinator svcA ServiceA: ImplA() svcB ServiceB: ImplB() svcC ServiceC: ImplC() svcD ServiceD: ImplD() orchestrate() svcA.doA() svcB.doB() svcC.doC() svcD.doD() default operator ? defines program ComponentDemo() stdout <- Stdout() stdout.println("Component handles service coordination")
Common mistakes
E11022 — A class with only service/trait fields and no data fields is a service coordinator. Use 'defines component' instead. See ek9 -h E11022 for details.
Incorrect:
defines class
Correct:
defines component
Other ways to ask this
- What triggers E11022 CLASS_SHOULD_BE_COMPONENT?
- Why does EK9 reject my class with service fields?
- What is the difference between class and component in EK9?
Coming from another language?
Java: no class/component distinction — Spring @Component is optional. C#: no language-level enforcement. Go: no component construct. EK9: compiler enforces class vs component based on field analysis.
Keywords: service, quality, trait, design, component, E11022, field, class