Write domain logic using domain terms (1 min read)
View this email in your browser
Abstraction in software should enhance understanding.

Levels of Abstraction

Imagine you're working on a new project, and come across some code like this:

if((user.Roles.Any(r => r.Id == 17)) && 
articleRepository.GetArticle(articleId).Authors.Any(a => a == user.Id) ||
user.Roles.Any(r => r.Id == 18))

After a bit of effort, you're able to discern that there is a role with an ID of 17 that corresponds to "Authors", and one with an ID of 18 that corresponds to "Editors". You determine that this bit of code is checking to see if a user is either the author of an article corresponding to a given ID value or an editor. It's likely you'll see this kind of verbose code throughout the codebase, or at least a certain layer of it, since code tends to follow the conventions of the code around it.

What if, instead of all of the low-level code and plumbing and magic numbers above, you read this code:


Wouldn't that be easier to follow? If you were reading the code because you were looking for the section of code where the article is displayed to the user, wouldn't this let you identify that section much more easily? This is an example where modifying the level of abstraction used within a method can improve understanding and comprehension for readers of the code. And remember, even for codebases that have a single author, code is read many times more often than it is written, so it's worthwhile to optimize for readability and clarity.

Detailed, low-level code is important, but keep it in its place and don't let it pollute your business logic or user interface layer any more than necessary. Capture the details in a method, and give the method a name that comprises the higher level operation the low level code is implementing. Just as it's more efficient to read and write with a higher level programming language than with 1s and 0s, the APIs that we create in the course of writing our own applications should properly utilize abstractions to improve our ability to quickly understand and evolve our solutions.

Learn more about how you can do exactly the kind of thing shown in the example above in my article, Favor Privileges over Role Checks.

Keep improving!
Steve (@ardalis)

PS - Please help spread the word about this new C# tutorial on the new .NET Core site.

Image Credit

Copyright © 2016 Ardalis Services, All rights reserved.

Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list

Email Marketing Powered by MailChimp