This mixin adds the comparison conditional operators to your class, so that whenever an instance of your class is one or more of the operands in a comparison test, the comparison is performed consistently. Comparison operations include:
| Test | Operators | Examples |
|---|---|---|
| Equality | ==, .eq. | if (myobj == other) |
| Inequality | !=, .ne. | if (myobj != other) |
| Greater Than | >, .gt. | if (myobj > other) |
| Less Than | <, .lt. | if (myobj < other) |
| Greater Than or Equal | >=, .ge. | if (myobj >= other) |
| Less Than or Equal | <=, .le. | if (myobj <= other) |
To use this mixin, you must define the identifier COMPARE_CLASS as the class under compilation and then include the module. For example:
class myclass
.define COMPARE_CLASS, myclass
.include "MIXINS:Comparable"
static method compare, int
in req obj1, @COMPARE_CLASS
in req obj2, @COMPARE_CLASS
proc
;Return -1, 0, or 1
end
You must supply the static method "compare" shown above, which may be public, private, or protected. This method will be invoked whenever one of the comparison operations shown above needs to compare your object to another instance of the same class. If obj1 is less than obj2, return -1. If they're equal, return 0. Otherwise, return 1.
If the only thing your "compare" method does is to compare members of each instance (fields, properties, or even method results), you can make use of another shortcut. Define the identifier COMPARE_MEMBER to be the member that should be compared, and the "compare" method will be automatically generated. For example:
class myIntegerWrapper
.define COMPARE_CLASS, myIntegerWrapper
.define COMPARE_MEMBER, m_intval
.include "MIXINS:Comparable"
private m_intval, int
To create comparisons against other types, define the identifier COMPARE_TYPE2 as the type to compare against, include the module, and provide another version of the "compare" method to handle that comparison:
.define COMPARE_TYPE2, int
.include "MIXINS:Comparable"
static method compare, int
in req obj1, @COMPARE_CLASS
in req obj2, COMPARE_TYPE2
proc
end
When COMPARE_TYPE2 does not equal @COMPARE_CLASS, the operators for both orders of operands will be generated automatically.
You may also define COMPARE_MEMBER2 to specify the member of COMPARE_TYPE2 that should be compared against COMPARE_CLASS's COMPARE_MEMBER member. If you define COMPARE_TYPE2 and COMPARE_MEMBER, but dont' define COMPARE_MEMBER2, then COMPARE_MEMBER must exist in both classes.