Which is better: code that is simple, or code that is short?
Many would answer that they frequently occur together. The length of a program is often a good indicator of how simple to understand the code will be.
But don’t make the mistake of confusing brevity with simplicity. Making a program shorter does not always make it simpler – sometimes quite the opposite.
A classic example of this phenomenon is AutoMapper, a popular .NET library. Fundamentally, AutoMapper solves the problem of too many assignment statements in your code:
userDto.Id = user.Id;userDto.FirstName = user.FirstName;userDto.LastName = user.LastName;// ... etc
What’s wrong with this code? Absolutely nothing. Lists of assignment statements are extremely easy to understand, extremely flexible, and extremely fast to run.
So why would you choose a reflection-based property loop over compile-time performance? A third-party library over built-in language support? Custom IValueResolvers and ITypeConverters over plain language statements? To save tens or maybe hundreds of lines of code? Really?
Remember, the simplest code possible does not mean the shortest code possible. DRY does not mean that all lines of code must be unique. A simple statement inlined twice is better than burying it in a ‘helper’ function.
Optimise for simplicity, not brevity.