Elegant code naming convention, code is like poetry


In daily coding, code naming is a big knowledge. Being able to quickly understand the code structure and intent of open source software is also a necessary ability. So what are their rules?

The code structure of a Java project can reflect its design philosophy. Java uses long naming to standardize the naming of classes and can express its main intention by itself. Coupled with an advanced IDE, the memory burden on coders can be reduced, and the resources they need can be found through fuzzy matching.

In order to let everyone better understand the naming routine, I drew on the most popular Java open source software (spring series, netty, libgdx, guava, logback, etc.) and summarized 10 common class naming. Most of them exist in the form of suffixes, and many can be used in combination to express multiple meanings.

These words are simple but can make your class names look crisper and more professional. Next, I will take you on a tour. To facilitate understanding, I have provided corresponding examples for each type.

Insert image description here

Management class naming

Writing code requires the management of unified resources. A clear startup process can effectively organize the code. In order for the program to run, the registration and scheduling of various resources are indispensable, and the management of public collection resources is indispensable.

Bootstrap,Starter

Generally used as a program launcher, or as the base class of a launcher. In layman's terms, it can be considered as the entrance to the main function.

AbstractBootstrap
ServerBootstrap
MacosXApplicationStarter
DNSTaskStarter

Processor

A processor of a certain type of function is used to represent a certain processing process and is a collection of a series of code fragments. If you don't know how to name some sequence class code, you can use it to look more elegant.

CompoundProcessor
BinaryComparisonProcessor
DefaultDefaultValueProcessor

Manager

Manage living objects, usually as the management entrance for a certain type of resource.

AccountManager
DevicePolicyManager
TransactionManager

Holder

Indicates that it holds a reference to an object or a certain type of object and can manage it uniformly. It is more common in the unified processing of memory that is not easy to recycle, or the cache of some global collection containers.

QueryHolder
InstructionHolder
ViewHolder

Factory

There is no doubt that the naming of factory mode is familiar. Especially in Spring, there are countless.

SessionFactory
ScriptEngineFactory
LiveCaptureFactory

Provider

Provider = Strategy + Factory Method. It is more advanced and combines the strategy pattern and method factory, making it very easy to use. Provider is generally an interface or abstract class to enable sub-implementation.

AccountFeatureProvider
ApplicationFeatureProviderImpl
CollatorProvider

Registrar

Register and manage a range of resources.

ImportServiceRegistrar
IKryoRegistrar
PipelineOptionsRegistrar

Engine

Generally it is a core module, used to handle a type of function. Engine is a very advanced term, and ordinary classes are not qualified to use it.

ScriptEngine
DataQLScriptEngine
C2DEngine

Service

a service. It's too simple to give an example. The scope is too broad, don’t abuse it.

IntegratorServiceImpl
ISelectionService
PersistenceService

Task

a certain task. Usually a runnable

WorkflowTask
FutureTask
ForkJoinTask

Communication class naming

In order to complete some statistical or global class functions, some parameters need to be passed to the end. Objects of propagation classes can be passed through unified encapsulation and copied or updated in appropriate places.

Context

If your program is executed, there are some variables that need to be passed from the entry point of function execution to after a large number of sub-functions have been executed. If these variables or collections are passed as parameters, the code will become extremely verbose. At this time, you can put the variables into the Context and transfer them as a single object.

In Java, due to the existence of ThreadLocal, Context does not even need to be passed between parameters.

AppContext
ServletContext
ApplicationContext

Propagator

spread, reproduce. Used to copy, add, clear, reset, retrieve, restore and other actions on the value passed in the context. Usually, it provides a method called propagate to implement real variable management.

TextMapPropagator
FilePropagator
TransactionPropagator

Callback class naming

Using multiple cores can increase the efficiency of program operation, and inevitably introduces asynchronization. We need certain means to obtain the results of asynchronous task execution and check key points during task execution. The callback API can obtain these events through monitoring, notification, etc.

Handler,Callback,Trigger,Listener

Callback is usually an interface used to respond to a certain type of message and perform subsequent processing; Handler usually represents an object holding real message processing logic, which is stateful; tigger trigger represents the processing of certain types of events, which belongs to Handler and is usually not It will appear in the naming of the class; the application of Listener is more limited and is usually used to express specific meanings in the observer pattern.

ChannelHandler
SuccessCallback
CronTrigger
EventListener

Aware

Aware means perception. Generally, classes ending with this word implement the Aware interface. Taking spring as an example, the purpose of Aware is to allow beans to obtain services from the spring container. Specific callback methods are implemented by subclasses, such as ApplicationContextAware. It's a bit of a callback.

ApplicationContextAware
ApplicationStartupAware
ApplicationEventPublisherAware

Monitoring class naming

Today's programs are more complex, and operating status monitoring has become a must-have at home. The collection of monitoring data often requires intrusion into every corner of the program. How to effectively distinguish it from normal business is very necessary.

Metric

Represents monitoring data. Don't use Monitor, it's ugly.

TimelineMetric
HistogramMetric
Metric

Estimator

Estimate, statistics. A calculator used to calculate certain types of statistical values.

ConditionalDensityEstimator
FixedFrameRateEstimator
NestableLoadProfileEstimator

Accumulator

means accumulator. Used to cache accumulated intermediate calculation results and provide a read channel.

AbstractAccumulator
StatsAccumulator
TopFrequencyAccumulator

Tracker

Generally used for recording logs or monitoring values, usually used in apm.

VelocityTracker
RocketTracker
MediaTracker

Memory management class naming

If your application uses custom memory management, then the following terms cannot be avoided. Netty, for example, implements its own memory management mechanism.

Allocator

Related to storage, usually represents a memory allocator or manager. If your program needs to apply for large chunks of memory on a regular basis, allocator is your best choice.

AbstractByteBufAllocator
ArrayAllocator
RecyclingIntBlockAllocator

Chunk

Represents a block of memory. If you want to abstract a type of storage resources and manage them uniformly, you can use it.

EncryptedChunk
ChunkFactory
MultiChunk

Arena

English means stage and arena. Since Linux uses it for memory management, it is widely used for the application, release and management of various storage resources. Providing a stage for storage chunks of different specifications seems to be a very vivid representation.

The point is, this word is beautiful, and as a suffix it makes the class name look beautiful.

BookingArena
StandaloneArena
PoolArena

Pool

Indicates a pool. Memory pool, thread pool, connection pool, pool pool are available.

ConnectionPool
ObjectPool
MemoryPool

Filter detection class naming

There are a lot of events and information received by the program, some of which are legal, and some of which need to be filtered and thrown away. There are many forms of filtering operations depending on the scope of use and functional differences. You will find a lot of these terms in the framework class code.

Pipeline,Chain

Generally used in the chain of responsibility model. Netty, Spring MVC, Tomcat, etc. have a large number of applications. By adding a certain processing process to a certain position in the responsibility chain, you can receive the results of the previous processing process and force certain functions to be added or changed. Just like Linux's pipeline operation, the desired result is finally constructed.

Pipeline
ChildPipeline
DefaultResourceTransformerChain
FilterChain

Filter

Filters are used to filter certain data sets that meet certain conditions, or to execute part of the logic when certain conditions are met. If connected to the chain of responsibility, multi-level filtering can usually be achieved.

FilenameFilter
AfterFirstEventTimeFilter
ScanFilter

Interceptor

Interceptor is actually similar to Filter. However, in Tomcat, Interceptor can get the controller object, but filter cannot. Interceptors are wrapped in filters.

HttpRequestInterceptor
WebInterceptor

Evaluator

It means evaluator in English. It can be used to determine whether certain conditions are true. Generally, the internal method evaluate will return the bool type. For example, if you pass in a very complex object or string, you can judge whether it is correct or not.

ScriptEvaluator
SubtractionExpressionEvaluator
StreamEvaluator

Detector

detector. Used to manage a series of detection events and be able to capture and respond when they occur. For example, Android gesture detection, temperature detection, etc.

FileHandlerReloadingDetector
TransformGestureDetector 
ScaleGestureDetector

Structural class naming

In addition to basic data structures, such as arrays, linked lists, queues, stacks, etc., other higher-level common abstract classes can greatly reduce everyone's communication and encapsulate common changes.

Cache

There’s not much to say about this, it’s just caching. Large chunks of cache. Common caching algorithms include LRU, LFU, FIFO, etc.

LoadingCache
EhCacheCache
RedisCache

Buffer

Buffer is a buffer, which is different from cache. It is generally used in the data writing phase.

ByteBuffer
RingBuffer
DirectByteBuffer

Composite

Similar components are combined and exposed with the same interface or function. Users do not know whether this is a combination or other individuals.

CompositeData
CompositeMap
ScrolledComposite

Wrapper

Used to wrap an object and do some additional processing to add or remove certain functions.

IsoBufferWrapper
ResponseWrapper
MavenWrapperDownloader 

Option,Param,Attribute

Used to represent configuration information. To be honest, it is not much different from Properties, but since Option is usually a class, the function can be extended to be more powerful. It is usually smaller level than Config and focuses on the value of a single attribute. Param generally exists as a parameter, and object generation is faster.

SpecificationOption
SelectOption
AlarmParam
ModelParam

Tuple

The concept of tuples. Due to the lack of tuple structure in Java, we usually customize such a class.

Tuple1
Tuple2

Aggregator

Aggregator, which can do some aggregation calculations. For example, the collection of aggregate functions such as sum, max, and min in sub-databases and sub-tables.

BigDecimalMaxAggregator
PipelineAggregator
TotalAggregator

Iterator

iterator. You can implement Java's iterator interface, or you can have your own iteration method. When the data set is large and deep traversal is required, iterators can be said to be necessary. Using iterators can also safely delete certain elements during the iteration process.

BreakIterator
StringCharacterIterator

Batch

Certain requests or objects that can be executed in batches.

SavedObjectBatch
BatchRequest

Limiter

The current limiter uses leaky bucket algorithm or token bucket to achieve smooth current limiting.

DefaultTimepointLimiter
RateLimiter
TimeBasedLimiter

Common design pattern naming

Design pattern is the hardest hit area of ​​nouns, here are just a few of the most commonly used ones.

Strategy

Separate the abstract part from its implementation so that they can both vary independently. Strategy mode. The same interface, different implementation classes, the same method has different results, and different implementation strategies. For example, whether a configuration file is placed in xml or json file, different providers can be used to name it.

RemoteAddressStrategy
StrategyRegistration
AppStrategy

Adapter

By converting the interface of a class into another interface that the client wants, the Adapter pattern enables classes that originally could not work together due to incompatible interfaces to work together.

However, compared to traditional adapters for api transfer, if your Handler has many methods, you can use Adapter to implement some default methods for zero adaptation. Then when other classes use it, they only need to inherit the Adapter and then override the methods they want to override. This is also a common usage of Adapter.

ExtendedPropertiesAdapter
ArrayObjectAdapter
CardGridCursorAdapter

Action,Command

Encapsulating a request as an object allows you to parameterize clients with different requests, queue or log requests, and support reversible operations.

It is used to represent a series of action instructions, to implement the command mode, and to encapsulate a series of actions or functions. Action is generally used for UI operations, and back-end frameworks can be used without distinction.

In the concept of DDD, the C of Command in CQRS is Command.

DeleteAction
BoardCommand

Event

Represents a series of events. Generally speaking, in semantics, Action, Command, etc. come from active triggering; Event comes from passive triggering.

ObservesProtectedEvent
KeyEvent

Delegate

Agency or delegation model. The delegation mode is to hand over a task that belongs to the delegate to another delegate.

LayoutlibDelegate
FragmentDelegate

Builder

Separating the construction of a complex object from its representation allows the same construction process to create different representations.

Standard naming for builder pattern. Such as StringBuilder. Of course StringBuffer is an alternative. This also shows that rules are made by people, and people can break them.

JsonBuilder
RequestBuilder

Template

The naming of the template method class. Define the skeleton of an algorithm in one operation, deferring some steps to subclasses. Template methods allow subclasses to redefine specific steps of an algorithm without changing the structure of the algorithm.

JDBCTemplate
FileTemplate

Proxy

Agent mode. Provides a proxy for other objects to control access to this object.

ProxyFactory 
SlowQueryProxy

Parse class naming

Writing code involves a lot of string parsing, date parsing, object conversion, etc. They are also divided into many types according to the differences in semantics and usage situations.

Converter,Resolver

Conversion and parsing. Generally used for format conversion between different objects, converting one type of object into another type. Pay attention to their semantic differences. Generally, Resolver can be used for particularly complex conversions or requirements for loading processes.

DataSetToListConverter
LayoutCommandLineConverter
InitRefResolver
MustacheViewResolver

Parser

Used to represent very complex parsers, such as parsing DSL.

SQLParser
JSONParser

Customizer

Used to indicate a special configuration of an object. Because these configuration processes are particularly complex, they are worth extracting separately for custom settings.

ContextCustomizer
DeviceFieldCustomizer

Formatter

Formatting class. Mainly used for formatting strings, numbers or dates.

DateFormatter
StringFormatter

Network class naming

Network programming students will never get around a few terms.

Packet

Typically used for packets in network programming.

DhcpPacket
PacketBuffer

Protocol

Similarly, in user network programming, it is used to represent a certain protocol.

RedisProtocol
HttpProtocol

Encoder、Decoder、Codec

codec

RedisEncoder
RedisDecoder
RedisCodec

Request,Response

Generally used for the entry and exit of network requests. If you use it on a non-network request method, it will look weird.

CRUD naming

This is much more interesting. Unified Controller, Service and Repository, there is nothing much to say. But once you use DDD, you have to follow the DDD naming scheme.

Since DDD does not belong to the general programming category, its noun will not be introduced in detail.

other

Util,Helper

Both represent tool classes. Util is generally stateless, and Helper requires the creation of an instance before it can be used. But generally Tool is not used as the suffix.

HttpUtil
TestKeyFieldHelper
CreationHelper

Mode,Type

When you see the suffix mode, you can guess that this class is most likely an enumeration. It usually lists the common possibilities in the enumeration class, and this Mode can be referenced elsewhere.

OperationMode
BridgeMode
ActionType

Invoker,Invocation

Invoker is a type of interface that usually executes some specific business logic through reflection or triggering. By abstracting the invoke method, input parameters can be recorded or processed before invoke is executed; processing results and exceptions after invoke is executed is a common operation method in AOP.

MethodInvoker
Invoker
ConstructorInvocation

Initializer

If your application requires a large number of initialization operations to start, then you need to separate it and specifically handle the initialization actions.

MultiBackgroundInitialize
ApplicationContextInitializer

Feture,Promise

They are used between multiple threads for data transfer.

Feture is equivalent to a placeholder, representing the future result of an operation. Generally, you can directly block the result through get, or let it execute asynchronously and then call back the result through callback.

But what if there is a callback embedded in the callback? If the level is very deep, it is callback hell. CompletableFuture in Java is actually Promise, used to solve the callback hell problem. Promises exist to make code beautiful.

Selector

According to a series of conditions, corresponding similar resources are obtained. It is more like Factory, but only handles a single resource.

X509CertSelector
NodeSelector

Reporter

Used to report certain execution results.

ExtentHtmlReporter
MetricReporter

Constants

Generally used for constant lists.

Accessor

A class that encapsulates a series of get and set methods. Like lombok, there are Accessors annotations to generate these methods. However, the Accessor class generally completes get and set through calculation rather than directly operating variables. This is suitable for more complex object access services.

ComponentAccessor
StompHeaderAccessor

Generator

Generators are generally used to generate codes, generate IDs, etc.

CodeGenerator
CipherKeyGenerator

END

When writing code and looking at the source code, how come you don’t get insights and supernatural powers? The code should be interesting and the naming should be elegant. If you name it well, the code will look cool and everyone will like it.

If you can't explain something clearly, just give me a piece of code and we will understand! It's so magical!

In fact, writing professional code does not require knowing too many English words. Most of the time, you don't need such a remarkable level as English level 4. With only a limited number of words, you can create a Hollywood feel in the code world.

After reading this article, look through the codes of open source software and see if this is true?

The above names exist in various frameworks with high frequency. If you understand these terms, reading most of the source code can be said to be no obstacle at all. In the same scenario, it has become a tacit norm for everyone to use these terms first.

There are many nouns that come from design patterns, but special words are used in specific situations, such as Provider. Just feel the difference carefully.

Naming is a very important part of coding. I hope you can find the rules to make your code functional and beautiful. I hope your salary will increase as time goes by, making it worthy of your professionalism and craftsmanship.

Original link: https://mp.weixin.qq.com/s/rGp6nC_0HzD5DxA5wuG37w

Guess you like

Origin blog.csdn.net/qq_38254635/article/details/131855706