Easy To Read != Easy To Understand
I ran into this code a while back:
1: public abstract class ScanPrefixSpecification : IScanSpecification
2: {
3: public abstract IEnumerable<string> BarcodePrefixesFilter { get; }
4:
5: public bool IsSatisfiedBy(string item)
6: {
7: return BarcodePrefixesFilter.Where(item.StartsWith).Any();
8: }
9:
10: public string GetScanFrom(string scanString)
11: {
12: foreach (var prefixFilter in BarcodePrefixesFilter.Where(scanString.StartsWith))
13: {
14: return scanString.Substring(prefixFilter.Length);
15: }
16: return "";
17: }
18: }
</div> </div>
There isn’t anything wrong with this code from a technical standpoint. It does exactly what it needs to do and it provides a specific point of functionality in our system. By reading the code and by reading the tests around this code, I can see what this class does:
- it’s a basic specification pattern where the scanned item satisfies the specification when the “item” starts with any of the strings found in the BarcodePrefixesFilter list
- and it removes the first match found in the BarcodePrefixesFilter list from the beginning of the “scanString”; or returns an empty string if no matches were found
Ok, that’s great… now, why does it do that? Where does this code express the needs of the business; the understanding of why those characters need to be removed from the front of the scanned string? How much additional code am I going to have to read to understand the context of this code? How long will it take me to understand what functionality this code facilitates, from a functional view of the system?
… easy to read is not the same as easy to understand. Be sure your code is understandable, not just readable; and the only way to do that is for someone else to look at your code and work with it.