Pattern: Constant Access Method


Context

It is considered bad practice to hard-code constant values in methods. A hard-coded constant is hard to find, may be duplicated, and is difficult to override.

Solution

Implement a Constant Access Method to answer the constant. This technique has several advantages over hard-coding the constant in a method where it is used:

Example

Consider a class Modem. It uses a constant to define the default connection timeout period.

Modem>>defaultTimeoutSeconds
        "Answers the default timeout period in seconds."

        ^30

We might later add a ISDN modem subclass with a much shorter timeout:

ISDNModem>>defaultTimeoutSeconds
        "Answers the default timeout period in seconds."

        ^5

Known Uses

WinWindow contains a Constant Access class method which answers the default size for new instances.

View>>defaultExtent
        "Private - Answer a point wihich is the default position for instances of the receiver"

        ^##(100 @ 100)

Related Patterns