提高代码简洁度的工具类合集

557 阅读1分钟

Assert

// original code
if (input == null) {
    throw new IllegalArgument("given argument must not be null");
}

if (num != 1) {
    throw new IllegalArgument("given number is not 1");
}

// clean code, powered by spring-core
Assert.notNull(input, "input is null");

Assert.isTrue(num == 1, "given number is not 1");

Safe equals

// not null-safe
!a.equals(b)

// better, powered by JDK-7
!Objects.equals(a, b)

StringUtils

// common-lang3
StringUtils.isEmpty(str);
StringUtils.isBlank(str);

BooleanUtils

Boolean b;

// original code
if (b == null || b == false) {
    //...
}

// clean code, powered by common-lang3
if (BooleanUtils.isNotTrue) {
    //...
}

defaultIfNull

// defaultIfNull common-lang3
int expiration = ObjectUtils.defaultIfNull(
                Utils.getConfigValueAsInt(PROPERTY_EXPIRATION),
                DEFAULT_EXPIRATION);

Ignore Checked-Exception

Lombok @SneakyThrow

public static void normalMethodWithThrowsIdentifier() throws IOException {
    throw new IOException();
}

@SneakyThrows
public static void methodWithSneakyThrowsAnnotation() {
    throw new IOException();
}

Builder Pattern with Lombok

lombok Builder

Required arguments with a lombok @Builder

import lombok.Builder;
import lombok.ToString;

@Builder(builderMethodName = "hiddenBuilder")
@ToString
public class Person {

    private String name;
    private String surname;

    public static PersonBuilder builder(String name) {
        return hiddenBuilder().name(name);
    }
}

Copied from SOF

guava

TODO

retry strategy

TODO