AngularJS controller exceeding allowed complexity (SonarLint alert)

While utilizing SonarLint in Eclipse, I encountered an issue while working on an AngularJS application. Specifically, I was cleaning up a controller to improve readability when SonarLint flagged the following problem:

The function has a complexity of 11, exceeding the authorized limit of 10.

Here is the code snippet for the controller in question:

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();
});

I am puzzled as to why this triggered the complexity issue. The only nested functions seem to be the start/stop/resume/pause functions calling the update function. Upon careful inspection, I verified the correct syntax with brackets and parentheses as well.

Answer №1

To simplify your code, you can create a single function:

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

Then you can use it like this:

$scope.generatorAction('stop');

Alternatively, you could use a service to handle your HTTP requests, which is considered a best practice.

Edit:

I follow the styleguide for my Angular applications found here: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

You can create a simple service for your HTTP requests like so:

(function() {
  'use strict';

  angular
    .module('yourModuleName')
    .factory('generator', generatorFactory);

  function generatorFactory($http) {

     var service = {
        start: start,
        resume: resume,
        suspend: suspend,
        stop: stop
     }

     return service;

     function start() {
        return $http.get('/start');
     }

     function resume() {
        return $http.get('/resume');
     }

     function suspend() {
        return $http.get('/suspend');
     }

     function stop() {
        return $http.get('/stop');
     }
  }

})();

Then in your controller:

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

    $scope.genStatus = "stopped";

    $scope.startgenerator = function() {
        generator.start().then(function () {
            $scope.updateStatus();
        });
    };

    $scope.resumegenerator = function() {
        generator.resume().then(function () {
            $scope.updateStatus();
        });
    };

    $scope.suspendgenerator = function() {
        generator.suspend().then(function () {
            $scope.updateStatus();
        });
    };

    $scope.stopgenerator = function() {
        generator.stop().then(function () {
            $scope.updateStatus();
        });
    };

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

    $scope.updateStatus();
});

At first glance, it may seem like more code and complexity, but by using a service, you make it easier to stop the generator from other pages or components simply by injecting the 'generator' service and calling generator.stop();. If the endpoint URLs ever change, you only need to update them in the service.

Answer №2

Is there a problem with this code?

You're seeking an unbiased response to a subjective inquiry. Let's consider that as the complexity of a function increases, it becomes more challenging for you or others to maintain it. This issue indicates that you've reached a point where the code may become difficult to comprehend.

Could the complexity be 11?

The method SonarQube uses to calculate complexity doesn't align perfectly with any established standards. Nonetheless, here is how it arrived at the number 11 in this case:

def login():
    username = request.form['username']
    if username == 'admin':
        return 'Hello admin!'
    else:
        return 'Invalid username'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to navigate through textarea components within an iframe tag

I am presented with the following HTML structure: <iframe id="screenshare" ref="screenshare" class="fullScreen2"></iframe> To dynamically fill the <iframe> element, I am utilizing JavaScript through the below function: func ...

Why aren't the divs appearing on the page?

I have developed a JavaScript and PHP page where the script in the PHP page sends data to my SQL database. However, the result is not displayed on my home page. Here is the code snippet: function getVote(question_ID) { var option_ID = document.queryS ...

How can an array be generated functionally using properties from an array of objects?

Here's the current implementation that is functioning as expected: let newList: any[] = []; for (let stuff of this.Stuff) { newList = newList.concat(stuff.food); } The "Stuff" array consists of objects where each ...

Merging double borders in a div using CSS is essential for creating

Upon examining this sample, it's evident that the borders do not blend together. css: div{ float:left; background-color:moccasin; width:100px; height:100px; border:1px solid tomato; } The number of divs is arbitrary, and only on ...

Is it possible to use the googleapis npm package to make a query to a googleSheet?

I have a huge dataset with thousands of rows and I want to optimize my queries instead of fetching all the data every time. I checked out the Query language but it doesn't quite fit my needs. For authentication, I am using a Service account: const au ...

Addressing the issue of prolonged Electron initialization

Scenario After spending considerable time experimenting with Electron, I have noticed a consistent delay of over 2.5 seconds when rendering a simple html file on the screen. The timeline of events unfolds like this: 60 ms: app ready event is triggered; a ...

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented: function toggleHiddenContent(tabClass) { let t = document.querySelectorAll(tabClass); for(var i = 0; i<t.length; i++) { t[i].classList.toggle="visible-class"; } } .hidden-conten ...

Difficulty understanding JavaScript sum calculations

I am currently working on a website project. Seeking assistance to enable an increment of one when clicked. Also need guidance on calculating the total price of items collected in a designated section under "number of items selected". Goal is to display ...

What is the best approach to determine the value of a textbox in an array for each row of

I am trying to display the total sum of values for each row in a data array. There are 5 rows of data, and I need to calculate the results for each one. Can someone assist me in solving this? function calculateTotalValue(){ var total = (document.get ...

Is sending an AJAX request to a Node.js Express application possible?

Currently, I am attempting to authenticate before utilizing ajax to add data into a database $('#button').click(function () { $.post('/db/', { stuff: { "foo" : "bar"} }, callback, "json"); }); Below is my node.js code: ...

What is the method to extract information from the provided URL?

Hello, I am looking to retrieve system requirements data from . How can I achieve this using JS or react? ...

Achieving the minimum width of a table column in Material-UI

Currently I am in the process of developing a React website with Material-UI. One query that has come up is whether it's feasible to adjust the column width of a table to perfectly fit the data, along with some extra padding on both ends? Outlined be ...

AngularJS is capable of executing conditional logic using the if/else statement

I am attempting to set the inputLanguage value to 'en' and encountering an error that says english is not defined. Here is the code snippet from my alchemy.js file: module.exports = function(Alchemy) { Alchemy.language = function(inText, inp ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

Implementing nested popup windows using Bootstrap

I am facing an issue with my two-page sign-in and sign-up setup in the header of my angular2 project. On the sign-up page, I have a link that should redirect to the sign-in page when clicked, but I am struggling to make it work. Can someone provide guidanc ...

Experience the click action that comes equipped with two unique functions: the ability to effortlessly add or remove a class

Currently, I am in the process of creating a list of anchor links that contain nested anchor links, and there are a few functionalities that I am looking to implement. Upon clicking on a link: Add a class of "current" Remove the class of "current" from ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

Creating a button that redirects to an external link in CodeIgniter:

Hello everyone, I'm new here and I could really use some assistance with a problem. I am trying to link the button labeled 'lihat rincian' and each row of tables to redirect to an external link like Here's a snapshot of my datatables ...

Ways to execute a GET request including all idRefs

In my project, I have 2 models: stores and products. The stores model has a reference to products like this: produtos: [ { type: mongoose.Schema.ObjectId, ref: 'Produto' } ] Currently, I have an object that looks like this: { "_id": "58971 ...