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

Exploring the Depths of Web Scraping: A Guide to Scraping Within a Scraped Website

I have successfully scraped data from a specific page, but now I need to follow another href link in order to gather more information for that particular item. The problem is, I am unsure of how to do this. Here is an excerpt of what I have accomplished s ...

There is no Api.js file in the Cordova iOS platform

I have been attempting to integrate the iOS platform into a new Cordova 7.0.1 project, but I continuously encounter the error mentioned in the title of this post. Despite following the steps outlined in this thread here, including removing and re-adding ...

Which property is best suited for styling a phone number field in the MUI data grid in ReactJS?

I previously utilized the pattern attribute for input fields in pure HTML, but now I no longer have any input fields. What should be my next steps? Can you provide me with a reference in the MUI documentation? https://i.stack.imgur.com/ ...

Obtaining the NativeElement of a component in Angular 7 Jasmine unit tests

Within the HTML of my main component, there is a my-grid component present. Main.component.html: <my-grid id="myDataGrid" [config]="gridOptions" </my-grid> In main.component.specs.ts, how can I access the NativeElement of my-grid? Cu ...

What is the best way to link multiple checkboxes to a single ng-model?

Currently, I am working on mobile app development using the Ionic framework. In order to set multiple checkboxes with the same ng-model, I want all three checkboxes to be clicked when one is selected. However, the values are not being stored as expected. ...

Having trouble getting Angular-UI-Select to work with a basic variable on $scope?

How can you reset an array with selected values so that the values can be reselected from the dropdown? I am working with a people array where the values are initially displayed in a select dropdown. When I choose certain names, they get transferred to th ...

Using Laravel 8 to create connected dropdown menus with the power of Ajax

Struggling with setting up a dependent dropdown menu in Laravel 8 using Ajax. The first dropdown works fine, but the next two don't display any options. Being new to Laravel, I'm having trouble pinpointing the problem areas. Seeking assistance to ...

Emphasize sections of text within a chart

Looking for a Specific Solution: I've encountered similar problems before, but this one has a unique twist. What I'm trying to achieve is to search for a substring within a table, highlight that substring, and hide all other rows (tr's) th ...

Is it possible to include additional transformations to a div element?

Is it possible to add additional rotation to a div that already has a transform applied? For example, can I do the following: <div style="width: 200px; height: 200px; background-color: red; transform: rotateX(90deg) rotateY(10deg)" id="myDiv">< ...

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

How can I retrieve the length of an array in vuejs?

This snippet includes a script tag <script> export default { data() { return { blogs: [], }; }, created() { this.paginate_total = this.blogs.length / this.paginate; }, }; </script> Displayed below is the respo ...

Can you choose an option from a dropdown menu without relying on jQuery?

Can a dropdown list item be selected using AngularJS instead of jQuery? I have successfully accomplished this using jQuery, but I am curious if it can be done with AngularJS. This is how I achieved it using jQuery: var dropdownlist = $("select").data("k ...

To ensure a rectangular image is displayed as a square, adjust its side length to match the width of the parent div dynamically

How can I make the images inside my centered flexbox parent div, #con, be a square with side length equal to the width of the parent div? The image-containing div (.block) is positioned between two text divs (#info and #links). I want the images to be squa ...

I am not getting any reply in Postman - I have sent a patch request but there is no response showing up in the Postman console

const updateProductInfo = async (req, res) => { const productId = req.params.productId; try { const updatedProduct = await Product.findOneAndUpdate({ _id: productId }, { $set: req.body }); console.log("Product updat ...

Finding the arithmetic operator and then assigning both the operator and its index to a globally accessible variable can be accomplished through a

Hello, I am currently learning web development and as a beginner project, I am working on creating a calculator in React. My goal is to have the selected arithmetic operation ("+", "/", "-", or "X") executed when the user clicks "=". To achieve this, I s ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Using ngBindHtml in combination with angularUI in a template may yield a different outcome compared to using $sce.parseAs

Edit: Problem solved! Details at the end of the question. Within my directive sfNgFieldWrapper, I have integrated a tooltip from angularjUI ui-bootstrap. The text for the tooltip is designated by tooltip="{{ttpText}}". The issue arises when the text con ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

Using Linux variables in the .env file of your Vue.js project can provide a convenient way to

Using .env in a *.js file allowed me to set the BANK variable as either A_BANK or B_BANK like so: BANK=A_BANK or BANK=B_BANK However, when passing the argument as A_BANK or B_BANK like: --bank A_BANK in a shell script loop for var in $@ do if [ ${var} ...