Krihox Krihox - 4 months ago 60
AngularJS Question

Complexity greater than authorized in AngularJS Controller (SonarLint issue)

I use SonarLint with Eclipse, and I'm codding an application using AngularJS. I had a problem with a controller so I was trying to clean it a bit to see clearer, and then SonarLint popped me up an issue :


Function has a complexity of 11 which is greater than 10 authorized.


And here's the code of my controller :

app.controller('LauncherCtrl', function ($scope, $http) {

$scope.genStatus = "stopped";

$scope.startgenerator = function() {
$http.get('/start').success(function () {
$scope.updateStatus();
});
};

$scope.resumegenerator = function() {
$http.get('/resume').success(function () {
$scope.updateStatus();
});
};

$scope.suspendgenerator = function() {
$http.get('/suspend').success(function () {
$scope.updateStatus();
});
};

$scope.stopgenerator = function() {
$http.get('/stop').success(function () {
$scope.updateStatus();
});
};

$scope.updateStatus = function() {
$http.get('/status').success(function (response) {
$scope.genStatus = response.data;
});
};

$scope.updateStatus();
});


Is there something wrong with it ? I assume this issue would be about too much nested loops/functions, but as far as I can see it's not (apart from the functions start/stop/resume/pause which are calling update, but it isn't complexity 11, is it ?). + I double checked the brackets/parenthesis, I don't think the problem comes from there.

Answer

If you want to remove complexity you can make one function :

    $scope.startgenerator = function() {
        $http.get('/start').success(function () {
            $scope.updateStatus();
        });
    };

    $scope.resumegenerator = function() {
        $http.get('/resume').success(function () {
            $scope.updateStatus();
        });
    };

    $scope.suspendgenerator = function() {
        $http.get('/suspend').success(function () {
            $scope.updateStatus();
        });
    };

    $scope.stopgenerator = function() {
        $http.get('/stop').success(function () {
            $scope.updateStatus();
        });
    };

to

$scope.generatorAction = function(action) {
    $http.get('/' + action).success(function () {
        $scope.updateStatus();
    });
};

and then use it like this:

$scope.generatorAction('stop');

Or use a service that handle your http request, It's a better practice.