dimanche 31 octobre 2021

Can this part of code be considered code duplicate

I want to ask about duplicates.. I know first is duplicate as would be better to extract it to a function but also second block of code if appears multiple times can be considered duplicate and needs to be extracted into separate function? I want to know the general approach and also if tools like sonar would complain about duplicates in this case. Thank you.

 struct X 
    {
        void print()
        {
            std::cout<<"print from X";
        }
        
   
        void print_2()
        {
            std::cout<<"print_2 from X";
        }
    };
    
    int main()
    {   
        
        int n1 = 10;
        for(int x = 0; x < n; x++)
        {
            std::cout<<x;
        }
        
        int n2 = 10;
        for(int x = 0; x < n2; x++)
        {
            std::cout<<x;
        }
        
        // printToN(n); printToN(n2)  // duplicate
        
        
        if (cond)
        {
            X x;
            if (cond2)
            {
                x.print();
                x.doSomething();
            }
            else
            {
                x.print_2();
            }
        }
        
        /*
        ...
        ...
        ...
        */
        // again this block of code
        if (cond)
        {
            X x;
            if (cond2)
            {
                x.print();
                x.doSomething();
            }
            else
            {
                x.print_2();
            }
        }
        
        // is this also duplicate ?
        
        
        
        return 0;
    }

Aucun commentaire:

Enregistrer un commentaire