Two Words About Clean Code
Happy weekend! Take a quick break in between doing chores and learn an easy way to write cleaner code in just a few minutes.
Join the DZone community and get the full member experience.
Join For FreeThere are many things to say about clean code and it might not be something new or be revealing to you, but I want to share a very helpful approach, which can help you to write nice looking code.
Background
Let's imagine that we have a piece of software that allows us to create documents with some indexes and file attachments. Our task is to listen to an event, like DOCUMENT_CREATED or something like that, and then carry out the following actions:
- Validate the document and move it to the Error folder if needed.
- Send an email to the administrator.
- Move the document to another folder based on its category index.
That's all, and enough to screw up the code.
A Reasonable Approach
1. Do not write any implementations first.
2. Instead, write out all your logic using only method names (i.e. descriptions).
public void onDocumentCreatedListener(Document doc){
if(isValid(doc)){
sendEmailNotificationToAdmin(doc);
moveToCorrectFolder(doc);
}else{
moveToError(doc);
}
}
We don't even have logic methods in the above code, but our IDE can create ones instead of us (ex: Eclipse).
The method above is the same as describing the each step in this process, as it allows us to think about each step.
3. Write implementations.
4. Fun!
Opinions expressed by DZone contributors are their own.
Trending
-
Security Challenges for Microservice Applications in Multi-Cloud Environments
-
Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs
-
Building a Robust Data Engineering Pipeline in the Streaming Media Industry: An Insider’s Perspective
-
Using Render Log Streams to Log to Papertrail
Comments