Why Java: A Python programmer tells you

Source: Internet
Author: User
Tags maven central

This article is written specifically for programmers, and the general reader is careful to enter. Original Kevin Sookocheff Translator: Celia Zhen, the original text click the end of the link.

Every time I tell someone that I've been working with Java, everyone's reaction is:

"Nani! Java? Why is Java? ”

To tell the truth, I was the same reaction when I first started. But thanks to Java's type-safety, execution performance and rock-solid tools, I gradually began to appreciate Java. At the same time, I have noticed that Java is not the same now-it has improved steadily over the past 10 years.

Why is Java?

Assuming that the idea of using Java every day has not made you disgusting to eat, I hereby reiterate that Java is not what you know "defeating". When Python, Ruby, and JavaScript shine in the "Dynamic Type Language Revolution" ™ (my own noun), Java has quietly borrowed from the many attractive features of dynamic and functional languages, with Preserve the efforts of the sages who made Java and the JVM advance into the first-class development environment. Java is still the world's most popular programming language with about 9 million Java Siege Lions ' grassroots communities. We can't erase all of its history and development work just because Java syntax is a little cumbersome. But popularity is not the same as right. Let's take a look at what makes Java so amazing.

Java Virtual machine (JVM)

The Java Virtual machine (JVM) has been in existence for 20 years. During this time, it was deployed on thousands of systems, with numerous bug fixes and performance improvements. The advantages of the JVM are as follows. First, the JVM perfectly supports logging and monitoring, which allows you to easily monitor performance metrics that are small to a single thread. The JVM has one of the world's most optimized garbage collector, and you can choose the garbage collection algorithm flexibly based on factors such as optimized throughput. Finally, the Java-committed "write once, run anywhere" has finally been implemented-you can easily deploy a Java application on any architecture (everyone acknowledges that the applet has never been). Why would smart people with new languages like Scala and Clojure choose the JVM as their execution environment? -Because the JVM provides an unmatched distribution environment for your code. It is unreasonable to abandon a rock-solid tool like a JVM.

Support for libraries

If you need to do something, you probably already have a very handy and tested Java library waiting for you. Most of the Java libraries are mature and used for actual production development. Google, Amazon, LinkedIn, Twitter and many Apache projects are heavily reliant on Java. If you use Java, you can refer to these libraries and companies to learn from the work of great programmers pioneers.

Type safety

Java type System, although sometimes cumbersome, but this allows you to write "good" code. No more running debugging, it allows you to rely on the compiler instead of unit tests--unit tests are only useful if you know where the bug is. Type safety also makes it easy to refactor your code. Java also supports one of the biggest criticisms of the Paradigm--go language. Furthermore, library I, such as guava, standardizes the way to create type-safe APIs with minimal boilerplate and overhead. The improvements to the Java compiler also mean that you can minimize the boilerplate code required for the paradigm while enjoying type safety.

Concurrency of

The following tweet summarizes the parallel state of most dynamic languages:

Most Js/python/ruby apps ... pic.twitter.com/hkdkjdxpfh

-reuben Bond (@reubenbond)

Java has first-class support for multithreading and parallelism. For Java 1.7, the immutable data structure allows you to easily share data between threads. The Akka Library further provides Erlang-type actors to write concurrent and distributed programs. I'm not saying that Java has better parallel support than go, but the ability to manage a single thread provides asynchronous performance for Java applications, and Python doesn't.

Programming with the latest Java

Now that your mood may have turned from nausea to curiosity, how do we write Java in 2015? Where do you start? First, let's review some of the core language concepts emerging in Java 7 and Java 8.

Iteration

First, let's look at iterations together. The following is a for loop in Java 8:

list<string> names = new linkedlist<> ();  compiler determines type of linkedlist//... add some names to the Collectionnames.foreach (name-a System.out.printl N (name));

Or is it a greatly simplified for keyword?

for (String name:names) System.out.println (name);

These 2 loop structures are much more concise than the For loop you see in your usual way.

Lambda functions

The first for loop mentioned above introduces the new concept of a lambda function. The LAMDA function, which is written as->, is a major reform of the Java language and introduces some concepts from functional programming.

Let's look at a few examples of lambda functions in Java.

LAMBDA runnablerunnable r2 = (), System.out.println ("Hello World two!"); /Lambda Sortingcollections.sort (personlist, (person P1, person p2), P1.getsurname (). CompareTo (P2.getsurname ()))/ /Lambda Listenertestbutton.addactionlistener (E-SYSTEM.OUT.PRINTLN ("Click Detected by Lambda Listener");

There is no way to expand the lambda function in detail this topic--http://www.drdobbs.com/jvm/lambda-expressions-in-java-8/240166764 article provides a good starting point to learn more about lambda functions.

Flow

Java 8 introduces the concept of stream, which gives Java a lot of modern functional language features. A stream is a mechanism for delaying execution of a series of transformations on a collection. For example, let's count the names that begin with ' A '. The first way to think about this is definitely like this:

list<string> names = new linkedlist<> ();//... add some names to the collectionlong count = 0;for (String name : Names)  {if (Name.startswith ("A")) ++count;}

If you use a stream, the above can be simplified to first convert the collection into a stream, and then use the function:

list<string> names = new linkedlist<> ();//... add some names to the collectionlong count = Names.stream (). fil ter (Name, Name.startswith ("A")). Count ();

Java also supports parallel processing of streams with Parallelstream (). Parallel streams allow pipelining to execute concurrently on separate threads, which not only improves syntax, but also improves performance. In most cases, you can simply replace stream () with Parallelstream () to implement parallelism.

Try-with-resources structure

Before Java 6, opening a file and then reading the content needs to be done via try/finally:

static string Readfirstlinefromfilewithfinallyblock (string path) throws IOException {BufferedReader br = new BufferedReader (new FileReader), try {return br.readline (),} finally {if (BR! = null) Br.close ();}}

However, both ReadLine and close may throw exceptions. In this case, the exception thrown by ReadLine is ignored, and we do not actually know that ReadLine execution failed.

Java 7 introduces the try-with-resources structure to overcome this flaw:

static string Readfirstlinefromfile (string path) throws IOException {try (bufferedreader br =new bufferedreader (New FileR Eader (path)) {return br.readline ();}}

In the above example, BufferedReader automatically closes the file stream regardless of the failure situation. You can open multiple resources by using a single try statement in a comma-delimited manner.

Multiple catch

In the past, Java only allowed one catch code block to correspond to an exception, which resulted in the following code redundancy:

catch (IOException ex) {Logger.log (ex); throw Ex;catch (SQLException ex) {Logger.log (ex); throw ex;}

Starting in Java 7, you can capture multiple exceptions within a block of code, reducing Code redundancy:

catch (ioexception| SQLException ex) {Logger.log (ex); throw ex;}
numeric literal constants (Numeric literals)

Numeric literal constants can be underlined as a new feature of the Java language. This allows you to use _ as a visual delimiter for large numbers. The following example is self-explanatory:

int thousand = 1_000;int million  = 1_000_000;
Using Java

Once you see how modern Java syntax simplifies and extends old Java, you might be tempted to get ready for Java. I've tidied up third-party tools and libraries that can be used to help you get started.

Maven

MAVEN is a Java build system that attaches more importance to specification than configuration. MAVEN defines the structure of the application and provides a number of built-in functions, such as running tests, packaging applications, and deploying your library. Using MAVEN can significantly reduce the cognitive overhead of managing Java projects. Maven Central is a pypi in the Java world, providing a one-stop service for published Java libraries.

Core functions

Google's Guava library provides the core functions used in Google Java development. This includes common functions that apply to collections, caches, underlying data types, concurrency, string processing work, I/O, and so on. Guava provides a great case study of how to design a good Java API, providing the most effective examples of best practices recommended in Java, a good case in point, effective most of the recommended best practices in Java are reflected in guava. Guava was used for Google product development and carried out more than 286,000 unit tests, which have withstood the test of actual combat testing.

Date/Time Functions

Joda-time has become the Java de facto standard date/time library of functions. In fact, Java 8 uses the Joda-time specification almost in a word. Since then, we recommend using the Date/Time function in Java.time instead of Joda-time. However, if you need to use a version prior to Java 8, Joda-time provides an unmatched API.

Distributed Systems

Akka provides an abstraction layer of an Actor model like the Erlang type to write distributed systems. Akka can handle many different kinds of failures, providing a higher level of abstraction for writing reliable distributed systems.

Web application

Need to write a fully functional Web application in Java? Don't worry, there's a play framework that covers you. Play is based on Akka's non-blocking I/O, providing an extensible asynchronous framework for writing Web applications. If you want to use a frame that is not so cutting-edge but is widely used in the product, try jetty.

Unit Test

JUnit is still the standard for writing unit tests. In recent years, JUnit's match has been extended to allow you to collaborate on assertions. For example, you can easily assert whether a linked list contains a particular value.

Simulation Framework (Mocking framework)

Mockito is the standard simulation library for Java. It provides all the features you can think of and the simulation libraries that are important for writing tests.

However, the shortage is ...

So far, I've been talking to Java, but in some ways it sucks.

It's still java!.

Java's history remains unavoidable, and Java is still backwards compatible with its earliest versions, meaning that the worst parts of the language and standard libraries still exist. The fact that guava is designed to make the Java language more likeable proves that Java and APIs are inconsistent, confusing, and sometimes even completely wrong.

Json

Java lacks an object literal syntax (such as a Python dictionary literal syntax) mapped to JSON. Because of this, mapping from Java objects to JSON sometimes requires complex object instantiation and mapping, and vice versa. There are a variety of JSON libraries currently competing in this field, andJackson is the most popular, but Jackson's documentation needs to be perfected.

Analog (Mocking)

Mockito solves many of the pain points in testing Java code, but from a flexible transition like the Python language to the strict Java language, you need to design your class more carefully for simulation.

Repl

One of the things I like about Python is that it can quickly implement a read ﹣ evaluation ﹣ output loop (Read-eval-print loop) to quickly evaluate new ideas or test assumptions. Even though there's always a voice. It is not currently supported to add read ﹣ evaluation ﹣ output loops to a standard Java library.

A cumbersome grammar

While the progress of the Java compiler means that explicit type signatures are no longer needed-especially for generics-Java is still much more redundant than Python. Starting and running a project requires more boilerplate and overhead-often that means more work.

Conclusion

Java has a long and legendary history in which there are good and bad. If you haven't worked with Java for years, maybe it's a good chance to try it again. As long as it is not done as follows:

Why Java: A Python programmer tells you

Related Article

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.