Java Best Practices, Tips, and Tricks

Java Best Practices, Tips, and Tricks

Java Best Practices: General Concepts

Let’s assume that you want to develop efficient and flexible?applications using Java. Otherwise, you wouldn’t be reading this article, right?

As you may already know, there are some proven design patterns and?coding standards?that will help you to be a better programmer.

Using the best coding practices and?following coding guidelines?improves code quality – it makes code much more understandable, flexible, reusable, and maintainable.

It also helps to increase code performance and employee productivity.

Can I stop you for a second?

If you’re here for the first time, you need to know that we have?more articles like this.

Looking fornon BS articles?written by software developers? You can find them in the?Tech category.

Code Quality

The most important thing regarding code quality is to keep your applications as secure and stable as possible from the beginning of the development process. To do this, always use the latest Java version in the source code.

What to do and what not to do?

  • Give priority to generic types, methods, and wildcards
  • Implement tight encapsulation, loose coupling, and high cohesion in classes
  • Avoid memory leaks by using final blocks whenever possible
  • Always close IO streams
  • Using Date and Time API (JSR 310) is better than using data.util.date and Joda-Time
  • Expression lambdas are better than block lambdas
  • Catching specific subclasses of the Exception class is better than catching the class itself
  • Returning empty collections is better than null
  • Remember about using interface type when you are declaring a collection
  • Every catch block needs the Exception class
  • If you need fast iteration and random access – use ArrayList
  • If you need fast insertion and deletion – use LinkedList

Additionally, using Java code style formatters and source code analyzers like FindBugs, CheckStyle or Sonar will improve your code’s readability.

Performance

Making an application function is one thing but developing it quickly is another. To make both possible, every Java developer should be aware of common performance issues and avoid them whenever possible.

  • database issues
  • N + 1 select – the trap of incomprehensible lazy fetching strategy
  • no-cache – it is faster to get content from memory than from a database (possibly on a different server)
  • the insufficient size of pool connections
  • memory problems
  • garbage collection procedure occurs too often or takes too much time
  • memory leaks and OutOfMemory error
  • concurrency problems
  • thread deadlocks
  • thread gridlocks

Logging levels in our code will allow us to avoid printing unnecessary logs in non-development mode. It also protects the production environment from slowing down. Logs and return codes can give you detailed information about what exactly happened. Thanks to this, code consumers won’t waste their time.

If you want to avoid the recreation of objects and reduce the amount of garbage collection, cache frequently-used objects.

Remember to use connection pools and cached-prepared statements to gain database access.

Frameworks and tools

If you are about to choose the application framework,?I strongly recommend choosing Spring?because of its popularity, flexibility, and capabilities. It’s an open-source framework that makes J2EE development easier to manage and helps to “wire” different components together.

Above all, Spring is helpful if you have a lot of components that you want to combine in different ways or if you want to facilitate swapping one component for another. This framework also provides many modules which support functionalities like:

  • Dependency Injection
  • Security
  • Database access
  • Webservices
  • System integration
  • Batch processing

WHAT ARE THE KEY BENEFITS OF SPRING?

  • Well-designed MVC framework
  • Modular architecture
  • The capability of implementing enterprise applications using POJOs
  • Set of conventional technologies, i.e. ORM framework, logging framework, J2EE
  • Consistent transaction management system
  • Flexibility in building different kinds of applications, i.e. GUI applications
  • Support for managing business objects and exposing their services to presentation-tier components
  • The capability of eliminating the creation of singleton and factory classes

Use JPA standard implementation as the data persistence framework. The most popular one is Hibernate, which provides several useful modules like:

  • Ehcache – for defining second-level cache
  • envers – for tracking change history
  • search – for indexing results in local storage

The key benefits of Hibernate are:

  • Advantages of OOP concepts, i.e. inheritance, encapsulation
  • Avoidance of repetitive code from JDBC API
  • Caching mechanism
  • Database engine independence
  • Support of lazy loading

Architecture

Following SOLID principles?is crucial to designing a good architecture. The acronym stands for:

  • S?– Single Responsibility Principle
  • O??– Open/Closed Principle
  • L??– Liskov’s Substitution Principle
  • I??– Interface Segregation Principle
  • D??– Dependency Inversion Principle

I’m pretty sure that you know them all, but do you follow them consistently?

Ask yourself and answer sincerely.

The next thing you should remember is to divide the application into different logical areas from the business perspective. What about implementation? It needs to be divided into logical tiers from a functional standpoint, i.e. presentation, business logic and data layer. If architecture is layered correctly, it means that it is built on separate layers that are not affected by specific changes in other layers.

If you want to offer some sophisticated and extensive functionalities for the users of your application, you should avoid developing one monolithic application and?consider using a microservices architecture. As a result, you will be able to build many small programs, and then you can create a small application that implements a new feature in every instance.

In addition, having a microkernel is another good practice. It helps us to implement extra features in plug-in architecture on top of the kernel module.

Deployment server

The construction of dynamic pages and implementation of services are supported by application servers, like clustering, fail-over, and load balancing. Thanks to this, developers can just focus on fulfilling business requirements. What is the most popular application server for Java?

  • GlassFish
  • JBoss
  • Tomcat
  • Geronimo
  • WebSphere

Other useful tips and tricks

AUTHORIZATION AND AUTHENTICATION

It is quite easy to configure access authentication as the applications are often created by using the Spring Framework.

Spring Security provides the capability of setting objects like Role, Permission, and User to Role assignment.

It also provides a comprehensive security solution that handles authentication and authorization, available at the web request level and the method invocation level.

UNIT AND INTEGRATION TESTING

One way of verifying if the logging and behavior of the source code are correct is to do unit tests.

That is to say, tests make it possible to identify software regressions or bugs created as a result of the latest changes in the source code.

If you want to continue implementing features without having to perform a vast amount of manual tests, high test coverage of code will come in handy.

Technologies that support unit and integration tests:

  • JUnit
  • TestNG
  • AspectJ
  • AssertJ
  • Mockito
  • PowerMock

If you want to visualize code coverage,?use the JaCoCo library .

BUILD AND DEPLOYMENT

If you want to build applications faster, use build tools. Every Java developer should know about tools like Ant, Maven, and Gradle.

Maven is the most popular one, and it allows for downloading remote dependencies and automation of manual tasks often needed for deployment, like copying files, cleaning cache, and injecting properties.

Java is a multifunctional, class-based, object-oriented programming language with less implementation dependency. It is a technical platform where you can develop different applications. Java is fast, reliable, and highly secured. It is popularly used to develop Java applications on laptops, data centers, game consoles, supercomputers, cell phones, and many more.

Java is one of the commonest programming languages, whether, for Windows applications, web applications, mobile devices, networks, consumer electronics, hardcover devices; in fact, you can find Java everywhere. More than 3 billion devices use Java, and over 9 million developers write code in Java. It is common with developers and the most widely used development platforms.

However, before you think of learning any language, it is important to learn some tips and tricks to make it clearer.

Build and Deployment

During building applications, you can speed up the process by using build tools. As a Java developer, it is essential that you are familiar with tools such as Ant, Maven, and Gradle.

Maven is the most popular; it enables you to download remote dependencies and automatically perform manual tasks that are often required for deployment, such as Copying files, clearing caches, and injecting properties.

Know the Difference Between Array and ArrayList

It is often difficult for developers to decide whether to use an Array type data structure or ArrayList type. Both have several characteristics and must be used in different situations. Arrays are fixed in size, but ArrayList is variable in size . Changing the elements in the ArrayList is much easier than changing the Array.

The interface is Better Than Abstract Class

Java doesn't have multiple inheritances, but the UI makes it easy to implement something like multiple inheritances without utilizing the extended keyword. If things don't go as planned, you always need an interface. An abstract class does not give the liberty to have multiple modes, but they have abstract methods.

Unit and Integration Testing

One way to test the accuracy of logging and source code behavior is to run unit tests. Tests allow you to identify software bugs that have resulted from recent changes to the source code. If you want to continue feature implementation without performing a large number of manual tests, high test code coverage is helpful. Some of the technologies that support unit and integration tests are Junit, TestNG, AspectJ, AssertJ, Mockito, and PowerMock.

String Concatenation

The first thing you will think about when you see String Concatenate is concatenating strings with the ‘+’ operator. However, did you know that this is not the best and only way to do the job? There are four methods to do this.

  • Use the "+" operator: This is the easiest way to concatenate multiple strings, but it uses extra memory and reduces your programs' performance speed, especially when dealing with multiple strings in a loop. But this does not mean you should avoid this method totally. You can still use this to concatenate strings into a single statement.
  • The concat( ) method: This is a rarely used method. You have a better performance than when you use the ‘+’ operator; however, much slower.
  • Using StringBuffer: You have a much faster performance with this than when you use the two methods above. StringBuffer has been synchronized for multi-threaded operations, making this method thread-safe. This is not as fast as the StringBuilder due to the synchronous approach.
  • Append method of StringBuilder class: This is the same as the StringBuffer; however, the StringBuilder lacks synchronization for multi-threaded operations. If you are making a loop with multiple strings, then StringBuilder is the best choice.

Avoiding Memory Leaks by Simple Tricks

Deterioration of software performance is usually due to Memory leaks. Because Java does automate memory management, developers have little control. However, there are still some standard procedures that can be used to protect against memory leaks.

  • Ensure the database connections are often released after completing the query.
  • Try to utilize the Finally block always.
  • Instances in Static Tables must be released.
  • Store cases in static tables.

Encode in JSON

JSON - JavaScript Object Notation is a syntax applicable for storing and exchanging data. JSON is an easier alternative to use than XML. Nowadays, JSON’s popularity on the internet these days has been increasing because of its light properties and weight. A typical data structure can be encoded in JSON and shared on websites. Before you can start writing any code, a JSON analyzer must be installed.

Better to Avoid BigDecimal and BigInteger

You can also choose BigDecimal and BigInteger, which are the precise way to represent numbers. If you want to use float numbers with several accuracies or deal with money when accuracy is required, then BigDecimal may be your choice. But it requires more memory, the algorithm is a little more complicated to use than twice the memory, and it slows down all calculations significantly.

Therefore, it is highly recommended to avoid BigDecimal and BigInteger and only use them when there is no other method.

Optimize Your Code with Profilers

Writing and compiling the code is not enough to achieve the desired result. We need to write code with the best possible performance. The best method to do this is to analyze what is going on behind the code, the memory allocation, the areas to be improved, and the impact of using one coding approach on the other. The best tool applicable for this is the Java Profiler.

Java Profiler is a tool to monitor the construction and operation of Java bytecodes at the JVM level. With these profilers, you can determine performance, memory usage, memory leaks, etc. Then, in your program, you can easily find out what needs to be changed, adjusted, or deleted.

There are several profilers available, such as JProfiler, XRebel, and New Relic. However, each profiler has a distinct character, best suited to specific aspects of performance failure. Therefore, the profiler must be selected based on the level of analysis required. You can combine multiple profiles to get the best results.

Float and Double

These two data types represent float numbers, or rather, this double number is a known fact.

It is strongly recommended that you use Double Float twice, especially if you cannot guarantee that your number will be within the specified "Float" range.

Note, however, that the cost is twice as much. It’s expensive because it takes up twice as much space as a Float.



要查看或添加评论,请登录

Omar Ismail的更多文章

  • OAuth Grant Types (Authorization Code Grant)

    OAuth Grant Types (Authorization Code Grant)

    The authorization code grant type is used to obtain both access tokens and refresh tokens. The grant type uses the…

  • What is Apache Kafka?

    What is Apache Kafka?

    Reference : https://www.qlik.

    2 条评论
  • Multi-Tenant Architecture in a Nutshell

    Multi-Tenant Architecture in a Nutshell

    Thanks to the original writer and article :…

  • Microservices Communication!

    Microservices Communication!

    Thanks To: https://medium.com/design-microservices-architecture-with-patterns/microservices-communications-f319f8d76b71…

    2 条评论
  • What Are the New Features of SpringBoot3 ?

    What Are the New Features of SpringBoot3 ?

    Thanks to : https://medium.com/javarevisited/what-are-the-new-features-of-springboot3-6ddba9af664 1.

    1 条评论
  • OAuth 2.0!

    OAuth 2.0!

    Thanks to the original writer : https://medium.com/@isharaaruna OAuth2.

    2 条评论
  • How to Draw a Technical Architecture Diagram

    How to Draw a Technical Architecture Diagram

    Thanks to the original writer and article : https://levelup.gitconnected.

    2 条评论
  • Event Sourcing Versus Event-Driven Architecture

    Event Sourcing Versus Event-Driven Architecture

    Thanks to the original writer and article :…

  • Best Practices For Your API Versioning Strategy

    Best Practices For Your API Versioning Strategy

    API versioning is critical. But do you know all of the API versioning best practices? Is your API versioning strategy…

    1 条评论
  • Enterprise Architecture Tools

    Enterprise Architecture Tools

    Thanks to the original writer and article : https://medium.com/geekculture/enterprise-architecture-tools-b8165c8c9d7…

社区洞察