Wednesday, July 20, 2022

Re: Need help on reducing cognitive complexity

The only things that comes into my mind is taking away that first if which is redundant with the third block.
An other way might be to include all the if in a big switch...
My 2 cents
Agnese

On Thu, 21 Jul 2022 at 07:53, Sencer Hamarat <sencerhamarat@gmail.com> wrote:
Hi everyone,

I have a code block with high cognitive complexity below:

    @staticmethod
    def in_circle_check(obj_type, item, uuid, item_is_array=False):

        if obj_type not in ['trees', 'flowers']:
            return None

        plant = get_plant_with_circles(uuid)
        if not plant:
            return None

        if obj_type == 'trees':
            if plant['in_all_tree_types']:
                return True
            circle_objects = plant['tree_circle']['items']
        else:
            if plant['in_all_flower_types']:
                return True
            circle_objects = plant['flower_circle']['items']

        if isinstance(circle_objects, list):
            if item_is_array:
                for item in item:
                    if item not in circle_objects:
                        return -1
                return True
            else:
                if item in circle_objects:
                    return True
        else:
            return -1

        return -1


I try to move the first 3 if statements on the beginning of the block into new methods but that maneuver ends up with raising complexity.

Can anybody help me to learn how to reduce cognitive complexity in code blocks like this?

Kind regards,
Sencer HAMARAT

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACp8TZhBa9EbekcT1ApmzdDRVk2vCb64%3DvvXHrSawO2RJSySpQ%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACXuh-RWFoxAk1zrtzgH0FAHD-XXMwRiDLGyiUr8ZRkhgnihfg%40mail.gmail.com.

No comments:

Post a Comment