Defining and using global variables and global functions, when the convention dictates OOP can be confusing and difficult to use properly for
multiple reasons:
- You run the risk of name clashes.
- Global functions must be stateless, or they can cause difficult-to-track bugs.
- Global variables can be updated from anywhere and may no longer hold the value you expect.
- It is difficult to properly test classes that use global functions.
Instead of being declared globally, such variables and functions should be moved into a class, potentially marked static
, so they can
be used without a class instance.
This rule checks that only object-oriented programming is used and that no functions or procedures are declared outside of a class.
Noncompliant code example
var name = "Bob" // Noncompliant
func doSomething() { // Noncompliant
//...
}
class MyClass {
//...
}
Compliant solution
public class MyClass {
public static var name = "Bob"
public class func doSomething() { // Compliant
//...
}
//...
}
Exceptions
The operator function is a function with a name that matches the operator to be overloaded. Because such functions can only be defined in a global
scope, they are ignored by this rule.
public class Vector2D {
var x = 0.0, y = 0.0
// ...
}
func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}