Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is reconstruction?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "what is the method of reconstruction". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Code structure before refactoring

Boy, all the third-party storage is written in one module, all kinds of Aliyun, Tencent Cloud, Huawei Cloud and so on. This kind of code architecture may still be available when you don't need to expand frequently in the early stage.

However, when a new requirement comes, such as the one I encountered: you need to support the upload and download of multiple accounts in multiple clouds, this is because the permissions and security authentication of different accounts are different on different clouds, so at some point, this requirement is put forward, that is, you can upload to any account in which cloud you want.

Then get this code, take a look at such an architecture, it may be no problem to complete the requirements on such a basis, but the expansion is very troublesome, and the code will become more and more onerous, and the architecture will become more and more complex and unclear.

So I just took this opportunity to refactoring, and other colleagues also discussed, decided to sub-module, SPI, the advantage is to introduce the corresponding dependency according to what you want to use, so that the code architecture is clearer, and it is easier to expand later! Here is the general architecture after refactoring:

Is it much clearer that even if a cloud storage needs to add new features or need to be compatible with more clouds, it will be easier after that?

All right, let's start talking about refactoring.

Reconstruct

What is refactoring?

Refactoring is to improve the quality and performance of the software by adjusting the program code, make the design pattern and architecture of the program more reasonable, and improve the expansibility and maintainability of the software.

The most important idea of refactoring is to enable ordinary programmers to write excellent programs.

The process of optimizing code quality is broken down into small steps, so that the huge workload of refactoring a project becomes simple goals such as changing variable names, extracting functions, extracting interfaces, and so on.

As an ordinary programmer, you can improve your coding ability and deepen your project understanding by achieving these easy-to-accomplish goals, so as to lay the foundation for the highest-level refactoring.

And high-level refactoring is still composed of countless small goals, rather than long-term, large-scale implementation.

The essence of refactoring is a part of extreme programming, and the complete realization of extreme programming can maximize the value of refactoring. Extreme programming itself advocates embracing change and enhancing adaptability, so decomposing the functions of extreme programming to adapt to the needs of the project and the current situation of the team is the best mode of operation.

The focus of refactoring

Repetitive code, overlong function, oversized class, overlong parameter column, divergent change, shrapnel modification, attachment complex, data mud mass, basic type paranoia, parallel inheritance system, redundant class, etc.

Here are some common or more basic examples:

I think I still need to understand some basic principles.

Try to avoid creating too many Java objects too long

Use local variables as much as possible

Try to use StringBuilder and StringBuffer for string concatenation

Minimize the double calculation of variables

Try to release resources in the finally block

Cache frequently used objects as much as possible

Unused objects are set to null in time

Try to consider the use of static methods

Try to use singletons on appropriate occasions

Use final modifiers whenever possible

The following is about class and method optimization:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Extraction of repetitive code

Segmentation of lengthy methods

Optimization of nested conditional branching or cyclic recursion

Extract constants from a class or inheritance system

Extract duplicate attributes and methods from the inheritance system to the parent class

Here first briefly introduce these more conventional reconstruction ideas and principles, methods, after all, today's protagonist is SPI, here is SPI!

SPI

What is SPI?

SPI, whose full name is Service Provider Interface, is a set of API provided by Java to be implemented or extended by third parties. It can be used to enable framework extensions and replacement components.

It is a service discovery mechanism that automatically loads classes defined in files by looking for files in the META-INF/services folder under the ClassPath path.

This mechanism provides the possibility for many framework extensions, for example, SPI mechanism is used in Dubbo and JDBC.

Here is the mechanism and process of SPI

SPI is actually a dynamic loading mechanism implemented by interface-based programming + policy mode + configuration file combination.

There are often many different implementation schemes in each abstraction of the system design. in the object-oriented design, it is generally recommended that the modules are programmed based on the interface, and the implementation classes are not hard-coded between the modules.

Once a specific implementation class is involved in the code, it violates the principle of pluggability, and if you need to replace an implementation, you need to modify the code. In order to realize that it can not be dynamically specified in the program when the module is assembled, a service discovery mechanism is needed.

SPI provides such a mechanism: a mechanism to find a service implementation for an interface. It is somewhat similar to IOC's idea of moving control of the assembly out of the program, which is particularly important in modular design. So the core idea of SPI is decoupling.

Introduction to use of SPI

To use Java SPI, you generally need to follow the following conventions:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

When the service provider provides a concrete implementation of the interface, create a file named with the fully qualified name `of the interface in the META-INF/services directory of the jar package, and the content is the fully qualified name of the implementation class

The jar package where the interface implementation class resides is placed in the classpath of the main program

The main program dynamically loads the implementation module through java.util.ServiceLoder. It scans the configuration file in the META-INF/services directory to find the fully qualified name of the implementation class and loads the class into JVM.

The implementation class of SPI must carry a constructor without parameters

SPI usage scenario

In a nutshell, it is applicable to the implementation strategy of enabling, extending, or replacing the framework according to the actual use needs of the caller.

The following are more common examples:

Database driver loading interface implements class loading JDBC loading drivers for different types of databases

Log facade interface implementation class loading SLF4J loading log implementation classes of different providers

SPI is widely used in Spring Spring, such as ServletContainerInitializer implementation of servlet3.0 specification, automatic type conversion Type Conversion SPI (Converter SPI, Formatter SPI), etc.

SPI is also widely used in Dubbo Dubbo to extend the framework, but it encapsulates the native SPI provided by Java and allows users to extend to implement the Filter interface.

Simple example of SPI

Define the interface class first

Package com.test.spi.learn; import java.util.List; public interface Search {public List searchDoc (String keyword);}

File search implementation

Package com.test.spi.learn; import java.util.List; public class FileSearch implements Search {@ Override public List searchDoc (String keyword) {System.out.println (File search + keyword); return null;}}

Database search implementation

Package com.test.spi.learn; import java.util.List; public class DBSearch implements Search {@ Override public List searchDoc (String keyword) {System.out.println ("database search" + keyword); return null;}}

Next, you can create a new META-INF/services/ directory under resources, and then create a file with the fully qualified name of the interface: com.test.spi.learn.Search

Add the implementation classes that we need to use

Com.test.spi.learn.FileSearch com.test.spi.learn.DBSearch

Then write a test method

Package com.test.spi.learn; import java.util.Iterator; import java.util.ServiceLoader; public class TestCase {public static void main (String [] args) {ServiceLoader s = ServiceLoader.load (Search.class); Iterator iterator = s.iterator (); while (iterator.hasNext ()) {Search search = iterator.next (); search.searchDoc ("hello world");}

You can see the output:

File search hello world Database search hello worldSPI principle Analysis

By looking at the source code of ServiceLoader and combing it, the implementation process is as follows:

The application calls the ServiceLoader.load method ServiceLoader.load method to first create a new ServiceLoader and instantiate the member variables in the class, including the following:

Loader (ClassLoader type, classloader) acc (AccessControlContext type, access controller) providers (LinkedHashMap

The application program acquires the object instance ServiceLoader through the iterator interface and first judges the member variable providers object (LinkedHashMap

If there is a cache, return it directly. If there is no cache, perform the loading of the class as follows:

(1) read the configuration file under META-INF/services/ and get the names of all the classes that can be instantiated. It is worth noting that ServiceLoader can obtain the configuration file under META-INF across jar packages.

(2) load the class object through the reflection method Class.forName () and instantiate the class with the instance () method.

(3) cache the instantiated class into the providers object, (LinkedHashMap

Summary

Advantages

The advantage of using the SPI mechanism is to decouple and separate the definition of the interface from the specific business implementation rather than coupling it. The application process can enable or replace specific components according to the actual business situation.

Shortcoming

Cannot be loaded on demand. Although ServiceLoader does deferred loading, it can only be obtained by traversing, that is, all the implementation classes of the interface have to be loaded and instantiated. If you don't want to use some implementation class, or if some class instantiation is time-consuming, it is also loaded and instantiated, which is wasteful.

The way to get an implementation class is not flexible enough, it can only be obtained in the form of Iterator, and the corresponding implementation class cannot be obtained according to a parameter.

It is not safe for multiple instances of the ServiceLoader class to be used by multiple concurrent multithreading.

An exception that is not the real cause is thrown when the implementation class is not loaded, and the error is difficult to locate.

Seeing so many shortcomings above, you must think, why do you still use these disadvantages? yes, in the process of refactoring, SPI interface is a very useful way. When you need to expand and adapt, the earlier you use it, the sooner you will benefit. At the right time and the right opportunity, pluck up the courage and restructure it!

This is the end of the content of "what is the Reconstruction method". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report