How do some people seem to effortlessly write such usable, clean code? This is a question that I’ve tortured myself with over this past year after having the good fortune to work alongside some incredible engineers. While trying to get to the bottom of what separates bad, good, and great one concept kept surfacing: _abstraction. _A good handle on this can work wonders for your codebase.

What is abstract code, why should you care, and how will it make you a better programmer? Abstraction is tricky to discuss because it’s, well, abstract. But I do like how John Ousterhout put it in the book A Philosophy of Software Design

The term abstraction is closely related to the idea of modular design. An abstraction is a simplified view of an entity, which omits unimportant details. Abstractions are useful because they make it easier for us to think about and manipulate complex things.

Or Steve McConnell explained inCode Complete: A Practical Handbook of Software Construction

Abstraction is the ability to engage with a concept while safely ignoring some of its details — handling different details at different levels. Any time you work with an aggregate, you’re working with an abstraction. If you refer to an object as a “house” rather than a combination of glass, wood, and nails, you’re making an abstraction. If you refer to a collection of houses as a “town”, you’re making another abstraction.

It’s the act of removing some/all concrete details so you can generalize more areas of your code for reuse. Abstraction is the weapon you can wield to fight off spaghetti code. Let’s jump right in with an example.

Here’s an ultra-simple piece of Ruby code (don’t worry if you don’t know Ruby, we’re just defining, and then calling, a function). We’re writing some code that turns our bedroom light on and off. Run it to see it’s magic at work.

Perfectly innocent-looking code, right? It does exactly what we want it to do. The light turns on and off so why is there still so much of this article left?

Almost nothing about this code is abstract. When I call the function, what light is going to turn on? Why the bedroom light, of course! It says it right there in the code. This code is _concrete _and non-flexible as it is completely _coupled _to only work with the bedroom light.

Problems arise when we need to change and reuse our code and, trust me, you always end up needing to change and reuse your code.

What if we suddenly have a kitchen that also needs lights? Our example code is unusable as it stands so we’d need to change it, duplicate it, or come up with a new solution. An easy fix would be something like this.

#software-development #computer-science #software-engineering #learning #learn-to-code #deep learning

Beating Spaghetti With Abstraction
1.15 GEEK