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

complexity is x it is time to do something…, visual studio code

I am using vscode for a react native app. And I am wondering if the message:

complexity is x it is time to do something…

is always useful.

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

Because for example I have this function:

import { API_URL } from "@env";
import { retrieveToken } from "../authentication/token";
export const fetchCategoryData = async () => {
    const token = await retrieveToken();
    try {
        if (token) {
            const response = await fetch(`${API_URL}/api/categories/main_groups/`, {
                method: "GET",
                headers: {
                    Authorization: `Token ${token}`,
                    "Content-Type": "application/json",
                },
            });
            return await response.json();
        } else {
            throw new Error(token);
        }
    } catch (error) {
        Error("can't retreive data");
    }
}

And vscode says:

complexity is 6 it is time to do something…

retrieveToken:

import AsyncStorage from "@react-native-async-storage/async-storage";

export const retrieveToken = async () => {
    try {
        const token = await AsyncStorage.getItem("Token");

        return token;
    } catch (error) {
        return null;
    }
};

Question: How to improve the function where the message says: complexity is 6 it is time to do something…?

>Solution :

the big question is: is it possible to refactor this?

Don’t use try/catch everywhere. Use it only where you can actually handle the error. Which in your example appears to be nowhere – any error needs to be handled by the caller of fetchCategoryData.

So you can simplify the whole thing to

export const retrieveToken = async () => {
    const token = await AsyncStorage.getItem("Token");
    if (!token) throw new Error('Got empty token from storage');
    return token;
}

export const fetchCategoryData = async () => {
    const token = await retrieveToken();
    const response = await fetch(`${API_URL}/api/categories/main_groups/`, {
        method: "GET",
        headers: {
            Authorization: `Token ${token}`,
            "Content-Type": "application/json",
        },
    });
    return await response.json();
}

which have a cyclomatic complexity of 2 and 1 respectively.

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