Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3086

Operator functions should call existing functions

    XMLWordPrintable

    Details

    • Message:
      Move the body of this operator function into another function and call the function from here.
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Covered Languages:
      Swift
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min

      Description

      Making an operator a convenience wrapper around an existing function or method provides additional flexibility to users in how the functionality is called and in what options are passed in.

      This rule raises an issue when the function that defines the operation of a operator consists of something other than a single function call.

      Noncompliant Code Example

      infix operator >< { associativity right precedence 90 }
      func >< (left: Double, right: Double) -> Double {  // Noncompliant
        let leftD = (left % 1) * 100
        let rightD = (right % 1) * 100
        let leftW = (left - leftD) / 100
        let rightW = (right - rightD) / 100
        return (leftD + leftW) * (rightD + rightW)
      }
      

      Compliant Solution

      infix operator >< { associativity right precedence 90 }
      func >< (left: Double, right: Double) -> Double { 
        return fubar(left, right)
      }
      
      func fubar(left: Double, right: Double) -> Double {
        let leftD = (left % 1) * 100
        let rightD = (right % 1) * 100
        let leftW = (left - leftD) / 100
        let rightW = (right - rightD) / 100
        return (leftD + leftW) * (rightD + rightW)
      }
      

      Exceptions

      Operators that end with = are expected to update their left-hand operands, and are therefore ignored.

      func **= (inout p1:Int, p2:Int) { 
          p1 = p1 ** p2
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: