Search code examples
javaloopscyclomatic-complexity

Reduce number of for loops in method


I'm trying to reduce the number of for loops in this method, but I'm not sure how to do that while still keeping the logic in tact and not moving to another method. I want to do this for the sake of reducing the McCabe Cycolmatic Complexity, which increases with each loop by 1. So I'd like to reduce the method by 1.

  private void method(int page)
    {
        for (int i = 0; i < LINES_PER_PAGE; i++)
        {
            nextLine[i] = null;
        }
        try
        {
            Scanner temp = new Scanner(fileToPrint);
            for (int i = 0; i < page - 1; i++)
            {
                skipAPage(temp);
            }
            for (int i = 0; (i < LINES_PER_PAGE) && (temp.hasNext()); i++)
            {
                nextLine[i] = expandTabs(temp.nextLine());
            }
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
    }

Solution

  •     for (int i = 0; i < LINES_PER_PAGE; i++) {
            nextLine[i] = null;
        }
    

    This is completely unnecessary, because default value for any object is null in java.

    In the rest of two loops, you are calling two different methods and your second loop also depends on the argument, so I am not sure they can be merged into one loop.


    As it appears that nextLine is declared outside the method, I would suggest you to use List<Sometype> and add the elements into it, coming from expandTabs(temp.nextLine());, every time you enter the method clear the list list.clear().


    Try this code. Use the appropriate type for declaring the List<String>. You can access the element from the List using myList.get(index) method.

    List<String> myList = new ArrayList<>();
    
    private void method(int page) {
      try {
        myList.clear();            // Clear the list.
        Scanner temp = new Scanner(fileToPrint);
        for (int i = 0; i < page - 1; i++) {
          skipAPage(temp);
        }
        for (int i = 0; (i < LINES_PER_PAGE) && (temp.hasNext()); i++) {
          myList.add(expandTabs(temp.nextLine()));    // Add the elements to the list.
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    }