Programming By Intention
Programming By Intention
A concept over 30 years in the making that first appeared in small talk but could pay huge dividends to your clean code
Join the DZone community and get the full member experience.Join For Free
Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.
In my blog post The Single Level of Responsibility Principle, I talked about the virtues of separating out perspectives in code so that any entity is only dealing with a single perspective. In this post, I’d like to tell you about the practice I use that helps me separate out perspectives in code without even thinking about it. This practice is called programming by intention.
Programming by intention is not new. I learned about it over thirty years ago. It’s the simple practice of thinking about how you call a service before you think about how you’ll implement it.
Back in the 80s I used a programming language called Smalltalk. The Smalltalk environment I used didn’t have a feature to create a new method. Instead, you made a call to a method in your code and if it wasn’t recognized Smalltalk would ask if you wanted to create it. Because of this feature, I got into the habit of thinking about how I’m going to use a service before thinking about how I’m going to implement a service, which turns out to be a good practice.
In programming by intention, we make our public APIs delegate to other methods so that the API code is clear and readable at the same level of abstraction.
Let public APIs delegate to private methods in order to do their work. Sometimes people ask me how you test private methods and the answer is usually: you don’t. Remember, the tests created by doing TDD are used to build out functionality and give us regression when refactoring. This is not QA activity. When we’re doing development, it’s typically better to write tests around behaviors. They give us more flexibility when refactoring code later.
My favorite technique to help keep code focused on creating testable behaviors is test-driven development. Writing the test first helps us forge an API from the consumer’s perspective, making it more implementation independent.
Both programming by intention and test-first development are excellent practices to help us build software that’s more understandable and straightforward to work with.
Published at DZone with permission of David Bernstein , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.