简体   繁体   中英

Cognitive Complexity of functions should not be too high

When I use SonarLint to check code, it notifies Critical that Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain.

I use a lot of if else statement, but can not use switch case .

This is my code:

str_time = str_time.lower()
if (bool(re.search(r'\d', str_time)) == True) and ('tối' or 'chiều' in str_time):
    day = re.findall(r'\d+', str_time)[0]
    if int(day) < datetime.date.today().day:
        month = datetime.date.today().month + 1
    else:
        month = datetime.date.today().month
    year = datetime.date.today().year
    day = f'{year}-{month}-{day}'
    return format_datetime(day)
elif 'hôm nay' in str_time or 'hn' in str_time or 'chiều nay' in str_time or 'tối nay' in str_time:
    return format_datetime(datetime.date.today())
elif 'ngày mai' in str_time or 'mai' in str_time:
    day = datetime.date.today() + datetime.timedelta(days=1)
elif 'ngày mốt' in str_time or 'mốt' in str_time:
    day = datetime.date.today() + datetime.timedelta(days=2)
elif 'thứ 2 tuần sau' in str_time:
    num = 7 - datetime.date.today().weekday() + 0
    day = datetime.date.today() + datetime.timedelta(days=num)
elif 'thứ 3 tuần sau' in str_time:
    num = 7 - datetime.date.today().weekday() + 1
    day = datetime.date.today() + datetime.timedelta(days=num)

Sonar lint is right. It seems your code complexity is high. You should create smaller methods or change the logic. But if that is not possible, just ignore the linter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM