Java life starting from scratch

Let's write Java!

In this article, as the second day of Java Advent Calendar 2018, for programmers who have never used Java, I will introduce a Java development environment that I think it is better to start from this time, and also said that "Java can be used". I would like to make settings so that the compiler and static analysis tools will scold me until I reach the level I think.

This article is not recommended for those who are new to programming and are new to Java. It's for people who can use other programming languages and understand Java somehow.

Also, if you are an experienced person, I think that everyone has a feeling that my environment is better, so please introduce it. In addition, although it is an article at the end of 2018, the basic composition has not changed much in the last few years at my hand. I'm wondering if Facebook Infer or Checker Framework will become common sense ...

install eclipse

Anyway, to write Java, put eclipse, which is also a Japanese version of the package Pleiades All in One.

pleiades.png

Writing Java with a familiar editor, such as Vim or Emacs, is ** unreasonable **. eclim is a little ~~ crazy ~~ There is also an advanced power technique, but since the content is eclipse, it is the next step after being able to write in eclipse. .. Other editors are also useless. I'll tell you the truth, Java is a ** IDE language **. Would you like to write a visual programming language in a text editor? You will edit it in a visual editor. Similarly, the IDE language is for editing in the IDE.

What about IDEs other than eclipse? If you are reading such an article in Japanese, Pleiades All in One is your choice. A common mistake here is to understand English, study English, or think that English is more informative and rush into a field you don't know properly in a language you're not good at.

Java has Java terms. (Although it's usually not very conscious, I think most languages have unique terms or terms specific to the domain to which they are oriented.) If you don't know if you can't understand the function of the IDE because it's in English or because it's in Java, you can't find out. Such words often give up even quickly to be understood, and as a result, they are useful features but never used. If you don't have someone to tell you exactly, the interface should be native, at least until you get the hang of it.

Of course, IntelliJ (even CE) can also be Japaneseized using Pleiades, but Japaneseization is generally not very common and is for advanced users. is. There are also NetBeans and VS Code, but you can forget about them for now. It's not a matter of good or bad, it's simply not suitable for this purpose.

Well, Pleia des All in One, but there are multiple types. Don't hesitate to download the Full Edition of ** for Java ** again.

pleiades-java.png

Did you choose Ultimate because you are also interested in other languages? It's a failure. eclise is a profound IDE. Ultimate is what makes it even more profound. I don't know how to switch the language environment, so it's Sekiyama.

Did you choose Platform because you want to set it yourself? Grass on failure. I'm not used to eclipse, but I can't set it.

If you already have eclipse for another language installed, don't hesitate to drop the latest for Java.

Eclipse is an IDE with a lot of plugins, but the fact that it has a lot of plugins and the fact that multiple plugins work together and work are completely different stories. Many of the causes of failure in eclipse are that you put a plugin in everything and the plugins are inconsistent, or some plugin gives a fatal error and eclipse does not start up. is.

You should use a validated stable environment until you understand that.

Set up eclipse

After the installation is complete, perform the initial setup.

Check before booting

~~ No human rights ~~ It's unfortunate to launch eclipse on a machine with low memory, but it's a rare story. I would like to exclude individual tuning etc. from this article, but if you are concerned about 32-bit version or memory, it is a good idea to add the following two lines to the end of ʻeclipse.ini`.

eclipse.ini(Excerpt)


-Xms1G
-Xmx1G

Set the compiler

The great thing (and rarely the pitfall) of eclipse's Java environment is that it comes with a Java compiler for eclipse called ** Eclipse Compiler for Java (ecj) **. IntelliJ, which uses only the JDK, can do something similar, so it's not because there is ecj now, but anyway, ecj can set its own warning and realize static analysis function by itself. doing. However, it is sweet by default, so change it to the full power setting. Although I will do my best, let's be warned.

Open the settings. 設定メニュー

コンパイラーのエラー/警告

Let's look at the settings individually for each item.

Code style

codestyle.png

Although it is called a style, it is generally a general rule, so I usually make it a ** warning . " Non-externalized string " is an option that is not relevant to many and can be ignored. If the style is divided, would it be " access to inaccessible members of the enclosing type " or " parameter assignment **"? The former is when you create an in-class class, so you probably don't have to worry about it for a while. The latter is an option that does not allow assignment to arguments.

Potential programming problems

潜在的なプログラミングの問題

"* Boxing and unboxing conversion " " enum incomplete'switch'case " "'default'case missing'switch' " " serializable class without serialVersionUID *" is at best * * Information ** is fine, but everything else is useful, so I'll make it a ** warning **.

Name shadowing and conflict

shadow.png

This is to prevent mistakes because they are more likely to be mistaken due to variable name covering. Actually, it is rare that reference support makes mistakes on the IDE, but let's make it ** warning **.

Null analysis

Null分析

"** Enable annotation-based null analysis **" is difficult to use, so it's a good idea to turn it off. Others are of course the best.

Set the formatter

I think you like the formatter settings themselves, but the default settings don't do anything for Javadoc-style comments, and the comments usually get dirty, so let's set that alone.

formatter.png

javadoc-format.png

"** Enable Javadoc comment format " " Enable block comment format " " Enable header comment format **" is important is.

Set save action

Personally, I think the best feature of eclipse is this save action. When you save the file, it not only formats it, but also cleans up the code. If the project does not have strict rules, it should be noted that when you edit the source code written by another person a little, it will be automatically changed to the unrelated part, but always enable it for your own writing Should be left.

保存アクション

You should use all the functions. Let's set additional actions as well.

There may be differences in preferences, coding standards, and development styles here, but I will explain my settings for the time being. If you make the save action too strict, the code you are making will be cleaned, so set it to a good feeling.

Code style

コードスタイル

Code organization

コード編成

Let's enable the formatter for the time being. Sometimes it's easier to sort the members in ABC order, but it's a good idea to avoid sorting them while editing, as it can be quite confusing.

Member access

member.png

Missing code

欠落コード I think it's the most useful in any scene, but it's enabled by default.

Unnecessary code

不要なコード

Set up cleanup

Cleanup is like cutting out a separate save action. You can do almost the same thing as the save action, so for example, turn on features that you normally don't want to work with, such as "remove unused local variables", and clean up when the implementation is complete. You can use it properly by looking at it.

cleanup.png

Try to make

Now that the settings are complete, let's start making.

use gradle

Today's major languages have software repositories of libraries and tools that can be installed in one shot with dependencies with package management tools like npm and pip. Of course it is also in Java. In Java, maven is the equivalent. It's equivalent, but as a promise of old Java projects, gradle with groovy config files is preferred these days because config files are XML. gradle is a build tool that can use maven repository for dependency resolution.

Pleiades All in One already includes the gradle plugin ** buildship **, so you can start using it right away. If you are going to make it in Java from now on, you should make it as a gradle project anyway. Although it is a build tool, it does not necessarily have to be able to be built with gradle, and it is extremely useful simply because it functions as a library installer.

新しいgradleプロジェクト

Once created, open the project's build.gradle. The biggest difference between maven repositories and npm repositories and pip repositories is that there are multiple well-known repositories, and it is common to have your own repositories or set up repositories on a project-by-project basis. There are two very famous public repositories, maven central and jcenter. It's a hassle, so it's a good idea to set both. Some libraries are usually on either side.

build.gradle


apply plugin: 'java-library'

repositories {
    jcenter()
    mavenCentral()
}

dependencies {
    //Dependent libraries are specified as follows:
    //The value generated by buildship by default, but is just a sample.
    api 'org.apache.commons:commons-math3:3.6.1'
    implementation 'com.google.guava:guava:23.0'
    testImplementation 'junit:junit:4.12'
}

maven artifact

The name of the library (called ** artifact **) in the maven repository consists of the group ID and the artifact ID. For example, a library called guava that is commonly used in Java becomes the artifact ID guava for group ID com.google.guava. Roughly speaking, you can think of it as a library name that is generally longer than in other languages.

Use completion

In IDEs like eclipse, completion is of utmost importance. The completion function can not only expand the variable name, but also specify the type and write an import statement, or generate the main method. (Usually import is not handwritten)

Date.png

main generation main

use lombok

What changed the most Java source code between when Java 6 came out 10 years ago and now is lombok rather than the language specification version upgrade. Is a big thing that has become commonplace. In the old days, Java-like Getter / Setter and toString () / hashCode () / ʻequals ()` were generated by eclipse and tools. Now, if you write annotations and embed lombok into the compiler at compile time, lombok will secretly generate it at compile time. You can keep your source code clean because you don't have to deal with the generated code by humans. Since it is built into Pleiades All in One from the beginning, you can use it immediately by incorporating the library into the dependency so that it can be used in the project.

build.gradle


apply plugin: 'java-library'

repositories {
    jcenter()
    mavenCentral()
}

dependencies {
    compileOnly 'org.projectlombok:lombok:1.18.+'
}

When there is no lombok

Example.java


public class Example {
  private String familyName;
  private String lastName;

  public String getFamilyName() {
    return familyName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setFamilyName(String familyName) {
    this.familyName = familyName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public boolean equals(Object o) {
    ...
  }

  public int hashCode() {
    ...
  }

  public String toString() {
    ...
  }
}

When there is lombok

Example.java


@Data
public class Example {
  private String familyName;
  private String lastName;
}

These will be the same code.

It looks like black magic, but it's a legitimate extension of the Java compiler spec, and it's just a code generator, so there's no penalty at runtime. (In most cases you don't need lombok at runtime)

See Lombok features for more information. It's easy to see what's happening by comparing the code before and after generation.

Use SpotBugs

SpotBugs, formerly known as FindBugs, is Java's standard static analysis tool. (To be exact, it was forked because FindBugs ate it) SpotBugs can detect null checks, resource leaks, API error check mistakes, and more. Since SpotBugs / FindBugs detects almost only general theory in Java, it is in a position to be used as standard among many Java static analysis tools, and it is about the position of eslint of JavaScript and PEP8 (checker) of Python. ..

This is also included in Pleiades All in One, so you can use it at the timing when you write the program to some extent.

UseSpotBugs.png

Use JSR305

There is (not) Java with you, and Java with the maxim, but something that can be null will eventually be null. Both ecj and SpotBugs allow you to do simple null checks, but both are based on simple parsing and don't capture the intent or complex code of the program (it's getting more sophisticated). By using a library called JSR305 that conforms to the specification that has failed to become the Java standard, it is possible to indicate with annotations whether or not a variable may be null. Of course, it is just an annotation, so it will not cause a compilation error. (Ecj can make errors, but I don't recommend it.) However, SpotBugs supports JSR305, so you can mix intent with null checking. It also forces @CheckReturnValue to use a return value, @Immutable to indicate immutability, @NotThreadSafe to indicate thread unsafe, @ WillClose to indicate that the resource is closed, etc. In addition to the null check, useful annotations are provided.

build.gradle


apply plugin: 'java-library'

repositories {
    jcenter()
    mavenCentral()
}

dependencies {
    compile 'com.google.code.findbugs:jsr305:3.0.+'
    //You may also need the spotbus annotation as you get used to it
    // compile 'com.github.spotbugs:spotbugs-annotations:3.1.+'
    compileOnly 'org.projectlombok:lombok:1.18.+'
}

When there is JSR305


//Method calls that don't use a return value don't make sense
@CheckReturnValue
public String getLastName() { ... }
//It can be null, so you need to check the return value
@CheckForNull
public String getFamilyName() { ... }
...

public void test() {
  getLastName(); //SpotBugs gets angry because I don't use the return value
  String f = getFamilyName();
  String t = f.substr(0); //SpotBugs gets angry because I haven't checked for null
}

Set stronger

As you get used to it (or the code is small), SpotBugs doesn't say much. In such a case, set it so that even minor problems can be reported in all categories.

SpotBugs

By the way, "** Minimum rank to report **" is the setting at the right end of the bar, where 20 is the most reported. Please note that it is not the opposite.

Also, SpotBugs can increase the detection function with a plugin (for example, fb-contrib), so you may consider it.

Other topics

You should now be able to set up your environment and start development. I won't cover the specific implementation using the framework in this article, but I will briefly introduce what you need to know.

Javadoc I think you're writing xxxDoc in any language these days, but don't forget Javadoc. In eclipse, if you type / ** in front of the method and press ʻenter`, it will generate a template that looks good. If you leave the rest to code completion, you should be able to write the minimum Javadoc as it is.

public class Library {
	/** //← It will be generated if you enter only here
	 * 
	 * @param t
	 * @return
	 */
    public boolean someLibraryMethod(int t) {
        return true;
    }
}

Let's complete the code to see what kind of tags there are. javadoc-comp.png

Coding convention

The standard format in Java is Google Java Style Guide (head family) | [(unofficial Japanese translation)](except for the handling of tabs / indents. I think it's a good idea to read https://kazurof.github.io/GoogleJavaStyle-ja/) exactly.

Reflection and annotation

I think it's more like black magic than lombok, but reflection is the basic technology used in frameworks and libraries here and there. Most modern languages can do it, so it should be accepted easily, but in Java, there are some troublesome situations where the reflection implementation level differs depending on the library.

Annotations are increasingly used to support reflection. So don't be fooled by the annotations themselves, which may look like complex code and be wary, as they are just labels.

Example.java


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;

@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class Example {
  private String familyName;
  private String lastName;

  public static void main(final String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Example e = new Example();
    e.familyName = "Surname";
    e.lastName = "Name";
    System.out.println(mapper.writeValueAsString(values));
    // {"familyName":"Surname","lastName":"Name"}
  }
}

Use Jackson

Jackson is a de facto standard library for working with JSON in Java, which is a great way to understand reflection.

Try using it with jackson-annotations. https://github.com/FasterXML/jackson-annotations

Today's Java

Writing Java in Notepad at university and trauma is a story of Java, but it is also a promise that the Java learned there will be in the Java 2 era.

Even if you don't know much about Java, if you do a little research, you may know that there were relatively big changes in Java 8. The Java 8 was released in March 2014, more than four years ago. Of course, it's only four years from Java's history of more than 22 years, but if you're starting now, you should at least start here. Effective Java is now Java 9 compliant.

Due to Java's history, unfortunately, Java applets and surviving (and couldn't be updated) people and information in i-mode are often found in places like online programming courses and schools. That may be fine in terms of learning programming, but it is harmful in terms of learning Java.

Old code

If you see code like the following, close it.

The person who writes this kind of code is Java SE 1.5 or earlier, so it's no longer an ancient person. The landscape is quite different between Java these days and Java today. It's better to forget about Java knowledge at this time.

Be a little careful with code like this:

Such code could be in the Java 6/7 era. It shouldn't be totally useless, but you can't really expect to take advantage of lambda expressions.

JVM The difficulty of getting started with Java by non-living people in the JVM ecosystem, or the height of the Java threshold, is a problem due to lack of knowledge of the JVM rather than Java, and the knowledge of modern process virtual machines rather than JVM. I think that's what it means. When talking about the JVM, it is often said that it is natural to know about generational GC. Depending on the language you have used so far, what is GC in the first place?

Most people just want to use Java and not talk about the JVM separately, but the JVM needs to determine the amount of memory available at boot time, which is a phenomenon that you don't have to shout at stop the world. Occurs, so there are often situations that you need to know.

For the time being, it would be better to follow what function options are available on the command line.

shell


java -XX:+PrintFlagsFinal -version

Effective Java This is a must-read book. Let's read it when you can write Java to some extent. The third edition of the Japanese version was published in October.

https://www.maruzen-publishing.co.jp/item/b303054.html

end

end

Recommended Posts

Java life starting from scratch
Java starting from beginner, override
Java, instance starting from beginner
Java starting from beginner, inheritance
Java, abstract classes starting from beginners
Deep Learning Java from scratch 6.4 Regularization
Java overload constructor starting from beginner
Study Deep Learning from scratch in Java.
Java starting from beginner, variables and types
Java starting from beginner, nested / break / continue
Java, if statement / switch statement starting from beginner
Java starting from beginners, logical operators / conditional operators
Getting Started with Java Starting from 0 Part 1
Deep Learning Java from scratch Chapter 1 Introduction
Deep Learning Java from scratch 6.1 Parameter update
Deep Learning Java from scratch Chapter 2 Perceptron
Deep Learning Java from scratch 6.3 Batch Normalization
Java, for statement / while statement starting from beginner
Scala starting from scratch (environment construction mac)
Deep Learning from scratch Java Chapter 4 Neural network learning
Java starting from beginner, class declaration / object generation
[Deep Learning from scratch] in Java 3. Neural network
For Java engineers starting Kotlin from now on
Deep Learning Java from scratch Chapter 3 Neural networks
Call Java from JRuby
Changes from Java 8 to Java 11
Sum from Java_1 to 100
Eval Java source from Java
Picture-in-picture starting from iOS14
From Java to Ruby !!
Build VS Code + WSL + Java + Gradle environment from scratch
[Note] Create a java environment from scratch with docker
Deep Learning Java from scratch 6.2 Initial values of weights
[Java] Platforms to choose from for Java development starting now (2020)
Deep Learning Java from scratch Chapter 5 Error back propagation method
Creating ElasticSearch index from Java
New features from Java7 to Java8
Connect from Java to PostgreSQL
Using Docker from Java Gradle
From Ineffective Java to Effective Java
JavaScript as seen from Java
Execute non-Java instructions from Java
Call Kotlin's sealed class from Java
Get country from IP address (Java)
Run node.js from android java (processing)
Run a batch file from Java
[Java] Remove whitespace from character strings
Akka hands-on preparation procedure from Java
Access Teradata from a Java application
Use Chrome Headless from Selenium / Java
Java to be involved from today
Work with Google Sheets from Java
Java, interface to start from beginner
[Java] Spring DI ④ --Life cycle management
[Java] Proxy setting method when starting Java
The road from JavaScript to Java
Reintroducing Java 8 available from Android Studio 2.4
Call TensorFlow Java API from Scala
[Java] Conversion from array to List
Spring Boot starting from zero Part 2
Sample code using Minio from Java