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 the way to manage constants in your code

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 knowledge of "what is the method of managing constants in code". In the operation of actual cases, many people will encounter such a dilemma, so 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!

First, let's see how the seniors do it.

In Web development, there is a constant that cannot be bypassed, that is, the status code of HTTP. It is better to take this as a starting point.

Org.springframework.http.HttpStatus

① uses enumerations

Public enum HttpStatus {CONTINUE (100, "Continue"), SWITCHING_PROTOCOLS (101, "Switching Protocols"), PROCESSING (102, "Processing"), CHECKPOINT (103, "Checkpoint"), OK (200, "OK"), CREATED (201, "Created"), ACCEPTED (202, "Accepted"), NON_AUTHORITATIVE_INFORMATION (203, "Non-Authoritative Information"), NO_CONTENT (204, "No Content") ... org.eclipse.jetty.http.HttpStatus

Define constants in the ② class

Public class HttpStatus {public static final int CONTINUE_100 = 100; public static final int SWITCHING_PROTOCOLS_101 = 101; public static final int PROCESSING_102 = 102; public static final int OK_200 = 200; public static final int CREATED_201 = 201; public static final int ACCEPTED_202 = 202; public static final int NON_AUTHORITATIVE_INFORMATION_203 = 203; public static final int NO_CONTENT_204 = 204;... org.apache.hc.core5.http.HttpStatus

Define constants in the ③ final class

Public final class HttpStatus {public static final int SC_INFORMATIONAL = 100; public static final int SC_CONTINUE = 100; public static final int SC_SWITCHING_PROTOCOLS = 101; public static final int SC_PROCESSING = 102; public static final int SC_EARLY_HINTS = 103; public static final int SC_SUCCESS = 200; public static final int SC_OK = 200; public static final int SC_CREATED = 201; public static final int SC_ACCEPTED = 202 Public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; public static final int SC_NO_CONTENT = 204;

The above are all defined in common open source frameworks, and I have seen a usage in business, which is

④ defines constants in the interface

Public interface HttpStatus {public static final int CONTINUE_100 = 100; public static final int SWITCHING_PROTOCOLS_101 = 101; public static final int PROCESSING_102 = 102; public static final int OK_200 = 200; public static final int CREATED_201 = 201; public static final int ACCEPTED_202 = 202; public static final int NON_AUTHORITATIVE_INFORMATION_203 = 203; public static final int NO_CONTENT_204 = 204;

This kind of interface is called constant interface, but in the suggestion that "interface is only used to define type" in "Effective Java", this constant interface is particularly criticized, saying that "constant interface mode is a bad use of interface". The original text is described as follows:

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if ina future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

Constant interface mode is a bad way to use interfaces. Some constants are used inside the class, which are implementation details. However, implementing a constant interface causes this implementation detail to leak to the export API of the class. For users of a class, there is little value for a class to implement a constant interface. In fact, it may even confuse them. To make matters worse, it represents a commitment that if a class is modified in a future release so that it no longer needs to use constants, it must still implement the interface to ensure binary compatibility. If a non-final class implements a constant interface, the namespaces of all its subclasses will be contaminated with constants in the interface.

Considering that constant classes should not be inherited, it is more appropriate to use final than none.

In addition, setting the constructor to private is an additional protection, considering that constant classes should not need to be instantiated.

To sum up, using enumerations and final constant classes is the first choice, so how to choose between the two? We can still get valid advice from "Effective Java", which in section 34 suggests that we replace int constants with enumerations.

How to manage constant classes

Although enumeration is the first choice, constant classes will not disappear. Constants are not only int constants, string constants are also inevitable in daily development, and sometimes we still find constants more convenient. So how do you manage these constants?

Constant bad smell 1. Giant constant class

Put all the constants used in the program into a Constants class. There are some disadvantages in doing so.

In order to add constants, this class will be modified very frequently.

There will be a lot of code that depends on this constant class

In order to use a constant, it will result in the introduction of a lot of irrelevant constants

two。 Duplicate constant definition

As a newcomer to the workplace, one of the things I often do is to define constants repeatedly, because I don't know if others have defined them or where. Instead of going through the entire code base to find this constant, it is much more convenient to define one myself.

Until one day I need to modify the definition of a constant, the previous debt will need to be repaid. The biggest problem with repeating code is that when you need to modify or maintain that repetitive code, you need to modify everything, and if there is an omission, it is bug. The same is true of repetitive constants.

Management ideas 1. Define multiple constant classes with a single function

One idea is to define constants in terms of functional dimensions, and a constant class is only related to a function.

Such as MySQLConstants, RedisConstants.

But there is a very virtual concept, that is, function, a function can be big or small, the category can be a certain class, or an entire module, there is no final conclusion here, it depends on the programmer's smart mind and rich experience.

two。 Do not define constant classes separately

Another way of thinking is not to design constant classes separately, but to define constants in any class in which they are used.

For example, constants from previous RedisConstants are used in both RedisClient and RedisConfig, and can be defined in RedisClient and RedisConfig, respectively.

But the obvious problem with this is that if multiple classes use the same constant, if their definitions are duplicated, if a declaration is defined as public, it will result in dependencies between the two classes. From this point of view, in the absence of reuse claims, in-place definition is preferable.

3. Hierarchical reuse

Neither of the above two ways can completely solve our puzzles. considering the combination of the above two ways, we can get a hierarchical way of defining reuse.

Cross-application reuse constants: placed in a two-party library, usually under the constant directory in client.jar.

Intra-application reuse constants: placed in a library, usually under the constant directory in common.

Reuse constants within the module: that is, in the constant directory of the current sub-project.

In-package reuse constant: that is, under a separate constant directory under the current package.

Intra-class reuse constant: private static final definition directly inside the class.

This is the end of the content of "what is the method of managing constants in code". Thank you for 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