Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Object Calisthenics70 XP7 min

No Classes with More Than Two Instance Variables

Limiting state to two instance variables dramatically increases cohesion β€” if you need more, decompose into a hierarchy of collaborating objects.

Why this matters

Every extra instance variable beyond two is a sign of a hidden concept waiting to become its own class. A class with seven fields like firstName, lastName, street, city, country, email, and phone is really four concepts β€” Name, Address, Location, and Contact β€” jammed into one. Decomposing them reveals the domain structure and dramatically increases cohesion: every method in a two-variable class uses both variables, which is the definition of maximum cohesion.

Code Challenge

Study the messy code, try to refactor it, then reveal the clean version.

πŸ’‘Key takeaway

Every extra instance variable beyond two is a hidden concept waiting to become its own class. Decompose until each class has at most two fields β€” the resulting hierarchy will reveal the true structure of your domain.

πŸ”§ Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it β€” it helps us fix it fast.

Hint: Every extra instance variable beyond two is a sign of a hidden concept waiting to become its own class.

βœ— Your version

No Classes with More Than Two Instance Variables β€” CleanKata β€” CleanKata