Navigation:  Appendix B: Dolphin Pattern Book > Method Patterns >

Constant Access Method

Previous pageReturn to chapter overviewNext page

Context

In Smalltalk it is often considered bad practice to hard-code constant values in methods. A hard-coded constant is hard to find, may end up being duplicated, and is difficult to override in subclasses.

Solution

Implement a method whose sole purpose is to answer the constant. Place this method in the constants category. This technique has several advantages over hard-coding the constant in a method where it is used:

the constant is easier to find
the comment in the constant access method can be used to describes the constant value
the constant will exist in just one place
the constant will be easier to override when new subclasses are added

Example

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

Modem>>defaultTimeoutSeconds

      "Answers the default modem 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 for ISDN modems."

      ^5

 

Known Uses

Class View contains a constant access method which answers the default size for new instances.

View>>defaultExtent

  "Private - Answer the default size of the receiver. This is used only to

  set the size of a view when it is created. Thereafter preferredExtent is

  used when the desired size of a view is requested."

  ^##(100 @ 100)

 

The sample class VideoTape contains a class method #defaultTapeLength for specifying the most common duration of video tapes.

defaultTapeLength

  "Private - Answer a default length (in minutes) to use for instances of the receiver.

  Illustrated Patterns:

  Constant Access Method

  Private Method

  "

  ^240

 

Related Patterns

Accessor Method