1. 程式人生 > >Conveying intent: Code it like you mean it

Conveying intent: Code it like you mean it

Code readability can, like a lot of things, be considered a bit like a layered cake (because who doesn’t like cake?). Being able to easily read, understand and comprehend what the code does is the first layer, and if done correctly it will provide a foundation for advanced code readability cakes to be baked on top of it. To bake the first layer of our code readability cake, we need a couple of ingredients. First and foremost, our code must be formatted in a consistent and sensible manner. It also needs to be well-structured into modules and files that make sense.

We also need to give our variables, functions and types sensible names that clearly describe their responsibility and what they do. Giving things sensible names is notoriously difficult though, so this should definitely not be underestimated and it is okay to spend time naming things properly. Even the most seasoned developers can get this wrong.

Once we start to get those things right, we can get started on the second layer of our cake: conveying intent in our code. Conveying intent is less about describing what the code does and more about what the code is intended to do. It’s often about nuances, and it’s about providing a sense of deeper understanding to the reader. What the purpose of it is and how it should be used. How many times haven’t we all wondered, perhaps while trying to resolve a bug, what a particular piece of code was intended to do? What did the developer who wrote it mean?

So how do we make our code convey intent? Well, first off, conveying intent can be hard. Having that said, it’s definitely not rocket surgery. We can all do it. It does require a moment of thought though, and sometimes we need feedback from our fellow developers to learn that the code we just wrote can be made more readable (and that’s okay). If we know the language and tools we’re using well enough, it definitely makes things easier. Let’s look at a couple of Swift examples.