Skip to content
Katabench
Try free

A Rule Tree Can Contain Any Rule

Hard About 40 min Free, no account needed

Replace a central tagged-tree evaluator with recursive rule objects that preserve child order, empty identities, and short-circuit behavior.

The brief

An eligibility engine understands a tagged tree: each node says min, and, or, or not, and the engine recursively switches on those tags. Adding a new leaf rule means editing that central interpreter. Replace it with a Composite design in which every leaf and branch honors the same contract.

Introduce IRule with bool Evaluate(int score). MinimumRule(int minimum) checks score >= minimum. AllRule(IEnumerable<IRule>) succeeds when all children succeed; AnyRule(IEnumerable<IRule>) succeeds when any child succeeds; NotRule(IRule) negates its child. The two collection composites copy their constructor input so later caller mutation cannot rewrite the tree. Keep all four implementations sealed and their fields readonly. They must accept arbitrary IRule implementations, including other composites.

EligibilityEngine accepts one IRule root, holds it readonly, and delegates evaluation. It must reference neither RuleNode nor any concrete rule class. Composition belongs to Solution. Remove the obsolete tagged-tree representation.

Preserve Run(string[] tokens, int score). Tokens are a valid postfix expression: min:<integer> pushes a leaf, not wraps the last rule, and and:<count> or or:<count> combines the last nonnegative count rules in their original order. Exactly one root remains. Empty AND is true; empty OR is false. Do not mutate tokens.

Evaluation is left-to-right and short-circuits: stop AND at its first false child and OR at its first true child. Evaluate each reached child once per occurrence; do not deduplicate repeated child objects or cache their result across calls. A trusted probe supplies counting leaves and a leaf that throws if reached unnecessarily, and mutates the constructor array after building a composite. A type-correct wrapper around an eager evaluator or a borrowed mutable array fails that probe.

How it is graded

Executable structural checks grade the shape of your types as well as their behavior.

SOLID principles exercises →

What it practices

Decorator and composite patterns
Wrap or nest objects behind one interface so behaviors stack and trees evaluate uniformly.
Replace conditional with polymorphism
Move each branch of a type switch into the type that owns it.

Related katas