You should update the common Java library, java

Source: Internet
Author: User

You should update the common Java library, java

In the eyes of many people, Java is already an old language, but it does not prevent the Java World from moving forward. If you have left Java, traveled to other worlds, or struggled with the legacy code every day, you may have to raise your head to see new things in old Java.

Guava

Guava[Gw runtime: v runtime]. In a word, Guava (Github) should be used as long as you are working on a Java project ). Official API.

Guava is a set of core Java libraries produced by Google. In my opinion, it should even be part of JDK. As a Java programmer, if you have never complained about JDK design, you can only describe that you write too few programs. It is precisely because of the poor JDK design that there are some projects to supplement the shortcomings of JDK. If the old Java programmer has heard of Apache Commons Lang, the new Java programmer should know Guava.

The old Java programmer knows Google Collections more and may wish to go to its home page. You will see that this library has been renamed Guava. In fact, Guava is not directly equivalent to Google Collections, and Guava is a superset. Guava is so powerful. To show its strength, we need to introduce it specially.

The following uses a small program for counting the number of words and numbers as the end of this section. Although it cannot be compared with the implementation of many other languages, as a Java programmer, you may wish to think about it in the traditional way, what should this code look like.

String content = Files.toString(new File(args[0]), Charset.defaultCharset());
 
Iterable texts = Splitter.on(CharMatcher.WHITESPACE)
                                               .omitEmptyStrings()
                                               .trimResults()
                                               .split(content);
Multiset collection = HashMultiset.create(texts);

In addition, Guava provides:

  • Cache, local cache implementation, support for multiple cache expiration policies );
  • Primitives extends native type operations (such as int and char) not provided by JDK, including some types of unsigned form;
  • Concurrency libraries (concurrency) is a powerful and simple abstraction that simplifies the compilation of correct concurrent code;
  • Common annotations ),
  • String processing (string processing), a string tool, including operations such as segmentation, connection, and filling;
  • Event bus and publish-subscribe mode components do not need to be explicitly registered to other components;
  • I/O simplifies the operations of I/O, especially I/O streams and files, for Java 5 and 6;
  • Reflection (Reflection), Guava's Java Reflection mechanism tool class;
  • Hash to provide a ratioObject. hashCode ()More complex hash implementation and bloom filter implementation.
Joda Time

If you think an API is poorly designed, You Can Deprecated all your APIs.Java. util. Date is such a wonderful thing. Because almost all its APIs are counter-intuitive, almost all Java programmers who dare to use them have suffered from its loss. It's not that easy to initialize the first day of June 1, 2013:

Date firstDayOf2013 = new Date(113, 0, 1);

If you are a beginner in Java, can you guess where 113 came from? (Well, It's 2013-1900. As for why it's 1900, I really want to ask the API designer ).

Joda Time is the product that people cannot bear. The same Code is implemented using Joda Time:

DateTime firstDayOf2013 = new DateTime().withDate(2013, 1, 1);

In any case, you can see the meaning of these parameters. In addition, you can also calculate the day of two days:

firstDate.plusDays(2);

Date formatting is also a feature of JDK Date APIs. You must write the code as follows:

new SimpleDateFormat("yyyy.MM.dd").format(firstDayOf2013)

As a slow initialization constructor, you must call it every time because it is not thread-safe. In the same code, in Joda Time, we can use DateTimeFormatter:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy.MM.dd");
...
formatter.print(dateTime);

Please feel free to declare formatter as a field because it is thread-safe.

Of course, Joda Time is far more powerful than that. Of course, JDK is not completely self-defeating, so we have a JSR 310 dedicated to designing a new Date API. Spec lead of JSR 310 is Steven Colebourne, author of Joda Time. However, although JSR 310 depicts the new scene of Date for us, before Java 8 came out, we should leave it alone. Use Joda Time to download Joda Time (IBM, sourceForge ).

For more information about Joda Time, see Joda-Time introduction.

 

 

 

 

 

 

Hamcrest

In a word, if you write unit tests, Hamcrest should be used.

If you do not want to write unit tests today, you are embarrassed to say that you are working on a project. But do you write assertions like this? If you write the following statement, I can only say that you are out of date:

assertEquals(a, b);

Please tell me which is the execution result and which is the expected result, no matter what you are, I cannot remember it in most cases.Therefore, it is time to update the API generated when only the function is disabled. Therefore, Hamcrest was born to solve such problems.

assertThat(a, is(b));

Obviously, the first is the execution result, and the other is the expected result. Of course, this is just a simple example. Since Hamcrest introduces the matcher concept (that is, the is part you see), we can make more combinations:

assertThat(number, greaterThan(5));
assertThat(text, startsWith("Hello"));
assertThat(array, hasItem("World"));

Hamcrest is so useful that JUnit has absorbed it. If the JUnit version you are using is later than 4.4, you already have Hamcrest. You can use it without additional configuration.

Mockito

Writing Unit Tests without the Mock framework is almost impossible. I mean, the Mock framework is not the Mock mode! For older Java programmers, when talking about the Mock framework, most of the first hits in their minds are JMock or EasyMock.

To use Mockito, there is only one reason. Compared with JMock, it does not need to write checking. Compared with EasyMock, it saves replay. The following is an example:

List mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("first");
System.out.println(mockedList.get(0));

Of course, Mockito is very powerful.

Once again, no matter which framework is used, please try not to use verify, that is, the legendary Mock mode, which is the beginning of pulling the code into the quagmire.

SLF4J and Logback

Logs are almost invisible to a slightly larger project. If you are an old Java programmer, you must know Log4J, and most of them know Commons Logging. It is time to discard them because SLF4J and Logback are available. SLF4J should replace Commons Logging, and the goal of Logback is Log4J.

I am angry with many programmers. The author of SLF4J and Logback is Ceki gülc. In fact, he is also the author of Log4J. The development status of Log4J really makes him so uncomfortable, so he made a new alternative.

Just one point is enough for us to ignore SLF4J. Do you still remember to use Commons Logging to write such code?

if (logger.debugEnable()) {
  logger.debug("Hello, ", name);
}

SLF4J has only one sentence:

logger.debug("Hello, {}", name);

In terms of its root cause, this is the result of the Times. Commons Logging was generated before Java 5 and has not changed the parameter at that time. Therefore, we have to say that it is old.

As for Logback, performance is the most important stunt. Of course, there are some other reasons. I did not mention one of the reasons, but it is very considerate for developers to improve the log mode. Do you still remember the log mode with the same password as Log4J?

%d{dd MMM yyyy HH:mm:ss} [%t] %-5p %m%n

The following is the version of Logback. You do not need to check the document. I also see what each segment represents:

%d{dd MMM yyyy HH:mm:ss} [%thread] %-5level %msg%n

The Several Libraries described here are very common. No matter how you develop them, you should be given more or less help. Java Development has never stopped. If you are an old Java programmer, it is time to update your knowledge.

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.