This article is participating in the Java Topic Month – Java Debug Notes event. See the event link for details

The original

As a qualified development, except in the premise of ensuring the validity of the code. We need to provide code quality in other areas. I have summarized some aspects of optimizing the code as follows:

  • Extract more than 5 lines of duplicate code. Simple extraction in idea can use shortcut keys Ctrl + Alt + M. If code reusability is not limited to the current class, you can abstract the method or extract it into the Util toolkit

  • Avoid using strings directly as parameters or variables, and extract magic values into individual classes for overall maintenance

  • If necessary, create enumeration classes to maintain the state of some keywords or special number fields on the page

  • Use assertions to streamline code

  • Use lambda expressions to simplify the code

I’ll post some code later that I think is, after all, simple to use

Assert

Looking at the source code, it’s easy to see, what exactly does each method mean

The primary use case for assertions is field validation

Here are some common ones.

Null check

  1. Assert.isnull (obj, "Return error checking rule prompt ") objIt’s triggered when it’s not empty
  2. Assert.notNull(obj," fired if null ")

Boolean check

Assert.isTrue(Boolean, "Error log returned ")

Expression check

Assert.state(Boolean," basically the same as isTrue ")

The exception log returns a block

Custom assertion

public class Assert {

    public static T fail(String message) {
        throw new ApiException(message);
    }


    public static T fail(RetCode retCode){
        throw newApiException(retCode); }}Copy the code

Abnormal encapsulation

public class ApiException extends RuntimeException
{
    private IErrorCode errorCode;

    public ApiException(IErrorCode errorCode) {
        super(errorCode.getMessage());
        this.errorCode = errorCode;
    }

    public ApiException(String message) {
        super(message);
    }

    public ApiException(Throwable cause) {
        super(cause);
    }

    public ApiException(String message, Throwable cause) {
        super(message, cause);
    }

    public IErrorCode getErrorCode(a) {
        returnerrorCode; }}Copy the code

Time code in use

Often get the encapsulation of a field in a collection

Reasons for encapsulation: In practice, many fields, states, enumerations, etc. are stored in the data dictionary, and user names, units, roles, organizations, etc. are stored in their own business tables. As the scale of the service grows. This interface for querying the actual meaning through IDS needs to be taken out in isolation. Each list page data translation, the repeated use of lambda expressions, code repetition is high. This is where we have the secondary encapsulation.

Here are some differences before and after code optimization: Code before optimization

/ / get userIds
String userIds = list.stream()
    .map(RepairVo::getUserId)
    .map(String::valueOf)
    .collect(Collectors.joining(","));
/ / get orgIds
String orgIds = list.stream()
    .map(RepairVo::getOrgId)
    .map(String::valueOf)
    .collect(Collectors.joining(","));
// Get the dictionary item
String dictIds = list.stream()
    .map(RepairVo::getType)
    .map(String::valueOf)
    .collect(Collectors.joining(","));
    
// Then query userName orgNames dictNames separately through a separate service and assign a value
Copy the code

The optimized code

Map<Integer, String> orgNames = CommonUtils.getOrgChainNames(organizationService, list, RepairVo::getOrgId);
Map<Integer, String> usernames = CommonUtils.getUsernames(userService, list, RepairVo::getApplicant, RepairVo::getCurrentUserId);
Map<Integer, String> dictNames = CommonUtils.getOrgChainNames(dictService, list, RepairVo::getType);

// Backfill the translated values
return list.stream()
    .map(e -> new RepairVo(e, orgNames, usernames,dictNames))
    .collect(Collectors.toList());
    
Copy the code

RepairVo entity class

@Data
public class RepairVo {

    private Integer id;
    private Integer userId;
    private String username;
    private Integer type;
    private String typeName;
    private String code;
    private Integer orgId;
    private String orgName;
    
    public RepairVo(RepairVo vo,Map<Integer, String> orgNames, Map<Integer, String> usernames,Map<Integer, String> dictNames {
        BeanUtils.copyProperties(vo, this); setUsername(usernames.get(vo.getUserId()); setOrgName(orgNames.get(vo.getOrgId()); setTypeName(dictNames.get(vo.getType()); }}Copy the code

Encapsulated utility classes

public class CommonUtils {

    public static void badRequest(String errorCode, String entityName) {
        throw badReq(errorCode, entityName);
    }

    public static BadRequestAlertException badReq(String errorCode, String entityName) {
        return new BadRequestAlertException(errorCode, entityName, errorCode);
    }

    public static Instant toInstant(String datetime) {
        return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.ofHours(8));
    }

    public static <T> PageDTO<T> transfer(Page<T> page) {
        return createPage(page.getContent(), page.getTotalElements());
    }

    public static <T> PageDTO<T> createPage(List<T> list, long total) {
        PageDTO<T> p = new PageDTO<>();
        p.setItems(list);
        p.setTotal(new Long(total).intValue());
        return p;
    }

    public static Map<String, Object> getResponse(Long id) {
        Map<String, Object> res = new HashMap<>();
        res.put("id", id);
        return res;
    }

    @SafeVarargs
    public static <E, M> List<String> map(Collection<E> entries, Function<E, M>... getters) {
        if (CollectionUtils.isEmpty(entries)) {
            return Collections.emptyList();
        }
        Assert.notEmpty(getters, "At least 1 elements in the \"getters\" parameter");
        List<M> values = new ArrayList<>();
        entries.forEach(e -> Stream.of(getters).map(getter -> getter.apply(e)).forEach(values::add));
        return values.parallelStream().filter(Objects::nonNull).distinct().map(Objects::toString).collect(Collectors.toList());
    }

    @SafeVarargs
    public static <E, M> String groupConcat(Collection<E> entries, String delimiter, boolean quote, Function<E, M>... getters) {
        return map(entries, getters)
                .parallelStream()
                .map(s -> quote ? StringUtils.quote(s) : s)
                .collect(Collectors.joining(delimiter));
    }

    @SafeVarargs
    public static <E, M> String groupConcat(Collection<E> entries, boolean quote, Function<E, M>... getters) {
        return groupConcat(entries, ",", quote, getters);
    }

    @SafeVarargs
    public static <E, M> String groupConcat(Collection<E> entries, Function<E, M>... getters) {
        return groupConcat(entries, false, getters);
    }

    @SafeVarargs
    public static <E, M> Map<Integer, String> getUsernames(UserService service, Collection<E> entries, Function<E, M>... getters) {
        String userIds = groupConcat(entries, getters);
        return StringUtils.isEmpty(userIds) ? Collections.emptyMap() : service.getUserNamesByUserIds(userIds);
    }

    @SafeVarargs
    public static <E, M> Map<Integer, String> getOrgNames(OrganizationService service, Collection<E> entries, Function<E, M>... getters) {
        String orgIds = groupConcat(entries, getters);
        return StringUtils.isEmpty(orgIds) ? Collections.emptyMap() : service.getOrgNamesByOrgIds(orgIds);
    }

    @SafeVarargs
    public static <E, M> Map<Integer, String> getOrgChainNames(OrganizationService service, Collection<E> entries, Function<E, M>... getters) {
        String orgIds = groupConcat(entries, getters);
        return StringUtils.isEmpty(orgIds) ? Collections.emptyMap() : service.getChainNamesByIds(orgIds);
    }

    @SafeVarargs
    public static <E, M> Map<Integer, String> getDictNames(DictService dictService, Collection<E> entries, Function<E, M>... getters) {
        String ids = groupConcat(entries, getters);
        returnStringUtils.isEmpty(ids) ? Collections.emptyMap() : dictService.getDictNamesByIds(ids); }}Copy the code