How to keep the code simple and the objects in charge? - Part 2
KISS, DRY and YAGNI keep the code simple, while Tell Don't Ask and the Law of Demeter keep the logic near the data, explained with mutual fund redemption and NAV examples.
How to keep the code simple and the objects in charge? - Part 2
Most of the maintenance problems do not come from a complex algorithm, they come from code which is more complicated than the problem needs, copied in many places, or written for the requirements which never came. On top of that, we have the objects which are only holders of data, and all the real decisions are taken by the other classes. In the previous article, we discussed why code becomes hard to maintain, and what is cohesion and coupling. In this article, we are going to see three simple guidelines, KISS, DRY and YAGNI, and two principles which keep the logic close to the data, Tell Don’t Ask and the Law of Demeter.
Maintainable Code series:
- Why does code become hard to maintain? - Part 1
- How to keep the code simple and the objects in charge? - Part 2 (this article)
- What are the Single Responsibility and Open Closed principles? - Part 3
- What are the Liskov Substitution and Interface Segregation principles? - Part 4
- How to use Dependency Inversion to loosen the coupling? - Part 5
TL;DR Summary
- KISS (Keep It Simple, Stupid) - Choose the simplest design which solves today’s problem.
- DRY (Don’t Repeat Yourself) - Every piece of knowledge should have one place in the system.
- YAGNI (You Aren’t Gonna Need It) - Don’t build a feature until it is really needed.
- Tell, Don’t Ask - Tell an object what to do, don’t ask for its data and decide on its behalf.
- Law of Demeter - Talk only to your friends, not to the friends of your friends.
- The last two make the code easy to test, and the logic lives in one place, near the data.
The three guidelines
KISS, DRY and YAGNI are not object oriented principles, they are general guidelines. But they protect every other principle in this series from being over done, so let us discuss them first.
KISS - Keep It Simple, Stupid
Complexity is the enemy of maintenance, because every reader of the code must pay for it. Between two designs which solve the problem, the simpler one is the better one.
Example: the exit load of a fund is 1% if the units are redeemed within one year, otherwise it is zero. A developer who builds a configurable rules engine with a rule parser for this requirement makes the code harder to read than the problem itself.
public decimal CalculateExitLoad(decimal amount, int holdingDays)
{
return holdingDays < 365 ? amount * 0.01m : 0m;
}
Start with this. When the second and the third rule arrive, we have real information to design a better structure, and we will see that in Part 3.
DRY - Don’t Repeat Yourself
Every piece of knowledge, a business rule, a formula or a constant, should have a single and unambiguous place. When the same rule is copied to many places, a change to the rule needs a change in every copy, and one forgotten copy is a bug.
Example: the NAV is rounded to four decimal places. If the rounding is written in the statement, the website and the email alert separately, and the fund house changes the precision, we must find all three places, otherwise customers see different NAV in different places.
public static class Nav
{
public const int Precision = 4;
public static decimal Round(decimal value)
{
return Math.Round(value, Precision, MidpointRounding.AwayFromZero);
}
}
Must Be Aware: DRY is about knowledge, not about the lines of text. Two pieces of code which look same but change for different reasons should not be merged, otherwise one change will force the other.
YAGNI - You Aren’t Gonna Need It
Don’t write code for a requirement which is not there today. Every unused feature must be designed, tested, understood and maintained, and mostly we guess wrong about it. If the fund house invests only in rupees today, don’t build multi-currency support just because it may come in future. Add it when it is needed, and the clean design we are discussing in this series makes that addition cheap.
Tell, Don’t Ask
Now let us move to the first object oriented principle of this article. Ask for help, don’t ask for information. When one object asks another for its data, and then takes the decision on its behalf, the logic is separated from the data it belongs to. In procedural code, this is normal. In object oriented code, it is a smell.
The following diagram explains the difference with a redemption.

Find below the “ask” version,
public void Redeem(Folio folio, decimal units)
{
if (folio.GetUnits() < units)
throw new InvalidOperationException("Insufficient units");
var amount = units * folio.GetNav();
folio.SetUnits(folio.GetUnits() - units);
// ...
}
The rule “you can’t redeem more than you hold” lives in the service. Any other class which changes the units, for example a switch, must remember to copy the same check. If one forgets, the folio goes to a wrong state. Now the “tell” version,
public class Folio
{
private decimal _units;
public decimal Redeem(decimal units, decimal nav)
{
if (units > _units)
throw new InvalidOperationException("Insufficient units");
_units -= units;
return units * nav;
}
}
// the service only tells
var amount = folio.Redeem(units, nav);
The rule is now in one place, near the data. The units are private (this is the encapsulation pillar working for us), and there is no way to put the folio in a wrong state.
Benefits
- Easy to maintain the object oriented code, because the logic is in one place.
- Improves the reasoning, you need to read only one class to know what happens.
- Reusability, every caller gets the rule for free. It reduces the code, the bugs and the development time.
- Easy testing, you test the Folio alone with simple inputs and outputs.
Note: It doesn’t mean every object must hide everything. Objects which only carry data across a boundary, for example the view model of an ASP.NET MVC view or a Data Transfer Object (DTO), are meant to expose the data. Apply Tell Don’t Ask to the objects which have behavior.
The Principle of Least Knowledge (Law of Demeter)
The Law of Demeter says, a method should talk only to its friends and not to the friends of its friends. In simple terms, an object should not know the internal structure of the other objects. The friends of a method are, the object itself, its parameters, the objects it creates and its direct components.
The following diagram depicts a statement printer which knows too much.

// The printer walks through the whole structure
var nav = investor.Folio.Fund.NavHistory.Latest().Value;
var value = folio.Units * nav;
This one line of code knows that the Investor has a Folio, the Folio has a Fund, the Fund has a NavHistory and the NavHistory has a Latest. If any one of these changes, for example a Folio can hold more than one Fund, the printer breaks, and so do all other callers who copied this line. Let us fix it by asking the friend,
public class Investor
{
public decimal GetPortfolioValue()
{
return _folio.GetValue();
}
}
// the printer
var value = investor.GetPortfolioValue();
Now the printer knows only the Investor. The internal structure is free to change, as long as the Investor keeps its promise.
Benefits
- Easy to maintain, the changes stay local.
- Easy testing, you need to build and fake only the direct friend and not the whole object graph.
Must Consider: Following the law blindly creates many small delegating methods on the classes. Be mindful, a fluent chain on the same object (a builder or a LINQ query) is not a violation, because it talks to the same friend again and again. Apply the law at the object boundaries, where the structure of one object leaks to another.
Wrap up
In this article, we have looked at KISS, DRY and YAGNI, the Tell Don’t Ask principle and the Law of Demeter, and how they keep the logic simple and close to the data. I appreciate your time and efforts to read this article. In the next article, I will walk you through the first two SOLID principles, the Single Responsibility Principle and the Open Closed Principle.
Related Posts
How to use Dependency Inversion to loosen the coupling? - Part 5
Dependency Inversion is explained with layered and multi-implementation examples, dependency injection, IoC containers, testing benefits and a summary of all the principles.
What are the Liskov Substitution and Interface Segregation principles? - Part 4
Liskov Substitution and Interface Segregation are explained with open-ended funds and fixed maturity plans, including the warning signs of a broken hierarchy and how to fix it.
What are the Single Responsibility and Open Closed principles? - Part 3
The Single Responsibility and Open Closed principles are explained with a mutual fund service and exit load rules, with the benefits, techniques and trade-offs of each.