We often concentrate on the logic and syntax in the beginning of our software career. Eventually there is a time where everyone starts focusing writing a clean and readable code. Writing clean code is hard-work. It takes a lot of effort from a developers side to create a software which is based on simple code. For such a software code itself is the design.

Here are some tips that matters to all java developers which can be used as a checklist before delivering their code.

Methods:

    1. The first rule of methods is that they should be small.
    2. Do one thing inside a method – follow single responsibility principle.
    3. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations.
    4. Use Intention-Revealing names for methods.
    5. Avoid disinformation in names.
    6. Make meaningful distinctions: you can’t use the same name to refer to two different things in the same scope.
    7. Use Searchable Names: Single-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text.
    8. Use descriptive names: A long descriptive name is better than a long descriptive comment. Use a naming convention that allows multiple words to be easily read in the function names, and then make use of those multiple words to give the function a name that says what it does.
    9. Function Arguments: The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn’t be used anyway.
    10. Flag Arguments: Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing.
    11. Functionality is implemented in a simple, maintainable, and reusable manner.
    12. Use descriptive and meaningful variable, method and class names as opposed to relying too much on comments.
    13. Class and functions should be small and focus on doing one thing. No duplication of code.
    14. Functions should not take too many input parameters.
    15. Use a standard code formatting template.
    16. Declare the variables with the smallest possible scope. (For example, if a variable “tmp” is used only inside a loop, then declare it inside the loop, and not outside.)
    17. Don’t preserve or create variables that you don’t use again.
    18. Omit needless and commented out code. No System.out.println statements either. (Use proper logging frameworks)
    19. Make a class final and the object immutable where possible.    (Immutable classes are inherently thread-safe and more secured. For example, the Java String class is immutable and declared as final.)
    20. Use right data types.
    21. Return an empty collection or throw an exception as opposed to returning a null. Also, be aware of the implicit autoboxing and unboxing gotchas.
    22. Don’t log sensitive data.
    23. Favor immutable objects.
    24. Use Prepared statements as opposed to ordinary statements.
    25. Release resources.
    26. Don’t let sensitive information like file paths, server names, host names, etc escape via exceptions.
    27. Don’t ignore or suppress exceptions. Standardize the use of checked and unchecked exceptions. Throw exceptions early and catch them late.
    28. Presence of hard coded config values. Externalize configuration data in a .properties file. Sensitive information like password must be encrypted.
    29. Avoid multiple if/else blocks.
    30. Opt for caching if possible.
    31. Use exceptions rather than return codes.
    32. Don’t return null from a method.  So that the caller of the method don’t have to check for null. Example:- Use Collections.emptyList() if a method usually returns a Collection object.
    33. Don’t  pass null to a method.

Comments:

  1. Clear and expressive code with few comments is far superior to cluttered and complex code with lots of comments.
  2. Legal comments:copyright and authorship statements are necessary and reasonable things to put into a comment at the start of each source file.
  3. Informative comments: It is sometimes useful to provide basic information with a comment.
  4. Explanation about the intent.
  5. Warning of consequences.
  6. Add TODO comments when needed.
  7. Function headers: Short functions don’t need much description. A well-chosen name for a small function that does one thing is usually better than a comment header.
  8. Do not write comments for what you are doing, instead write comments on why you are doing. Specify about any hacks, workaround and temporary fixes. Additionally, mention pending tasks in your to-do comments, which can be tracked easily.

Test Cases:

  1. Check the test coverage and quality of the unit tests with proper mock objects to be able to easily maintain and run independently/repeatedly.
  2. Test only a unit of code at a time (e.g. one function).
  3. Unit tests must be independent of each other. They should run independently.
  4. Set up should not be too complicated.
  5. Mockout external states and services that you are not asserting. For example, retrieving data from a database.
  6. Avoid unnecessary assertions.
  7. Start with functions that have the fewest dependencies, and work your way up.
  8. Write unit tests for negative scenarios like throwing exceptions, negative values, null values, etc.
  9. Don’t put try/catch inside unit tests. Use throws Exception statement in test case declaration itself.
  10. Ensure that the unit tests are written properly and giving 100% code coverage.

Code formatting:

  1. While going through the code, check the code formatting to improve readability and ensure that there are no blockers.
  2. Use alignments (left margin), proper white space. Also ensure that code block starting point and ending point are easily identifiable.
  3.  Ensure that proper naming conventions (Pascal, CamelCase etc.) have been followed.
  4. Code should fit in the standard 14 inch laptop screen.  There shouldn’t be a need to scroll horizontally to view the code. In a 21 inch monitor, other windows (toolbox, properties etc.) can be opened while modifying code, so always write code keeping in view a 14 inch monitor.
  5. Remove the commented code as this is always a blocker, while going through the code. Commented code can be obtained from Source Control (like SVN), if required.

Maintainability (Supportability):

  1. The application should require the least amount of effort to support in near future. It should be easy to identify and fix a defect.
  2. Readability: Code should be self-explanatory. Get a feel of story reading, while going through the code. Use appropriate name for variables, functions and classes. If you are taking more time to understand the code, then either code needs refactoring or at least comments have to be written to make it clear.
  3. Testability: The code should be easy to test. Refactor into a separate function (if required). Use interfaces while talking to other layers, as interfaces can be mocked easily. Try to avoid static functions, singleton classes as these are not easily testable by mocks.
  4. Debuggability: Provide support to log the flow of control, parameter data and exception details to find the root cause easily. If you are using Log4Net like component then add support for database logging also, as querying the log table is easy.
  5. Configurability: Keep the configurable values in place (XML file, database table) so that no code changes are required, if the data is changed frequently.

Reusability:

  1. DRY (Do not Repeat Yourself) principle: The same code should not be repeated more than twice.
  2. Consider reusable services, functions and components.
  3. Consider generic functions and classes.
  4. Extensibility: Easy to add enhancements with minimal changes to the existing code. One component should be easily replaceable by a better component.

Object-Oriented Analysis and Design (OOAD) Principles:

  1. Single Responsibility Principle (SRS): Do not place more than one responsibility into a single class or function, refactor into separate classes and functions.
  2. Open Closed Principle: While adding new functionality, existing code should not be modified. New functionality should be written in new classes and functions.
  3. Liskov substitutability principle: The child class should not change the behavior (meaning) of the parent class. The child class can be used as a substitute for a base class
  4.  Interface segregation: Do not create lengthy interfaces, instead split them into smaller interfaces based on the functionality. The interface should not contain any dependencies (parameters), which are not required for the expected functionality.
  5. Dependency Injection: Do not hardcode the dependencies, instead inject them.

 

Courtesy:

List compiled by: Deeksha K, UST Global Inc.

Share this article:

Leave a Reply

Your email address will not be published. Required fields are marked *