How to write modern Java. Immutable Java, consider Null safety.

Java has also been adapted with a mechanism that allows you to write some modern programming by adding stream processing, lambda, optional types, etc. in Java 8. But are programmers writing in Java pervading a modern implementation culture?

This time, I will write about "Immutable Programming" and "Handling of null" as a modern implementation method.

Premise

It is intended when implementing a Web application server. Of course, there are many parts that are applied even in the native implementation. I will explain how to write Java 8.

What is Immutable Programming?

The very simple explanation is that you don't reassign to a variable. It's like programming with all finals.

Can people who haven't done it yet do that? You may feel that, in most cases web applications do not need to be reassigned. Because the HTTP processing of the browser is 1 request 1 response, You can think of it as converting (Request)-> Response. Also, the place to manage the state is limited to session and db. In other words, I think that most of them can be described by conversion processing with a map of stream processing.

Recently, there is a trend to make the infrastructure Immutable, and Immutable Infrastructure is also attracting attention. It can be considered as evidence that the benefits of being Immutable are considered to be great.

Benefits of Immutable Programming

The value of the object does not change once it is created. In other words, what you receive as a method argument etc. will not be changed even if you go through other processing, so it will be easier to debug and the code will look better.

This is because variables that you do not know somewhere, such as the one passed after calling the method and the contents of the instance, are not rewritten, and the only new change is the variable received as the return value.

Disadvantages of Immutable Programming

It can be said that the performance is poor and the memory efficiency is reduced because the work of recreating the entire instance to change one variable in the object of Class. However, considering the current server specs, the server specs are more than someone can take the time to investigate and fix bugs, or write the human cost of understanding and working with the code in a wide scope when adding functions. In most cases, the final cost can be reduced by improving.

If performance becomes an issue, it is more realistic to fix only that part. Even when changing to logic that takes performance into consideration, the scope is well defined, so it will often be possible to fix it neatly.

Way of thinking of practice

Basically, the conversion process like stream map will be repeated.

Object creation

The basic idea is to make an object perfectly usable from the moment it is born. The way to do that is to pass all the parameters for the object to exist in the constructor.

Java has a bad specification called JavaBeans (from an Immutable point of view). There is a setter, but it should only be used with libraries that work according to the JavaBeans specification. (Recently, more libraries can be written to private parameters) Setting after doing new creates an unstable object between new and set. Also, the fact that there is a set method does not mean that some method will set what value at what timing. Just having a setter expands the scope of debugging.

Introducing Lombok as a tool and library to promote Immutable Java

If you look for it in Qiia, there are many people who write technical usage, so I will leave the detailed setup and usage to that, and I will write only the case when using it with the idea of Immutable.

val type

It does type inference and makes it a variable that can't be changed automatically! Immutable god!

val x = "hogehoge";

Getter annotation

Automatically add getters for field variables.

class Hoge {
   @Getter
   private Integer id;

   @Getter
   private String name;
}

AllArgsConstructor annotation

Automatically generate a constructor that takes all field variables as arguments.

@AllArgsConstructor
class Hoge {
   private Integer id;
   private String name;
}

RequiredArgsConstructor annotation

Add a static method to instantiate.

@RequiredArgsConstructor(staticName="of")
class Hoge {
   private Integer id;
   private String name;
}

Integer id = 1;
String name = "Jojo";
Hoge obj = Hoge.of(id, name)

Value annotation

You can get the effect of adding @Getter and @AllArgsConstructor annotations together.

Conclusion

It is OK if you use all the values that make it non-assignable.

About the handling of Null

From here, the story changes completely and is treated as null. I think that programming is becoming commonplace in modern programming languages, clearly expressing the existence and nonexistence of values.

It is explained in detail in this article, so if you want to know more, please refer to it.

Null insecure languages are no longer legacy languages

Benefits of expressing in code that there is a Null case

The best thing I can think of is that you can clearly express in your code whether the variable always has a value or no value (null case).

Optional was introduced from Java 8. As a result, the case that always has a value is the same type. If there is a case where there is no value, it can be expressed as a state where the value is contained in Optional.

In the column of the DB table, non null can be expressed as it is, and if null is possible, it can be expressed in the source code with Optional [column type]. And you can force the processing of cases where there is no value.

If you master this programming, you will almost never get a NullPointerException.

However, unfortunately, I feel that there are not enough functions to write smartly.

JDK9 Optional

Methods will be added for flexibility. I'm waiting personally.

ifPresentOrElse method

With the current Optional, there is only a way to separate the process of checking safety and the process of extracting.

Optional o = something;

if(o.isPresent()) {
  //Processing when a value is entered
  Hoge hoge = o.get(); // <- o.get()Is not safe! !! !!
} else {
 //Processing when there is no value
}

Personally, I would like the Optional get method to be basically unusable. Why is it wrapped in Optional when I don't need to write an orElse method? Obviously the declarations and specifications are wrong.

But! I can't write smartly with Java 8. .. sad.

However! In Java9 you can write like this!

Optional o = something;

o.ifPresentOrElse(
  hoge  ->{
     //Processing when there is a value
     print("this is " + hoge)
  },
    () ->{
     //Processing when there is no value
     print("none")
  }
);

stream method

Only when there is a value of Optional, the value is passed to the subsequent processing such as map! This is sure to be able to describe the process in a smart way!

For those of you who can't wait for Java 9.

After studying Scala, the idea of functional programming and Immutable Programming are pervasive, so you may be able to write better code.

In any language, I want to be good at programming for practical code that is stylish and artistic, not just working!

Finally

I'd love to know more about modern coding, so if anyone knows a better idea, I'd love to hear from you.

Recommended Posts

How to write modern Java. Immutable Java, consider Null safety.
How to write java comments
Studying Java # 6 (How to write blocks)
How to write Java variable declaration
[Introduction to Java] How to write a Java program
[Java] How to output and write files!
Kotlin's Null safety to send to Java developers
[Java] How to test for null with JUnit
Java Development Basics ~ How to Write Programs * Exercise 1 ~
How to hide null fields in response in Java
[Java] Memo on how to write the source
How to write Java String # getBytes in Kotlin?
How to write Rails
How to write dockerfile
How to write docker-compose
How to write migrationfile
How to write Scala from the perspective of Java
[Java] Types of comments and how to write them
java: How to write a generic type list [Note]
How to lower java version
[Java] How to use Map
How to write good code
Java --How to make JTable
How to use java Optional
Bit Tetris (how to write)
How to minimize Java images
[Refactoring] How to write routing
How to use java class
[Java] How to display Wingdings
Great poor (how to write)
[Java] How to use string.format
[Note] How to write Dockerfile/docker-compose.yml
How to use Java Map
How to set Java constants
How to write Junit 5 organized
How to write Rails validation
How to write Rails seed
How to use Java variables
[Ruby] How to write blocks
How to convert Java radix
How to write Rails routing
[Java] How to implement multithreading
[Java] How to use Optional ①
How to initialize Java array
Comparison of how to write Callback function (Java, JavaScript, Ruby)
How to write and notes when migrating from VB to JAVA
[Rails] How to write in Japanese
[Java] How to update Java on Windows
How to make a Java container
How to disassemble Java class files
How to use Java HttpClient (Post)
[Java] How to use join method
How to learn JAVA in 7 days
Baseball ball count (how to write)
[Processing × Java] How to use variables
[Java] How to create a folder
How to decompile java class files
[Java] How to use LinkedHashMap class
Rails on Tiles (how to write)
[Rails] How to write exception handling?
[JavaFX] [Java8] How to use GridPane