⚠️ this article for nuggets community first contract article, not authorized to forbid reprint

In everyday coding, code naming is a big deal. Being able to quickly read the structure and intent of open source software code is also a must. So what’s the pattern?

The code structure of a Java project reflects its design philosophy. Java uses the long naming method to regulate the naming of classes, which can express its main intention. With an advanced IDE, you can reduce the memory burden of the coder and find the resources you need by vague matching.

To give you a better idea of how to name classes, I’ve compiled a list of 10 common class names that I’ve taken from the most popular Java open source software (Spring, Netty, libgdx, Guava, Logback, etc.). Most are in the form of suffixes, but many can be combined to express multiple meanings.

These words are simple, but can make your class names look clean and professional. Next, I’m going to take you on a tour. For ease of understanding, I have provided examples for each type.

Management Class Naming

Writing code requires unified resource management, and a clear startup process can effectively organize the code. In order to make the program run, it is necessary to register and schedule various resources, and it is necessary to manage public collection resources.

The Bootstrap, Starter

Generally used as a program initiator, or as a base class for an initiator. In layman’s terms, think of it as the entry to the main function.

AbstractBootstrap
ServerBootstrap
MacosXApplicationStarter
DNSTaskStarter
Copy the code

Processor

A processor for a class of functions, used to represent a process, is a collection of code snippets. If you don’t know the name of some sequential class code, you can use it to make it look more glamorous.

CompoundProcessor
BinaryComparisonProcessor
DefaultDefaultValueProcessor
Copy the code

Manager

This section describes how to manage objects with a living state, usually as the entry point of a certain type of resource.

AccountManager
DevicePolicyManager
TransactionManager
Copy the code

Holder

It holds references to an object or a class of objects and manages them in a unified manner. This is often seen in the uniform processing of memory that is not easy to reclaim, or in the caching of some global collection container.

QueryHolder
InstructionHolder
ViewHolder
Copy the code

Factory

There is no doubt that the name of the factory model is familiar. Especially in Spring, there are so many.

SessionFactory
ScriptEngineFactory
LiveCaptureFactory
Copy the code

Provider

Provider = Strategy + Factory Method. It’s a little more advanced, and it’s a combination of strategic patterns and methods that makes it easy to use. Providers are generally interfaces or abstract classes so that they can complete sub-implementations.

AccountFeatureProvider
ApplicationFeatureProviderImpl
CollatorProvider
Copy the code

Registrar

Register and manage a range of resources.

ImportServiceRegistrar
IKryoRegistrar
PipelineOptionsRegistrar
Copy the code

Engine

They are typically core modules that handle a class of functions. Engine is such a high-level term that ordinary classes are not qualified to use it.

ScriptEngine
DataQLScriptEngine
C2DEngine
Copy the code

Service

A service. Too simple to give an example. The scope is too broad. Don’t abuse it.

IntegratorServiceImpl
ISelectionService
PersistenceService
Copy the code

Task

A task. It’s usually a runnable

WorkflowTask
FutureTask
ForkJoinTask
Copy the code

Propagation class naming

In order to perform some of the functions of the statistics class or global class, some parameters need to be passed through. Objects of the propagation class can then be passed in a uniform wrapper and copied or updated where appropriate.

Context

If your program executes, and you have some variables, you need to start at the entry point of the function execution, all the way down to the end of the big quantum function execution. These variables or collections, if passed as arguments, would make the code infinitely verbose. At this point, you can plug the variable into the Context and pass it as a single object.

In Java, the Context doesn’t even have to be passed between parameters because of ThreadLocal.

AppContext
ServletContext
ApplicationContext
Copy the code

Propagator

Spread, reproduce. It is used to copy, add, clear, reset, retrieve, restore and so on the value passed in the context. In general, it provides a method called Propagate for real variable management.

TextMapPropagator
FilePropagator
TransactionPropagator
Copy the code

Callback class name

Using multiple cores can increase the efficiency of program running, and inevitably introduce asynchrony. We need to have certain means to obtain the results of asynchronous task execution and check the key points in the process of task execution. The callback API can obtain these events through listening, notification, and so on.

Handler, Callback, Trigger, and Listener

A callback is usually an interface that responds to a certain type of message for subsequent processing. Handler usually represents the object that holds the real message processing logic, which is stateful; A Tigger trigger represents the handling of a certain type of event, which belongs to a Handler and is usually not included in the class name; The application of a Listener is more limited and is usually used in observer mode to represent a specific meaning.

ChannelHandler
SuccessCallback
CronTrigger
EventListener
Copy the code

Aware

Aware simply means to be Aware, and classes that end with the word generally implement the Aware interface. In the case of Spring, the purpose of Aware is for beans to get services from the Spring container. Specific callback methods are implemented by subclasses, such as ApplicationContextAware. It’s kind of a callback.

ApplicationContextAware
ApplicationStartupAware
ApplicationEventPublisherAware
Copy the code

Monitoring Class Naming

Today’s programs are more complex, and health monitoring has become a must-have at home. Monitoring data collection often needs to intrude into the edges and corners of the program, how to effectively distinguish from normal business, is very necessary.

Metric

Indicates monitoring data. Don’t use Monitor. It’s ugly.

TimelineMetric
HistogramMetric
Metric
Copy the code

Estimator

Estimate, estimate, estimate A calculator used to calculate a class of statistics.

ConditionalDensityEstimator
FixedFrameRateEstimator
NestableLoadProfileEstimator
Copy the code

Accumulator

Accumulator. Used to cache accumulated intermediate calculations and provide a read channel.

AbstractAccumulator
StatsAccumulator
TopFrequencyAccumulator
Copy the code

Tracker

Generally used to log or monitor values, usually used in APM.

VelocityTracker
RocketTracker
MediaTracker
Copy the code

Name the memory management class

If your application uses custom memory management, the following terms are not to be avoided. Netty, for example, has implemented its own memory management mechanism.

Allocator

Associated with storage, it usually represents a memory allocator or manager. If your application needs regular chunks of memory, allocator is your choice.

AbstractByteBufAllocator
ArrayAllocator
RecyclingIntBlockAllocator
Copy the code

Chunk

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

EncryptedChunk
ChunkFactory
MultiChunk
Copy the code

Arena

Stage, arena, arena Since Linux has used it for memory management, it is widely used for the application, release, and management of various storage resources. Providing a stage for different chunks of storage also seems to be a very visual representation.

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

BookingArena
StandaloneArena
PoolArena
Copy the code

Pool

It’s a pool. Memory pool, thread pool, connection pool, pool pool available.

ConnectionPool
ObjectPool
MemoryPool
Copy the code

Name the filter detection class

The program receives a lot of events and information, some are legal, some need to be filtered out. Filtering operations can take many forms, depending on the range of use and functional differences. You’ll find a lot of these nouns in the framework class code.

Pipeline, Chain

Commonly used in chain of responsibility patterns. Netty, Spring MVC, Tomcat and so on have a lot of applications. By adding a process somewhere in the chain of responsibility, you can receive the results of a previous process and force some functionality to be added or changed. Just like Linux pipelines, the desired result is constructed.

Pipeline
ChildPipeline
DefaultResourceTransformerChain
FilterChain
Copy the code

Filter

Filters that filter certain sets of data that meet certain conditions, or perform a portion of the logic when certain conditions are met. If linked to a chain of responsibility, it is often possible to implement multiple levels of filtering.

FilenameFilter
AfterFirstEventTimeFilter
ScanFilter
Copy the code

Interceptor

Interceptors, which are really similar to filters. In Tomcat, however, Interceptor can get the Controller object, but filter cannot. Interceptors are wrapped in filters.

HttpRequestInterceptor
Copy the code

Evaluator

“Evaluator” means “evaluator” in English. It can be used to determine whether certain conditions are true. Generally, evaluate, the internal method, returns a bool. Let’s say you pass in a very complex object, or a string, to determine whether it’s correct or not.

ScriptEvaluator
SubtractionExpressionEvaluator
StreamEvaluator
Copy the code

Detector

Detector. It is used to manage a series of probing events and to capture and respond to them as they occur. For example, Android gesture detection, temperature detection and so on.

FileHandlerReloadingDetector
TransformGestureDetector 
ScaleGestureDetector
Copy the code

Structure class naming

In addition to basic data structures such as groups, linked lists, queues, stacks, and so on, the common abstract classes at a higher level can greatly reduce communication between people and encapsulate common changes.

Cache

There’s nothing to say about this, it’s just caching. Large chunks of cache. Common caching algorithms include LRU, LFU, FIFO and so on.

LoadingCache
EhCacheCache
Copy the code

Buffer

A buffer is a buffer, unlike a cache, which is usually used during the data write phase.

ByteBuffer
RingBuffer
DirectByteBuffer
Copy the code

Composite

Similar components are combined and exposed with the same interface or functionality without the consumer knowing whether it is a combination or another individual.

CompositeData
CompositeMap
ScrolledComposite
Copy the code

Wrapper

Used to wrap an object and do some extra processing to add or remove functionality.

IsoBufferWrapper
ResponseWrapper
MavenWrapperDownloader 
Copy the code

Option, Param,Attribute

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

SpecificationOption
SelectOption
AlarmParam
ModelParam
Copy the code

Tuple

The concept of tuples. Due to the lack of tuple structures in Java, we usually customize such classes.

Tuple2
Tuple3
Copy the code

Aggregator

Aggregators, which can do some aggregation calculations. For example, the collection of aggregation functions such as sum, Max, min, etc.

BigDecimalMaxAggregator
PipelineAggregator
TotalAggregator
Copy the code

Iterator

Iterators. You can implement the Java iterator interface or have your own way of iterating. Iterators are a must when the data set is large and deep traversal is required. Iterators also allow you to safely remove certain elements during an iteration.

BreakIterator
StringCharacterIterator
Copy the code

Batch

Certain requests or objects that can be executed in batches.

SavedObjectBatch
BatchRequest
Copy the code

Limiter

Current limiter, which uses the leaky bucket algorithm or token bucket to accomplish smooth current limiting.

DefaultTimepointLimiter
RateLimiter
TimeBasedLimiter
Copy the code

Common design pattern naming

Design patterns are the hardest hit nouns, so here are just a few of the most commonly used ones.

Strategy

Separate the abstraction from its implementation so that both can change independently. Policy mode. The same interface, different implementation classes, the same method results different, different implementation strategy. For example, a configuration file, whether it is placed in XML or JSON file, can be named using different providers.

RemoteAddressStrategy
StrategyRegistration
AppStrategy
Copy the code

Adapter

The Adapter pattern converts the interface of one class to another that the customer wants. The Adapter pattern makes classes that otherwise wouldn’t work together because of incompatible interfaces work together.

However, compared to traditional Adapter API conversions, if you have a particular Handler with many methods, you can use Adapter to implement some default methods for 0 adaptation. When other classes use Adapter, they just need to inherit the Adapter and override the methods they want to override. This is also a common use of Adapter.

ExtendedPropertiesAdapter
ArrayObjectAdapter
CardGridCursorAdapter
Copy the code

The Action of the Command

Encapsulating a request into an object allows you to parameterize customers with different requests, queue or log requests, and support undoable operations.

To represent a sequence of action instructions, to implement command patterns, and to encapsulate a sequence of actions or functions. Actions are generally used for UI operations, and the backend framework can be used indiscriminately.

In the concept of DDD, THE C of CQRS Command is called Command.

DeleteAction
BoardCommand
Copy the code

Event

Represents a series of events. Generally, semantically, actions, commands, etc., come from active trigger; Events come from passive triggers.

ObservesProtectedEvent
KeyEvent
Copy the code

Delegate

Agent or delegate mode. The delegating mode is to entrust one thing that belongs to the delegator to another delegator.

LayoutlibDelegate
FragmentDelegate
Copy the code

Builder

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

Standard naming of the builder pattern. For example, the StringBuilder. StringBuffer, of course, is an anomaly. It also shows that rules are made by people and can be broken by people.

JsonBuilder
RequestBuilder
Copy the code

Template

The naming of the template method class. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The template approach allows subclasses to redefine certain steps of an algorithm without changing the structure of the algorithm.

JDBCTemplate
Copy the code

Proxy

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

ProxyFactory 
SlowQueryProxy
Copy the code

Parsing class naming

Writing code involves a lot of string parsing, date parsing, object conversion, and so on. They are also divided into different types, depending on the semantics and the situation of use.

The Converter, the Resolver

Transformation and parsing. Generally used for format conversion between different objects, to convert one class of objects into another class. Note the differences semantically, Resolver can be used for particularly complex transformations or for loading requirements.

DataSetToListConverter
LayoutCommandLineConverter
InitRefResolver
MustacheViewResolver
Copy the code

Parser

Used to represent very complex parsers such as parsing DSLS.

SQLParser
JSONParser
Copy the code

Customizer

Used to indicate a particular configuration of an object. Because these configuration procedures are particularly complex, it is worth extracting them separately for customization.

ContextCustomizer
DeviceFieldCustomizer
Copy the code

Formatter

Format classes. Mainly used for string, number, or date formatting work.

DateFormatter
StringFormatter
Copy the code

Network class naming

Network programming students, never around the past a few nouns.

Packet

Typically used for packets in network programming.

DhcpPacket
PacketBuffer
Copy the code

Protocol

Also in user network programming, used to represent a protocol.

RedisProtocol
HttpProtocol
Copy the code

Coder, Decoder, Codec

Encoding decoder

RedisEncoder
RedisDecoder
RedisCodec
Copy the code

The Request and Response

Generally used for inbound and outbound network requests. If you use it in a non-network request way, it’s weird.

CRUD named

This is a lot more interesting, unified Controller, Service, Repository, nothing to talk about. But once you use DDD, you have to follow the DDD set of names.

Since DDD does not fall into the category of general purpose programming, there is not much to say about its terminology.

other

Util, Helper

Both represent utility classes, and Util is generally stateless, a Helper in case you need to create an instance to use it. But generally do not use Tool as the suffix.

HttpUtil
TestKeyFieldHelper
CreationHelper
Copy the code

Mode, Type

By looking at the mode suffix, you can guess that this class is most likely an enumeration. It usually lists the common possibilities in an enumeration class and references the Mode elsewhere.

OperationMode
BridgeMode
ActionType
Copy the code

Invoker, Invocation

An Invoker is an interface that performs some concrete business logic, usually in a reflection or trigger manner. By abstracting the Invoke method, the incoming parameters can be recorded or processed before the invoke execution. Handling results and exceptions after invoke execution is a common operation in AOP.

MethodInvoker
Invoker
ConstructorInvocation
Copy the code

Initializer

If your application needs a lot of initialization to launch, you need to make it a separate application that handles the initialization.

MultiBackgroundInitialize
ApplicationContextInitializer
Copy the code

The Feture, Promise

They’re all used to transfer data between multiple threads.

A Feture is a placeholder for the future result of an operation. Generally, you can block the result directly with get, or let it execute asynchronously and then callback the result with callback.

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

Selector

According to a series of conditions, obtain corresponding similar resources. It is more like a Factory, but only deals with a single resource.

X509CertSelector
NodeSelector
Copy the code

Reporter

Used to report certain execution results.

ExtentHtmlReporter
MetricReporter
Copy the code

Constants

Commonly used for lists of constants.

Accessor

A class that encapsulates a set of get and set methods. Lombok, for example, has Accessors annotations that generate these methods. But the Accessor class generally does get and set computationally, rather than directly manipulating variables. This is suitable for more complex object access services.

ComponentAccessor
StompHeaderAccessor
Copy the code

Generator

Generator, generally used to generate code, generate ID, etc.

CodeGenerator
CipherKeyGenerator
Copy the code

End

Write code, look at the source code, how little will and avatar? Code to take sense, naming also coquettish. Well named, the code will look good, and everyone will love it.

Say not clear thing, give a piece of code, we can understand! That’s amazing!

In fact, to write professional code, you don’t need to know too many English words, and most of the time you don’t need English level 4 so great. With only a limited number of words, you can play the Hollywood of code.

After reading this article, turn over the source software code to see if this is true?

These names, high frequencies exist in various frameworks. Once you understand these terms, you can read most source code without any obstacles at all. It has become an unspoken norm to use these nouns preferentially in the same context.

There are many nouns that come from design patterns, but use specific words in specific situations, such as Provider. Just take a look at the difference.

Naming is a very important part of the code, I hope you find the rule, let your code function on the powerful, good-looking appearance level; I wish you all a rising salary worthy of your professionalism and artisan spirit.

⚠️ this article for nuggets community first contract article, not authorized to forbid reprint