Things to be aware of when writing code in Java

Preface

I usually write Java, so I will write it assuming Java. While avoiding the DDD-like taste ... (desire)

Use generics, not abbreviations

As for the example, even ʻid is the author who writes ʻidentifier, so it may be a little overkill, but I think that a name that conveys a long meaning is better than a name that does not convey a short meaning. The ideal is short (one word if possible), so I think you should be aware of the naming that is closer to the ideal. (Except for de facto standard names such as ʻi and ʻid)

class Identifier {
  String value;

  Identifier(String value) {
    this.value = value;
  }

  String value() {
    return value;
  }
}

Use your own as much as possible

I feel that the types already in the language, such as String and ʻint`, are not suitable for expressing the concept of my own application. I often see the code that I'm trying to express by naming it with variables, but when a change occurs, even the change with the help of the IDE is a troublesome task such as "forgot to change" or "Typo". It can be. Also, the merit obtained by defining the type independently is that ** a compile error occurs when passing an argument **, ** objects of the same concept are not defined separately in the product code (reuse) * I think it's best to use types as much as possible, such as *.

class Name {
  String value;

  Name(String value) {
    this.value = value;
  }

  String value() {
    return value;
  }
}

If you can't think of a name, give it a strange name on purpose

People often ask me, "Why is PR going up with such a class name?" What we are aiming for is a sense of discomfort that everyone gets caught in. By including the intention to change it later in the name, you can play an active role like a commandment ** with a strange name **. I repeat the experience that if you give it a name like that, it will rot without being looked at, I write as follows. It takes courage to merge into production, but think twice. Can you say that ** that kind of name ** and ** that kind of processing ** are absolutely nothing other than this ** weird name **? Is there a way to find it clearly? If you think about it, there will be less resistance. The most important thing is to give it a good name at the end, which is the responsibility of giving it a ** strange name **.

//Correct the TODO word when it is found
class XxxCharacter {
  String value;

  XxxCharacter(String value) {
    this.value = value;
  }

  String value() {
    return value;
  }
}

I will enumerate the categories with Enum for the time being

** Hobby **. What can be divided while saying that thinking has stopped to some extent is likely to be a branch of business processing, and it is easy to push in the difference in processing depending on the division, so let's define ** for the time being. If they don't match, maybe it wasn't enough to divide them and declare them as their own classes, or think of something else.

enum Gender {
  NONE, MALE, FEMALE
}

Try to have business logic (business rules) in the model

Business logic is often found in the Service layer etc. in the layered. I think the Service layer is the layer that writes ** business **, not the layer that defines ** logic **. If you want to write in the layer that should be, write in the Domain layer. The reason is very simple, because it is a layer packed with business interests. I think of each business interest as business logic (maybe a misunderstanding). By the way, it's good to protect DRY too! I am also happy from the perspective.

class Age {
  int value;

  Age(int value) {
    this.value = value;
  }

  int value() {
    return value;
  }

  boolean isMinor() {
    return value < 20
  }
}

Instantiate with full constructor

I am aware of ** immutable **. We want to limit the responsibilities of the object when it is instantiated and ensure that the internal state does not change **. Not writing Setter is also relevant. If you write code that is easy to tolerate variable **, it has been changed without someone knowing it! It gives the situation **, and the amount of code that must be seen when performing tasks such as "reading, testing, and debugging code" will increase. It's better to have a minimum number of places to see and one place to define the state, right? The same situation is always returned, so I think that the fact that the above does not happen will make you feel very happy as the product grows. If you casually try to define the state of a class with Setter, it might be a good idea to stop. Strictly speaking, some people say that it is better to add the final qualifier to make it even stronger, but it is adjusted according to the level of the team involved in the product. Believing to some extent that ** no one would use it this way **, I rarely write the final modifier, because it's a hassle to write. If you want to know more, check out ** Complete Constructor Pattern **.

class User {
  Identifier identifier;
  Name name;
  Age age;
  XxxCharacter xxxCharacter
  Gender gender;

  User(Identifier identifier, Name name, Age age, XxxCharacter xxxCharacter, Gender gender) {
    this.identifier = identifier;
    this.name = name;
    this.age = age;
    this.xxxCharacter = xxxCharacter;
    this.gender = gender;
  }
}

Instantiate with static method as a precursor

Define the responsibilities of a highly abstract class by naming the instantiation. It is used when you want to create another class with a low level of abstraction, an index of **, or an instance generation by a certain ** category difference **. As a rule, don't forget to make the constructor private. Otherwise, the degree of freedom will increase and a class with an unexpected state will be born. By the way, if you make anything static for no reason, you may be ridiculed as ** static uncle **, so please be careful.

class User {
  Identifier identifier;
  Name name;
  Age age;
  XxxCharacter xxxCharacter
  Gender gender;

  static User ofMale(Identifier identifier, Name name, Age age, XxxCharacter xxxCharacter,) {
    return new User(identifier, name, age, xxxCharacter, Gender.MALE);
  }

  static User ofFemale(Identifier identifier, Name name, Age age, XxxCharacter xxxCharacter,) {
    return new User(identifier, name, age, xxxCharacter, Gender.FEMAL);
  }

  private User(Identifier identifier, Name name, Age age, XxxCharacter xxxCharacter, Gender gender) {
    this.identifier = identifier;
    this.name = name;
    this.age = age;
    this.xxxCharacter = xxxCharacter;
    this.gender = gender;
  }
}

Rough use of loop processing

When looping in Java, I mainly use stream or for. As a miscellaneous index that I use properly, ** when not throwing an exception, when creating an object from a certain object, stream **, ** throwing an exception, when just calling void methods sequentially, etc. Is using for **. I personally like stream because it can be written in a method chain and you can simply see complicated processes such as intermediate operations on objects. On the other hand, for is used when writing code in a block that does not affect the previous processing so much. Also, exceptions are easier to handle than stream.

When I'm about to make a util module, I'll stop

It's a module such as ʻutil, manager, helper` that has too wide a role to become a god. It tends to be often made when "Isn't there a useful tool?" In particular, the latter has many patterns that affect only the one you are using when a change occurs. It was often a problem to be fooled by this as DRY. Think twice, literally ** God **, so it's not something that stupid humans can handle. Rather, the god created by humans is nothing more than a ** synthetic demon beast **. You should be a rushing Buddhahood.

If you try to explain the code in a comment, stay on

It shouldn't be offensive ... it's the one. It's very close to the code and doesn't give more information than the code, it's not worth the mystery format by mystery rules, maybe a lot, but it may not be very good. Comments don't compile, and if you make a mistake, the compiler won't tell you, so it's easy to become a debt. The code works, so if it's wrong, it's pointed out, and with the help of the IDE, I think it's easy to refactor. There are two things I think about when writing a comment: ** Can this comment be good or bad **, ** Can I express it in code before writing this **? I don't think the comments are bad, but the tools can determine the way (afterwards) depending on what you use. I often feel that it is better to face it seriously.

In the test code, write the test method name in Japanese and write a comment etc. in the code

I wrote it right above, but do you write a comment? You might think that. However, unlike the product code, the test code rarely has a fixed flow and is often left to the implementer, so it is a book that mixes personal feelings and logic. If so, I will be more motivated to take responsibility for the explanation. Oh, it doesn't matter, but ** the test is a specification! I often hear **, but is that so? Every day I become suspicious.

Summary

We plan to add more in the future. I'm afraid of Masakari, so I strongly emphasize ** I **. However, I would appreciate your feedback regardless of whether it is good or bad.

Recommended Posts

Things to be aware of when writing code in Java
[Java] Things to be aware of when outputting FizzBuzz
Things to be aware of when using devise's lockable
To be aware of easy-to-read code
[Java Silver] Things to be aware of regarding switch statements
[Java] [Microsoft] Things to be aware of when including the JDBC driver for SQL Server in one jar
Basic rules to be aware of to write easy-to-read code
Summarize the life cycle of Java objects to be aware of in Android development
The story of writing Java in Emacs
5 things new programmers should be aware of
How to find the total number of pages when paging in Java
CORBA seems to be removed in Java SE 11. .. ..
Code to escape a JSON string in Java
There seems to be no else-if in java
[Java] Be aware of short circuits (short-circuit evaluation)
Things to keep in mind when committing to CRuby
Java Servlet should be aware of multithreaded environment
Things to watch out for in Java equals
[Beginner] Points to be aware of after Java exercises / Inheritance / Abstract method [Note 26]
Sample code to get the values of major SQL types in Java + MySQL 8.0
Sample code to convert List to List <String> in Java Stream
Things to keep in mind when adding war to dependency
Things to keep in mind when using if statements
Things to watch out for in future Java development
[Rails] When using ajax, be aware of "CSRF measures".
[Java] When writing the source ... A memorandum of understanding ①
[Java] Things to note about type inference extended in Java 10
When you want to dynamically replace Annotation in Java8
Summary of how to implement default arguments in Java
Differences in code when using the length system in Java
I want to be aware of the contents of variables!
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
Summary of how to use the proxy set in IE when connecting with Java
Code to use when you want to process Json with only standard library in Java
[Technical memo] Things to be careful of from an engineer's point of view when creating a view
I want to randomly generate information when writing test code
Things you often use when doing web development in Java
Things to keep in mind when testing private methods in JUnit
Java in Visual Studio Code
How to dynamically switch JDK when building Java in Gradle
Write Java8-like code in Java8
Implementation of gzip in java
How to derive the last day of the month in Java
I tried to make a client of RESAS-API in Java
Java 14 new features that could be used to write code
[Rails] Where to be careful in the description of validation
Be sure to compare the result of Java compareTo with 0
Implementation of tri-tree in Java
Things to keep in mind when using Sidekiq with Rails
A collection of patterns that you want to be aware of so as not to complicate the code
How to make a key pair of ecdsa in a format that can be read by Java
Is it easy for the user to use when implementing general-purpose functions? Let's be aware of
Text file placed in resources in Java cannot be read when jarted
Summary of ORM "uroboroSQL" that can be used in enterprise Java
Settings to delete unused Java imports when saving with VS Code
Things to note when using Spring AOP in Jersery resource classes
The milliseconds to set in /lib/calendars.properties of Java jre is UTC
Cast an array of Strings to a List of Integers in Java
Determine if the strings to be compared are the same in Java
Avoid character code error in java when using VScode extension RUN-CODE
Sample code to call the Yahoo! Local Search API in Java