Article Preview
Buy Now
COLUMN
Favor Composition over Inheritance
Designing a Validating EditField
Issue: 1.1 (August/September 2002)
Author: Charles Yeomans
Article Description: A validating editfield
Article Length (in bytes): 5,141
Starting Page Number: 36
Article Number: 1010
Resource File(s):
1010.zip Updated: 2013-03-11 19:07:55
Related Link(s): None
Excerpt of article text...
The Problem
You are writing a Quicken-killer in REALbasic. You need to do a lot of input validation -- dates, currency input, names, etc. You think, "Ah, RB has made it easy for me -- all I need to do is slap some validation code in the LostFocus event handlers of the editfields." But writing a Quicken-killer is a big job, and cut-and-paste is especially efficient at propagating errors. It occurs to you that you can subclass Editfield. So you define DateEditField, NumberEditField, CurrencyEditField, NonEmptyEditField, TextLengthAtMostNEditfield, and other subclasses. But as the subclasses begin piling up -- for instance, you need an EditField subclass that accepts valid currency input and must be nonempty -- the project begins to crumble under its own weight. Then you decide that some editfields must be able to change the validation method at runtime. Next, you need to write an editable listbox requiring validation. And then Real Software introduces a Text class....
The Solution
The common theme of this problem is the need to validate text input. This is a task that can be handed off to an object whose sole purpose is to validate text. In other words, we can create validating editfields by
composing an editfield and a validator object; the editfielddelegates the task of validating input to a validator object.We'll still need to use inheritance to write an EditField subclass which can use validators. But it will be just one subclass requiring simple coding and offering a consistent interface; it's very easy to introduce small but annoying variations in the interfaces of several similar subclasses.
...End of Excerpt. Please purchase the magazine to read the full article.