Saturday, May 4, 2019

3 Coding Tips Java Developers can Learn From Spring Framework

There is no doubt that 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 of Java APIs e.g. JDBC, JMS, Java Mail etc by providing a useful layer of abstraction. It's much more easy to work with JDBC with Spring's JdbcTempalte and other utility class. They remove most of the friction Java developer faces with respect to executing SQL statement and processing ResultSet to get the Java object they want.

So, when you learn Spring framework, you not just learn how to use it but also learn some useful insight about 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 Classic Spring in Action book by Craig Walls and my own experience with Spring framework. The book is now also updated to cover Spring 5 which is simply great.

Especially, the book, Spring in Action has a huge 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 read that book, it's totally worth your time and money.

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

Best Practices Java Programmers Should 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

This is an old OOP guideline which I have first learned while reading Head First Design Pattern. The main 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 expose an interface to use key classes e.g. JdbcOperation interface is created to leverage JdbcTemplate. This practice promotes loose coupling between different layers.

Another good example for this is a Cache interface which is used to provide caching. All other cache implementations e.g. EhCache, ConcurrentMapCache, and NoOpCache implement this interface.

If your code is dependent upon Cache interface and not on any specific implementation you can switch 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 Pluarlsight 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 type of methods in Java.

import java.util.Arrays;
import java.util.List;

 * 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);


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




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 Basics of Software Architecture & Design Patterns in Java, an excellent course on this topic.

2. Favor Unchecked Exception over Checked Exception

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

Spring has a rich hierarchy of exception 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 errors 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 practice while dealing with errors and Exception in Java. If you are interested in that topic then I suggest you go through a comprehensive Java course like The Complete Java Masterclass on Udemy which was recently updated for Java 11 and covers this topic well.

3. Use of Template Design Pattern

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

If you don't know 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 table to an object.

Here is a nice diagram which explains 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 Template method. All they need to define is their work, which they co by defining the work() as an abstract method.

Template Design Pattern in Java

Apart from JdbcTemplate, you will also find a lot of other examples of template method pattern throughout Spring framework API e.g. 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 Spring framework. Spring is a great framework and their authors are experienced Java developers. You can learn a lot by using Spring as well as looking at their code, 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 has a huge impact on code quality of Spring framework.

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

Other Java and Spring Articles you may like
Spring Frameworks MasterClass by Ranga Karnan
How Spring MVC works internally in Java?
10 Things Java Developer should learn in 2019?
10 Frameworks Java and Web Developer Should learn
10 Essential Testing Tools for Java developers
10 Tips to become a better Java Programmer in 2019
7 Reasons to use Spring for REST API development in Java

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

1 comment :

Post a Comment