문제

we've a python function that can be achieved in 2 ways 1st method

def complexity_1(x, y):
    if 2 == x and 3 == y:
        a=3
        b=4
        c = a + b
    elif 2 == x and not 3 == y:
        a = 3
        b = 5
        c = a + b
    else:
        c=5
    return c

2nd method

def complexity_2(x, y):
    if 2 == x:
        a=3
        if y==3:
            b=4
        else:
            b=5

        c = a + b
    else:
        c=5
    return c

Which is the better way to do it the first one east to understand and reduces cyclomatic complexity but you're having duplicated code c=a+b and a=3 twice, but in the 2nd method you don't have that duplication but hard to go through the logic which one is better and right way to do?

도움이 되었습니까?

해결책

How about:

def complexity_3(x, y):
    if 2 != x:
       return 5

    return (7 if (3 == y) else 8)

Don't be afraid to exit a function from multiple locations. That advice was specific to assembly, and means always return to the caller that called you. This is (excluding some safe compiler optimisations) enforced by functions and return.

Also don't sweat cyclomatic complexity. Its a way of calculating branching, nothing more. Only the most uninteresting pieces of code that do not change their own behaviour, do not branch. Everything else necessarily must branch. Of course if the branching becomes too high (say spaghetti code) then yes some cleanup is required.

And finally code should be written to be maintainable. And by maintainable I mean very readable, because that is the single slowest thing this code will ever do. There are many ways to try and achieve this. The simplest way is to get the new guy on the team to read it. The next best way is to just get someone else to read it the longer they take/more questions they have, the harder the code is to read.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top