3 Best Practices Java Programmers Can Learn From Spring Framework
Take one look at Spring's source code, and you can see the thought that went into the framework. Check out some best practices Java devs can learn from Spring.
Join the DZone community and get the full member experience.
Join For FreeThere 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 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's APIs e.g. JDBC, JMS, Java Mail, etc., by providing a useful layer of abstraction. It's much easier to work with JDBC with Spring's JdbcTempalte and other utility classes. They remove most of the friction a Java developer faces with respect to executing SQL statements and processing ResultSets to get the Java object they want.
So, when you learn Spring, you learn not just how to use it, but also some useful insights 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 that I have come across while learning Spring, mainly by reading the classic Spring in Action book by Craig Walls and my own experience with Spring.
The book has had an especially 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 it — it's totally worth your time and money.
Anyway, without wasting any more of your time, here are three best practices I have learned and suggest every Java programmer to be aware of it and apply it whenever they write code in Java.
1. Coding for Interfaces
This is an old OOP guideline that I first learned while reading Head First Design Patterns. 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 exposes an interface to use key classes, e.g. the 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 a Cache interface and not on any specific implementation, you can switch the cache provider without impacting other parts of your code.
Here is a simple code example of coding for interfaces 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;
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.
2. Favor Unchecked Exceptions Over Checked Exceptions
If you have used Spring Framework, then you have noticed 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 databases, but the root of them is DataAccessException, which is unchecked.
Spring believes that most errors stem from reasons that cannot be corrected in catch blocks, hence it leaves the decision to catch the exception to developers instead of forcing them into it like Java does. The result is cleaner code with no empty catch blocks — 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 you may also check out my post 10 Java Exception best practice for more advice.
3. Use of Template Design Patterns
Spring makes heavy 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 the JDBC API. You only need to define what it requires and Spring takes care of the rest of the process.
If you don't know, the Template 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 the SQL, which is different in each case, as well as mapping logic to map a row from a table to an object.
Here is a nice diagram that explains the Template Pattern nicely. You can see that every person has some common task, but they do different work and that's nicely captured by a Template method. All they need to do is define is their work, which they can by defining the work() abstract method.
Apart from JdbcTemplate, you will also find a lot of other examples of the Template Method Pattern throughout Spring Framework's API, e.g. JmsTemplate and RestTemplate, which allow you to consume REST APIs from Java applications.
That's all about some Java best practices you can learn from Spring. 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, the decisions they made, and how they designed their APIs. Spring is open source, which means you can download and view their source code as well.
I know that 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, which has led to a huge impact on the code quality of Spring Framework.
Anyway, if you have come across any other best practices you have learned from Spring, feel free to share with us.
Published at DZone with permission of Javin Paul, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Top Six React Development Tools
-
Auditing Tools for Kubernetes
-
Software Development: Best Practices and Methods
-
Tactics and Strategies on Software Development: How To Reach Successful Software [Video]
Comments