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

Constant Access Method

Previous pageReturn to chapter overviewNext page


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.


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


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


      "Answers the default modem timeout period in seconds."



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


      "Answers the default timeout period in seconds for ISDN modems."



Known Uses

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


  "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.


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

  Illustrated Patterns:

  Constant Access Method

  Private Method




Related Patterns

Accessor Method