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

It's Not Too Late!!: How to Write Quality Code

DZone 's Guide to

It's Not Too Late!!: How to Write Quality Code

Keep in mind that it's never too late to write and refactor code to increase its quality and make it more robust.

· Agile Zone ·
Free Resource

In today's era, everyone is moving to enhance resource capabilities. If we talk about web applications, then we have frameworks like Spring, Play, and Struts which help us to make our software scalable and manageable. Much of the boilerplate code is done by these frameworks so you don't need to write that code in your application.

Writing code is not tough, but it is tough to write quality code.

As a developer, the same fundamentals are applied in our daily lives. We should do our work with perfection or as error-free as the client expects. Many times, while under pressure, developers write unmanaged or complex code. A good rule of thumb for quality code is that code should be written in such a way that anyone can read like a phrase.

Things to Keep in Mind When Writing Code

  • Think a twice and write once, or think before you write.
  • Follow best practices.
  • Use code quality tools like SonarQube, or if you are using an IDE like eclipse or IntelliJ, then you can also use the Sonar plugin (SonarLint), easily available over the marketplace.
  • Try to write generic code.
  • Don't create your own method which already exists in APIs like isEmpty, isNull, or isNotNull . Many well known open-source libraries have those, like Apache, which provides a well-defined library for such type of things.
  • Use the Refactor Tool of IDE and learn its shortcuts.
  • public void doSomething ( ) {
        Line1 ....
        Line2 ....
        Line3 ....
        Line4 ....
        Line5 ....
    }

    Now you want to extract from 1-4 and want to create a separate method. So, usually, what people do is copy and create a method and then paste the copied line inside that method so in all it takes 3 or 4 steps. To do such tasks, you can easily use an IDE’s refactor tool instead of that copy and paste method.

    Refactor tools have many important features, including the ability to:

  • Move a code snippet from one location to another.
  • Create a method by just extracting code from any location (shown in the above example).
  • Rename a file, variable, or method.
  • Note: If you do such tasks on your own then you also need to change them everywhere corresponding to each change.

  • If possible, try to write proper test cases. (Optional)

When Writing Class

  1. The class name should be nouns and the first letter of each word should capitalized
  2. Search before writing a new class as there may be such a file is already there in your project. Many times it’s found that we create the same file with a different name and misguide the project and other developers. For example:
  3. Already There

    Newly Created

    AppUtil

    ApplicationUtil

    ConfigutationUtil

    ConfigurationHelper

    LoggerUtil

    LoggerHelper

  4. The class name should describe its function thoroughly enough.
  5. Shouldn't

    Should be

    PersonRestApi

    PersonController

    PersonRest

    PersonController

    PersonImplementation

    PersonService


  6. Use proper access modifiers.
  7. The packaging of files also very important put right file in right place don’t put the constant file in util package or such mistake the right place for this is constant or metadata whichever suits you.

When Writing Methods

  1. A method should be verbs and the name should follow the camel case, like  doWhatToDo( ) , not  doWHatTODO( ) .
  2. A method shouldn't contain more than 30 lines; if it does, that means you are increasing its complexity.
  3. The Think before defining the method it should have some meaning or should be created for a specific task like createPerson , or sendMail  .
  4. A method shouldn’t perform multiple tasks at the same time. If your method's name is createPerson  then it should only create a person, nothing else. Many of us do this:
public Long createPerson(PersonVO personVO) { 
    1.Appointment appointment = trying to getting an appointment from DB.
    2.then performing if else over the result of appointment.
    .
    .
    .
    .
    14.then updating something on the basis of some condition.
    15.then finally creating person.
 } 

Many times it crosses the limit of the method and a developer puts 100-300 lines of code in a single method and at the end it makes code horrible and undecipherable.

Some of the problems it creates include:

  • Being unable to understand the flow of code.
  • Debugging issues.
  • Testing issues.
  • Taking a long time to solve a bug.

Solution:

  • Try to do all the other tasks in separate methods.
  • Extract validation code in a separate method and just call that method.

So the code should look like:

 public Long createPerson(PersonVO personVO) { 
  appoitnmentValidation();
  updatingSomething();
  creating person code;
 }

When Writing Variables

  1. The name should follow camel case like  isTrue , userService , personName , and localServiceRerpository .
  2. Shouldn’t use one character name for except in temp case.
  3. Shouldn’t start with _ and $.
  4. Think before defining the name of a variable.
  5. Don’t write large variable names.

When Writing Constants:

  1. Try to use the class to define the constants, not the interface.
  2. Mark class as a final.
  3. Create one private constructor in the constant class so that no one can create its instance.
  4. If you have a single constant file for the whole service then it's a good idea to segregate the constants by using a comment like
  5. /**** Cache ****/
    public static final String CACHE_NAME = "personCache";
    
    /**** Attributes ****/
    public static final String NAME = "name";
    public static final String MOBILE = "mobile";
    
    /**** Configuration ****/
    public static final String APP_NAME = "PersonDemo";
    public static final String APP_VERSION = "1.0";

    so it is easy to search in the whole file.

  6. The constant name should be very specific and should be all upper and separate with Underscore ( _ ) like APP_NAME, not appName.

When Writing Logic

  1. Avoid multiple nested If else   which increases the cyclomatic complexity in your code.
  2. Try to write generic code.
  3. Don't swallow the exceptions by just using log , throw a proper message or exception in place of just printing the exceptions.
  4. If you have a single constant file for the whole service then it's a good idea to segregate the constants by using a comment like

What Is "Generic Code"?

In many projects at the time of refactoring, there is a redundancy of code which shouldn’t be there.

Let's say we have one mail draft POJO class with relevant members for sending a mail. What are the steps we need to follow for sending a mail?

  1. We need to create one POJO object by selecting the data using the setters.
  2. We need to write code to send mail.

And finally, the number of lines :

For Object creation - 1 Line:

 MailDraft mailDraft = new MailDraft(); 

For setting the data - 3 Lines

mailDraft.setTo(); 
mailDraft.setBody(); 
mailDraft.setMessage();

There to 4 lines minimum for send mail logic, so a total 9-10 lines of code.

What happens if we need to send mail at multiple conditions or events? We require the same logic, and what is generally found is that developers just follows the same steps in each place and create a method with some specific code and the chain of redundancy will go on.

However, if we extract the draft creation and send the mail code in a separate method so that every method can consume that code, which saves our 10 lines in each method, there's no need to write that code again and again.

Don’t write code in a hurry if you do so then also use:

TODO: need to refactor one day.


Topics:
code ,refactoring ,quality code ,agile ,clean code

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}