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.
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.