Organize experience and improve code quality

1) Do not arbitrarily add null judgments, and clarify business requirements through exceptions

The business logic of the following code: If bspcalendar.getHasProduction() is true, then billPeriodService.queryBillPeriod must have a value. This limitation is implemented through interface control. In this case, the following if (billp != null) judgment is meaningless, because The data preparation problem in the development phase will cause billPeriodService.queryBillPeriod to be empty, so increase the if (billp != null) judgment, so that the program will not have a null pointer, but if it is really empty, it will cause a logic error (the code does not report an error, But the result is wrong, it brings difficulties to the debugging problem), the reason why the data is empty is caused by the error of other code. A better approach is to throw an exception if it is empty, so that the program is interrupted instead of executing on the wrong path, and the developer is clearly prompted that it is caused by a data problem, so that the developer can know the reason at a glance. And it must not be empty is also a business logic requirement.

        int month = 1;
        int period = 1;
        BspCalendar bspcalendar = bspCalendarService.queryBspCalendar(param.getYear());
        if (bspcalendar.getHasProduction()) {
            BillPeriod billp = billPeriodService.queryBillPeriod(userInfo.getBspCode(),
                    param.getStartDate());
            if (billp != null) {
                month = praseBillPeriod(billp.getBillPeriod().substring(2))[0];
                period = praseBillPeriod(billp.getBillPeriod().substring(2))[1];
            } 

        } else {
            if (yearHeader.compareTo(param.getStartDate()) > 0) {
                month = 1;
            } else {
                month = DateUtils.getMonth(param.getStartDate());
            }
        }

Improved code, adding null exception.

int month = 1;
        int period = 1;
        BspCalendar bspcalendar = bspCalendarService.queryBspCalendar(param.getYear());
        if (bspcalendar.getHasProduction()) {
            BillPeriod billp = billPeriodService.queryBillPeriod(userInfo.getBspCode(),
                    param.getStartDate());
            if (billp != null) {
                month = praseBillPeriod(billp.getBillPeriod().substring(2))[0];
                period = praseBillPeriod(billp.getBillPeriod().substring(2))[1];
            } else {
                throw new RuntimeException("not exist BillPeriod,it's StartDate is:"
                        + DateUtils.dateToString(param.getStartDate(), "yyyyMMdd"));
            }
        } else {
            if (yearHeader.compareTo(param.getStartDate()) > 0) {
                month = 1;
            } else {
                month = DateUtils.getMonth(param.getStartDate());
            }
        }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327106058&siteId=291194637