The evil annotations in Java

Source: Internet
Author: User

This article by the Code Rural Network – Sun Tenghao original translation, reproduced please see the text at the end of the reprint requirements, welcome to participate in our paid contribution program!

When Java 1.5 introduces annotations, enterprise developers have great expectations for simplifying EJB and other enterprise product development. You can take a look at one article in the same period simplify enterprise Java development with EJB 3.0.

Since then, however, there have been unforeseen consequences and side effects of the use of annotations by Java Enterprises, some of which have not even been noticed today. Fortunately, not all of the side effects are not noticed, see some examples in StackOverflow titled "Why Java Annotations?" There are a lot of valuable comments, "is Annotations bad?" This article has a great view, and "Magics is Evil", "Annotations ... Good, bad or Worse? ".

Not all annotations are the same

Although many of the discussions above contain valuable ideas, not all annotations are the same.

There are two types of annotations, the difference being whether they affect the program at run time. First, to say the harmless category, they do not have any effect on the code at run time, and the other is a harmful one, which modifies the run-time behavior. Harmless annotations include @deprecated, @Override, @SuppressWarnings, and so on. Harmful annotations include @entity, @Table, @PostConstruct, @ApplicationScoped, and so on.

There are a small number of annotations in harmless annotations that are very useful. There are some offers to catch errors during compilation (static check) or to provide security. Some useful notes include: @Override, @NonNull/@Nullable from (Checker Framework), etc.

Why are harmful annotations bad?

We have defined some harmful annotations, why should we avoid using them?

Imagine a standard Java data class that has the @postconstruct method. This annotation indicates that the method being annotated should be called after the object has been created. This function is not handled by the JVM, so the date class implicitly acquires the unknown frame and container, and does not semantically do anything. What if the code is not running in any container, but just running in the JVM? This annotation greatly reduces the reusability of this class. It is also a nightmare for any unit test where date is used, because you must ensure that post-construction is properly bound every time, to simulate a compatible container. It's a little ridiculous that a date class needs a container to run, but this is really the effect of harmful annotations on classes, methods, and parameters.

Admittedly, business logic is often complex and requires more dependencies and relationships than just a simple date class. However, there is no reason to add unnecessary dependencies or constraints explicitly or implicitly in a class, and harmful annotations are: dependencies and constraints.

Enterprise Traps

Unfortunately the harmful statements are legalized on a large scale in Java Enterprise 5. To correct the ease of use of early enterprise APIs, annotations are used to hide redundant and hard-to-use parts of the system. The new Jee 5 is praised as "lightweight" and "simple", ostensibly like this. But a tiny, but also crucial misuse of the spread.

@Statelessdocumentrepository {   getdocument(String title) {...} ...}  

If you want to get a stateless EJB, simply declare the @stateless annotation on the class. It is true that writing this class requires only a bit of action, but note that the harmful annotations in this class are bound to the hundreds of-page documentation and can only be run on a million-byte application server (Application Server). How can this be called "lightweight"? So, this annotation is just a placeholder for the Java code that really needs to be written, and the code still needs to exist in some form. Now it's just hiding underneath the annotations.

Unfortunately, this workaround is called a pattern, and now the harmful annotations are widely distributed: JPA, CDI, Common Annotations, JAXB, and so on.

Harmful annotations sometimes appear in the wrong place

Because annotations are often used as a development environment, sometimes harmful annotations are considered best practices for single-Responsibility Principle or separation of concerns (separation of concerns).

Let's consider the following CDI example:

@ApplicationScopeddocumentformatter {   ...}

The above note describes that the class should be a CDI Bean, meaning that it should only be instantiated by CDI, and that there is only one instance in each application.

This information does not belong to this class. The functionality of the service (in any way) does not have an impact on its role in the current application. Here are two obvious points of concern.

A simple example of JPA:

@Entity@Table (' person ') person{...}  

The problem is that this category is often "domain objects", which persists the domain model directly. To make things worse, data transfer objects (DTOS) are used to transfer data between objects, making the entire structure brittle because the coupling between objects is too tight. In any case, this is a wrong way.

All of these additional features and/or information should be separated from these classes, but they are quietly mixed together because they are "just" annotations.

Harmful annotations are sometimes spread

Annotations can sometimes infect other objects. Review the CDI Bean above. Each object that uses it, each object that relies on it now has a CDI annotation, otherwise the dependency tree will not build successfully.

The same is true for @Entity annotations. Because of the relationship between objects, other objects are persisted by annotations, and soon all persisted objects will have this annotation. We cannot use native third-party objects (unless we serialize or wrap them) and we cannot use other persistence mechanisms (such as storing objects in NoSQL db).

These annotations make it impossible for these objects to be reused. They can only be used in a strict, controlled, opaque environment and cannot be integrated with anything.

What are the alternatives?

Is it XML? Of course not, at least not for the above example.

The spring framework uses configuration to manage objects, so you can use XML as a configuration file. However, does a dependency need to change at run time without recompiling? If not, it is hard to say that the configuration should be represented in another language, especially refactoring difficulties, testing difficulties, and management requiring special tools.

The real alternatives are, of course, good Java code, which is properly encapsulated and decoupled. Yes, using code to manage objects, although sometimes used as boilerplate (boilerplate), is not too bad. It brings some benefits, such as making the code readable, debugged, and reconfigurable. Only those long, complex, redundant templates are bad, such as "About EJB 2.0". But the solution is not to get rid of all the boilerplate or hide the template in another language, but rather a simple and clean architecture that is straightforward and not redundant, and is simple and appropriate to object-oriented.

This also applies to JPA, spring, and other things. The misuse of annotations to represent functionality can occur stcakoverflow on this issue "Arguments against Annotations", why not use existing tools: such as the Java language itself and compilers, to solve such problems, object-oriented and software best practices.

Summarize

If annotations add additional functionality and constraints to the code's run time, it is harmful. This is bad because it hides the facets of a class or method, making it difficult to understand, difficult to reuse, difficult to refactor, and difficult to test.

Unfortunately, Java Enterprise ignores the voice of annotations in the Java developer community. So enterprise-class Java and other "official" frameworks are less likely to focus on such issues.

At a minimum, we can continue to focus on harmful annotations, and if possible avoid them, write new frameworks and software to replace annotations without the problem of harmful annotations.

Link: http://www.codeceo.com/article/java-evil-annotations.html
English Original: Evil Annotations
Translation Code Rural Network – Sun Tenghao
[ reproduced in the text must be marked and retained in the original link, translation links and translators and other information. ]

The evil annotations in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.