Robert C. Martin
“Master programmers think of systems as stories to be told rather than programs to be written.”
Description
Branching and looping are widely used in computer programming and they may be some of the basics in coding. Have you ever reached such a high level of branching and looping that your code just became hard to read?
How about someone else taking a look at the code, how easy would it be for him to understand your intent? What about testing the code?
Recently I’ve been studying some of the best practices in making understandable code and I reached the conclusion that a good code should be written in a “human language” manner
Example. Given a set of persons:
class Adress { public string City { get; set; } } class Person { public string Name { get; set; } public Adress Adress { get; set; } public int Age { get; set; } } static Adress NY = new Adress { City = "New York" }; static Adress Delhi = new Adress { City = "Delhi" }; static List<Person> persons = new List<Person> { new Person{ Name = "John", Age = 22, Adress = NY}, new Person{ Name = "Bob", Age = 88, Adress = Delhi}, new Person{ Name = "Maria", Age = 21, Adress = null}, };
Demand: Let’s say you want the names of all the persons that are in Delhi with age over 22. A common way of writing this would be:
List NamesOfPersonsInDelhiOver22 = new List(); foreach (Person person in persons) { if (person.Age > 22) { if (person.Adress != null) { if (person.Adress.City == "Delhi") { NamesOfPersonsInDelhiOver22.Add(person.Name); } } } }
The problems in the above code are:
- Readability which is obviously not so great
- Branching. It’s a simple exercise but think what it would look like if you were asked to add new features like “get only males, sort by age” et
- Each new brach would add more complex tests to validate the solution
Linq provides a very good framework that would help you write this like:
public static bool PersonAdressIsNotNull(Person person) => person.Adress == null; public static bool PersonCityIsDelhi(Person person) => person.Adress.City == "Delhi"; public static string PersonName(Person person) => person.Name; NamesOfPersonsInDelhiOver22 = persons.Where(PersonAgeIsOver22) .Where(PersonAdressIsNotNull) .Where(PersonCityIsDelhi) .Select(PersonName) .ToList();
Does this solution look more readable?