Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Two Words About Clean Code

DZone's Guide to

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.

· Agile Zone
Free Resource

See how three solutions work together to help your teams have the tools they need to deliver quality software quickly. Brought to you in partnership with CA Technologies

There 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!

Discover how TDM Is Essential To Achieving Quality At Speed For Agile, DevOps, And Continuous Delivery. Brought to you in partnership with CA Technologies

Topics:
clean code ,agile ,readable code

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}