Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Limiting a number without a conditional

Consider the following function:

def absolute_value(some_number):
    if some_number < 0:
        return -some_number

    return some_number

and this one:

def absolute_value(some_number):
     return (some_number**2)**0.5

We can say that (in a naive manner) these two more or less achieve the same result (ignoring the performance issues) but the latter one has less cyclomatic complexity due to lack of the conditional. What I want is, for the sake of reduced cyclomatic complexity, I want to implement the following function without the conditional:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def limit(some_number):
    if some_number > 1
        return 1

    return some_number

Is there an elegant way of doing this?

Thank you for your interest.

>Solution :

Aside from min(1, some_number) you can also do this:

def limit(x):
    return (x > 1) + (x <= 1) * x

But that is in my opinion way harder to understand than your code. That also holds for your absolute_value example. I think such tricks to reduce cyclomatic complexity are beyond the point of cyclomatic complexity. In the end it doesn’t make your code easier to understand, but cyclomatic complexity is just unable to capture this. But maybe that is what you want to demonstrate…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading