Java Best Practices and Tips


  •  10-50-500 Rule

In big software packages, maintaining code becomes very challenging. Developers who join fresh ongoing support projects, often complain about: Monolithic Code, Spaghetti Code. There is a very simple rule to avoid that or keep the code clean and maintainable: 10-50-500.
10: No package can have more than 10 classes.
50: No method can have more than 50 lines of code.
500: No class can have more than 500 lines of code.

  • SOLID Class Design Principles

Single responsibility principle - A class should have one and only one task/responsibility. If class is performing more than one task, it leads to confusion.
    Open/closed principle - The developers should focus more on extending the software entities rather than modifying them.
      Liskov substitution principle - It should be possible to substitute the derived class with base class.
        Interface segregation principle - It’s like Single Responsibility Principle but applicable to interfaces. Each interface should be responsible for a specific task. The developers should need to implement methods which he/she doesn’t need.
          Dependency inversion principle - Depend upon Abstractions- but not on concretions. This means that each module should be separated from other using an abstract layer which binds them together.
          • Design Patterns
          Design patterns help developers to incorporate best Software Design Principles in their software. They also provide common platform for developers across the globe. They provide standard terminology which makes developers to collaborate and easier to communicate to each other.
          • Use Collections Correctly
          Java have set of build-in collection data structures available for usage out of box. List, Map, Set, Array. The developers are encouraged to use collections as extensively as possible for the following reasons:
          - Use of collections makes the code reusable and interoperable.
          - Collections make the code more structured, easier to understand and maintainable.
          - Out of the box collection classes are well tested so the quality of code is good.

          Since Vector and Hashtable are heavily synchronized even for read operations, they can present some challenging problems in performance tuning.
          • Avoid Floating Point Numbers
          Floating point numbers should be used only if they are absolutely necessary. For example, representing Rupees and Paise using Floating Point numbers can be Problematic – BigDecimal should instead be preferred. Floating point numbers are more useful in measurements.
          • Avoid deadlock by using correct lock sequence
          References 
          - https://docs.oracle.com/cd/A97688_16/generic.903/bp/java.htm 
          - https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

          No comments :

          Post a Comment