Be ready to explain your code

Full article

When we're programming, there's all kinds of ways to code defensively. We surround blocks of code with "try / catch" structures that prevent our apps from crashing. We log errors, to help track down problems later on. We include tests to help make sure next week's changes don't break last weeks' code. We document our work so that other devs, business, end-users etc will find it when they (or you and me in 6 months!) need to figure out why something works the way it does.

All of these things defend our code against being subpar, riddled with bugs.

But there's another kind of defensive programming that benefits everyone - making sure you understand what you're writing and why you're writing it that way. That doesn't mean you can't lift a snippet from someone else.. there's no need to reinvent the wheel. But whether you invent your own wheel or use someone else's, anyone driving your car down the highway at 70 mph reasonably assumes you know how that wheel works.

Imagine someone on your team asking you, genuinely and in the spirit of learning, why'd you write that piece of code that way.. can you explain it to me? What do you tell them?

I've had the benefit several times recently (yes, it's a benefit for both of us) to explain my code to a developer with less experience. Nothing makes you realize your gaps in knowledge, or where things could be written better, than going through your own code and trying to explain it to someone else. You're forced to double-check your assumptions, look up docs to verify things, maybe even realize there was a better way.

Doing regular code reviews is a good way to do this, but that's usually an asynchronous process.. sitting with someone and talking it out is even better. If you ever have the opportunity to explain your code to someone else, don't get defensive, but do defend it. You might both learn something!


Photo by Christina Morillo from Pexels

Author

Grant Winney

I write when I've got something to share - a personal project, a solution to a difficult problem, or just an idea. We learn by doing and sharing. We've all got something to contribute.


Comments / Reactions