How to deal with the type that I thought about writing a Java program for 2 years

How to deal with the type I think in Java

We have summarized the contents of LT announced in the past at weekend engineer.

It's been two years since I started programming, so I've summarized what I usually pay attention to when programming. I may update it from time to time.

Preface

Conclusion

If used in a mold, you lose. It can be said that the power of statically typed languages can be utilized only by mastering the power of typing.

table of contents

What is static typing?

Static typing means that in a program written in a programming language, the types of variables, subroutine arguments, return values, etc. are pre-determined before the program is executed, such as at compile time. It is the nature of the type system.

Wikipedia | Static TypingThan

Dynamically typed languages such as JavaScript check the type when you run the program.

const str = 10;
const length = (str) => {
  return str.length;
}
length(str);
// =>undefined is returned.

In comparison, statically typed languages check types before they run. At the code level, it is different from dynamically typed languages in that it declares the types of variables, function parameters, and return values.


Integer str = 10;
Integer length(String str) {
  return str.length();
}
System.out.println(length(str));
// =>At compile time,In other words, an error occurs before execution.

Recently, editors sometimes give warnings even in dynamically typed languages such as JavaScript, but I think that is largely due to static parsing technology.

How to deal with static typing

There are disadvantages to static typing. It is troublesome to specify the variable type in advance. It is also troublesome to cast (convert the variable type).

I know everything. I did too. But I recently realized that it indicates that ** I'm used for typing **. Statically typed languages make typing more aggressive. Define, ** I realize that the benefits come only when I use types **.

Below, I will write specifically how to use the type.

Give meaning to the data.

You can express more in your program by using your own defined types than by using primitive types such as String and ʻInt`.

When using primitive types as they are

String phoneNumber = "000-0000-0000";

When using a type defined by yourself

PhoneNumber phoneNumber = new PhoneNumber("000-0000-0000");

If you just use the String type, you only know that the variable is a string. From the variable of type PhoneNumber as in the second example, you can predict what kind of string is stored, and you can also imagine what kind of method can be called. In this case, I don't think I can call anything, but lol

Do secure programming based on contracts.

The details of contract programming are more detailed in the following articles.

What I want to say here is that we can guarantee that variables are "not just strings, but strings in the form of telephone numbers, so they can behave without raising exceptions for certain instructions." It means that there are merits.

In the following class, when creating an instance of the PhoneNumber class, it checks whether it is a "phone number format string with a hyphen" and raises an exception. Paradoxically, a variable of type PhoneNumber always " The type can guarantee that the data has a "phone number format string with a hyphen".

/**
 *Class that represents a phone number.
 * String
 */
class PhoneNumber {
  private static final Pattern pattern = 
      Pattern.compile("^0\\d{2,3}-\\d{1,4}-\\d{4}$");
  private final String value;

  /**
   *Returns an instance of a new phone number type based on the hyphenated phone number specified in the argument.
   * @param value phone number
   * @return Phone number type instance
   * @throws IllegalArgumentException If the argument is something other than a hyphenated phone number
   */
  PhoneNumber(String value){
    Objects.requireNonNull(value);
    if (!value.matches(pattern)) {
      throw new IllegalArgumentException();
    }
    this.value = value;
  }

  String getValue() {
    return this.value;
  }
}

Give restrictions and meaning to behavior

Various methods and functions are defined for types provided by languages such as the String type. Do you really need all of them?

Is it appropriate to be able to get the character code or reverse the order of the strings for the phone number? Dare to define the type for the phone number by limiting the operations on the variables and preventing mistakes. It is also for.

On the contrary, it may increase the behavior. It is assumed that you get the local code of the telephone number. When substituting a telephone number for a String type variable and using it, the program will be as follows.

String phoneNumber = "000-0000-0000";
String cityCode = phoneNumber.split("-")[1];

If you define the behavior of returning the local code to the PhoneNumber type, the program will be as follows.

PhoneNumber phoneNumber = new PhoneNumber("000-0000-0000");
String cityCode = phoneNumber.getCityCode();


class PhoneNumber {
  private final String value;
  //Abbreviation

  String getCityCode() {
    return value.split("-")[1];
  }
}

Digression

I've written the source code quite redundantly so far, but in reality, the code is coded using the annotations of Lombok and Bean Validation. Can be simplified.

/**
 *Class that represents a phone number.
 * String
 */
@Value
class PhoneNumber {
  @NotNull
  @Pattern(regexp="^0\\d{2,3}-\\d{1,4}-\\d{4}$");
  private final String value;
}

at the end

So far I've written about micro units (phone numbers), but I don't think it's necessary to make molds in these units. Making molds in units that require integrity is a big advantage. In this article, all the input values from the screen are defined as a type and used as an argument of the calculation logic. Restrictions and guarantees by type and constructor I hope I can continue to utilize this method.

Recommended Posts

How to deal with the type that I thought about writing a Java program for 2 years
I tried to make a program that searches for the target class from the process that is overloaded with Java
I want to return a type different from the input element with Java8 StreamAPI reduce ()
How to reduce the load on the program even a little when combining characters with JAVA
I made a program in Java that solves the traveling salesman problem with a genetic algorithm
A story that I struggled to challenge a competition professional with Java
How to check for the contents of a java fixed-length string
About the procedure for java to work
[Introduction to Java] How to write a Java program
How to interact with a server that does not crash the app
Declare a method that has a Java return value with the return value data type
[Java] How to turn a two-dimensional array with an extended for statement
I thought about the best way to create a ValueObject in Ruby
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
[Java] How to test for null with JUnit
[Java] How to use Thread.sleep to pause the program
[Java] (for MacOS) How to set the classpath
I tried to break a block with java (1)
Until you run a Java program with the AWS SDK local to Windows
[Ruby] I want to make a program that displays today's day of the week!
(Java) How to implement equals () for a class with value elements added by inheritance
Diet program with preprocessor (how to deal with i-appli size)
java: How to write a generic type list [Note]
A memo about the types of Java O/R mappers and how to select them
How to deal with No template for interactive request
`bind': Address already in use --bind (2) for 127.0.0.1:3000 (Errno :: EADDRINUSE) How to deal with the error
How to save a file with the specified extension under the directory specified in Java to the list
How to make a mod for Slay the Spire
[Azure] I tried to create a Java application for free ~ Connect with FTP ~ [Beginner]
[Java] How to start a new line with StringBuilder
How to deal with the error yaml.scanner.ScannerError: while scanning for the next token that appeared in Rails environment construction with Docker
I want to create a generic annotation for a type
Java: A story that made me feel uncomfortable when I was taught to compare strings with equals for no reason.
I want to write a loop that references an index with Java 8's Stream API
How to batch initialize arrays in Java that I didn't know when I was a beginner
A memo of the program that allows you to realize that the probability of dice rolling is about 1/6
Implemented a strong API for "I want to display ~~ on the screen" with simple CQRS
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.
How to take a screenshot with the Android Studio emulator
Java program to resize a photo into a square with margins
I tried to modernize a Java EE application with OpenShift.
How to create a lightweight container image for Java apps
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
How to test a private method with RSpec for yourself
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I tried to convert a string to a LocalDate type in Java
How to deal with the error ERROR: While executing gem ... (Gem :: FilePermissionError)
About the behavior when doing a file map with java
Investigated how to call services with Watson SDK for Java
A story about misunderstanding how to use java scanner (memo)
[Java] I thought about the merits and uses of "interface"
It's not a big deal if you understand that I was addicted to receiving emails with Java Mail from Exchange Online
How to deal with the event that Committee :: InvalidRequest occurs in committee during Rspec file upload test
Mechanism for converting to a language that the browser can recognize
I thought about how to use Swift's willSet did Set properly.
I want to create a chat screen for the Swift chat app!
I want to return to the previous screen with kotlin and java!
The story of Collectors.groupingBy that I want to keep for posterity
How to implement a job that uses Java API in JobScheduler
[Ruby 3.0] A memo that I added a type definition to a library I wrote