20가지 자바 모범 사례
Mar 09 2023
코드 품질을 향상시키는 데 도움이 되는 몇 가지 Java 모범 사례입니다. 1- 가능하면 프리미티브 래퍼보다 프리미티브를 선호합니다.
코드 품질을 향상시키는 데 도움이 되는 몇 가지 Java 모범 사례입니다.
1- 가능하면 프리미티브 래퍼보다 프리미티브를 선호합니다.
Long idNumber;
long idNumber; // long takes less memory than Long
int birthYear;
short birthYear; // better because birth year can not be more than 32767
int personRunningSpeedKmHour;
byte personRunningSpeedKmHour; // better because a person can not have
// more than 127 km/h as speed
public boolean isOdd(int num) {
return (num & 1) != 0;
}
// best way to check the oddity of a number
String name = null; // redundant
int speed = 0; // redundant
boolean isOpen = false; // redundant
String name;
int speed;
boolean isOpen;
// same values in a cleaner way
public int age; // very bad
int age; // bad
private int age; // good
String s1 = new String("AnyString") ; // bad : low instantiation
// The constructor creates a new object, and adds the literal to the heap
String s2 = "AnyString" ; // good: fast instantiation
// This shortcut refers to the item in the String pool
// and creates a new object only if the literal is not in the String pool.
String address = streetNumber +" "+ streetName +" "
+cityName+" "+cityNumber+" "+ countryName; // bad
StringBuilder address = new StringBuilder(streetNumber).append(" ")
.append(streetName).append(" ").append(cityName).append(" ")
.append(cityNumber).append(" ").append(countryName); // good
8- 숫자 리터럴에서 밑줄 사용.
int myMoneyInBank = 58356823;
int myMoneyInBank = 58_356_823; // more readable
long billsToPay = 1000000000L;
long billsToPay = 1_000_000_000L; // more readable
for (int i = 0; i < names.length; i++)
{ saveInDb(names[i]); }
for (String name : names)
{ saveInDb(name); } // cleaner
Scanner scanner = null;
try
{scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext())
{System.out.println(scanner.nextLine());}}
catch (FileNotFoundException e)
{e.printStackTrace();}
finally
{if (scanner != null)
{scanner.close();}}
// error-prone as we can forget to close the scanner in the finally block
try (Scanner scanner = new Scanner(new File("test.txt")))
{while (scanner.hasNext())
{System.out.println(scanner.nextLine());}}
catch (FileNotFoundException fnfe)
{fnfe.printStackTrace();}
// cleaner and more succinct
try
{ productPrice = Integer.parseInt(integer); }
catch (NumberFormatException ex)
{ }
// fail silently without giving any feedback
try
{ productPrice = Integer.parseInt(integer); }
catch (NumberFormatException ex)
{unreadablePrices.add(productPrice); // handle error
log.error("Cannot read price : ", productPrice );// proper and meaningful message
}
- Null 요소를 반환하는 대신 빈 컬렉션 반환
Optional당신이 할 수있는대로 사용requireNonNull방법java.utils.ObjectsNotNull,NotEmpty,NotBlank주석Objects::nonNull~에StreamsrequireNonNull방법java.util.Objects
14- 동등성을 확인하려면 ==참조 및 equals개체 에 사용하십시오.
// prerequisite: the person class overrides equals() and hashCode()
Person p1 = new Person("John","Doe");
Person p2 = new Person("John","Doe");
System.out.println(p1 == p2); // false
System.out.println(p1.equals(p2)); // true
15- equals를 구현할 때 항상 hashCode를 구현하십시오. hashCode재정의 하는 경우 equals"계약 위반"을 방지하기 위해 항상 재정의해야 합니다 .
API에 따라 hashCode()두 개체에 대한 메서드 에서 반환된 결과는 해당 메서드가 동등하다고 표시하는 경우 동일해야 합니다 . equals그 반대가 반드시 참인 것은 아닙니다 .
16-불변 데이터에 대한 선호 레코드(java14부터)
public final class Person {
private final String name;
private final long idNumber;
public Person(String name, long idNumber) {
this.name = name;
this.idNumber = idNumber;
}
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Person that = (Person) other;
return (this.name.equals(that.name)) && (this.idNumber == that.idNumber);
}
public String toString() {
return name + " " + idNumber;
}
public int hashCode() {
return Objects.hash(idNumber, name);
}
}
// this class can be transformed to a record:
record Person(String name, long idNumber) { } // cleaner and less verbose
public final class MyValues {
private MyValues() {
// No need to instantiate the class, we can hide its constructor
}
public static final String VALUE1 = "foo";
public static final String VALUE2 = "bar";
}
// <-- empty line
@Repository
public class ...
20- java.handling.java.localDateTime자바 8부터 날짜 유형 처리가 권장됩니다.
더 많은 Java 모범 사례를 보려면 Clean code 및 Effective java 라는 훌륭한 책을 추천합니다 .

![연결된 목록이란 무엇입니까? [1 부]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































