Sunday, April 21, 2024

Top 3 Design Patterns and Best Practices Java Developers Can Learn From Spring Framework

There is no doubt that the Spring Framework is one of the most popular Java frameworks and makes it really easy to create real-world, enterprise-grade Java applications easy by providing features like dependency injection and inversion of control. But, to be honest, Spring is much more than just another DI and IOC framework. It goes one more level to simplify many Java APIs like JDBC, JMS, Java Mail, etc by providing a useful layer of abstraction. It's much more comfortable to work with JDBC with Spring's JdbcTempalte and other utility classes. They remove most of the friction Java developer faces with respect to executing SQL statements and processing ResultSet to get the Java object they want.

So, when you learn the Spring framework, you not just learn how to use it but also gain some useful insight into how to write better code in Java and Object-Oriented programming in general.

In this article, I am going to share some of the best practices which I have come across while learning Spring, mainly by reading the Classic Spring in Action book by Craig Walls and my own experience with the Spring framework. The book is now also updated to cover Spring 5, which is simply exceptional.

Notably, the book Spring in Action has a significant impact on me because of Craig's excellent writing style and the way he explains each and every concept in Spring. If you have not read it already, I strongly suggest you to understand that book, it's totally worth your time and money.

Btw, if you are new to the Spring framework and want to learn it, I also suggest you join the Spring Framework 6: Beginner to Guru course on Udemy by John Thomson. This is an excellent course and effectively complements the Spring in Action book.





3 Best Practices Java Programmers Can Learn From Spring Framework

Anyway, without wasting any more of your time, here are 3 best practices from Spring I have learned and suggest every Java programmer be aware of it and apply it whenever they write code in Java.

1. Coding for Interfaces than Implementations

This is an old OOP guideline that I have first learned while reading Head First Design Pattern. The primary purpose of this OOP Design principle is to reduce coupling between two classes and thus increase flexibility.

Spring follows this Object Oriented guideline rigorously and often exposes an interface to use key classes like JdbcOperation interface is created to leverage JdbcTemplate. This practice promotes loose coupling between different layers.

Another excellent example of this is a Cache interface which is used to provide caching. All other cache implementations like EhCache, ConcurrentMapCache, and NoOpCache implement this interface.

If your code is dependent upon the Cache interface and not on any specific implementation, you can switch the cache provider without impacting other parts of your code. If you are interested in learning more about clean code, then Clean Code: Writing Code for Humans By Cory House on Pluralsight is a great resource.

Here is a simple code example of coding for the interface in Java using the Collection framework. If you look closely, in this example, I have used an interface instead of implementations for declaring variables, arguments and return types of methods in Java.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Program to demonstrate coding for interfaces in Java
 * @author WINDOWS 8
 *
 */
public class Hello {

  public static void main(String args[]) {

    // Using interface as variable types
    List<String> rawMessage = Arrays.asList("one", "two", "three");
    List<String> allcaps = toCapitalCase(rawMessage);
    System.out.println(allcaps);

  }

  /**
   * Using Interface as type of argument and return type
   */
  public static List<String> toCapitalCase(List<String> messages) {

    return messages.stream()
                    .map(String::toUpperCase)
                    .collect(Collectors.toList());

  }

}


This kind of coding style is flexible and easier to change in the future.  If you want to learn more about coding for interface principle, I suggest you go through the Basics of Software Architecture & Design Patterns in Java, an excellent course on this topic.

design patterns from Spring framework





2. Favor Unchecked Exception over Checked Exception

If you have used the Spring framework, then you would notice that Spring favors unchecked exceptions over checked exceptions, and the best example of this is Spring JDBC.

Spring has a rich hierarchy of exceptions to describe different errors you can get while connecting and retrieving data from the database but the root of them is DataAccessException which is unchecked.

Spring believes that most of the error steps from the reason which cannot be corrected in catch block; hence it leaves the decision to catch the exception of developers instead of forcing them like Java does. The result is cleaner code with no empty catch block and fewer try-catch blocks.

This is also one of the best practices while dealing with errors and Exceptions in Java. If you are interested in that topic then I suggest you go through a comprehensive Java course like The Complete Java Masterclass by Tim Buchalaka on Udemy which was recently updated for Java 11 and covers this topic well.


best practices from spring framework



3. Use of Template Design Pattern

Spring makes heavy use of the Template method design pattern to simplify things. An excellent example of this is JdbcTemplate, which takes away a lot of pain while using the JDBC API. You only need to define what requires, and Spring takes care of the rest of the process.

If you don't know, the Template design pattern defines a process or algorithm where you cannot change the process, but at the same time, you can customize steps based upon your needs.

For example, while dealing with JDBC, you can use JdbcTemplate to execute a query and get the Object you want. You just need to provide SQL, which is different in each case, as well as mapping logic to map a row from the table to an object.

Here is a nice diagram that explains the Template design pattern nicely. You can see that every person has some common task, but they do different work, and that's nicely captured by the Template method. All they need to define is their work, which they co by defining the work() as an abstract method.

Btw, If you are interested to learn more about Template Design patterns or other object-oriented and GOF design patterns then I also highly recommend The Design Pattern in Java course by Dmitri Nesteruk on Udemy. It's a great course to discover modern implementations of classic design patterns in Java and every experienced Java programmer should join it.


Template Design Pattern in Java


Apart from JdbcTemplate, you will also find a lot of other examples of template method patterns throughout the Spring framework API like JmsTemplate and RestTemplate, which allows you to consume REST API from Java application.

Btw, if you are interested in learning more about using Spring for developing RESTful web services, then REST with Spring Masterclass by Eugen Paraschiv is a nice place to start with.


That's all about some Java best practices you can learn from the Spring framework. Spring is a great framework, and its authors are experienced Java developers. You can learn a lot by using Spring as well as looking at their code, the decisions they made, and how they design their APIs. Spring is open-source, which means you can download and view their source code as well.

I know, Spring is a collection of many such best practices and there is a lot to learn but I have found these three used everywhere in Spring and thus have a huge impact on the code quality of the Spring framework.

Anyway, if you have come across any other best practices you have learned from Spring Framework, feel free to share them with us.

Other Java and Spring Articles you may like

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you want to learn the Spring framework from scratch and looking for some free resources then you can also check out this list of free courses to learn Core Spring and Spring Boot online. It contains some free courses from Udemy, Pluralsight, and other online platforms. 

2 comments :

Alssamaui said...

thanks a lot

Alien δΊžι‡Œ η‚Ž said...

Nice sharing. However:
1. XxxTemplate in Spring is NOT Template Method design pattern. It is hardly a named pattern actually. Closest one may be Facade.
2. Coding for Interface and Checked Exception are more design principles/practices instead of patterns.
3. For checked exception, it is not a good idea to assume "cleaner code with no empty catch block and fewer try-catch blocks.". The closer situation in checked exception is declaring extra exceptions in throws. "Empty catch block" in checked exception is aimed to ignore certain exception, and even you switch to unchecked exception, you still need to do the same. (Of course there are benefits using unchecked exception but these are probably not the main ones)

Post a Comment