The use case
We want to create a component that lets the user create a url of any kind with an intuitive interface. For now we support two url kinds: telephone and mailto. Telephone urls look like tel:0411223341 and mailto's look like mailto:me@gmail.com?subject=my%20subject&body=my%20body.
We want to have a select which lets the user choose which kind of url they want to construct, and then we want the appropriate input(s) to appear to enable them to construct the URL. In the case of a telephone url, we would just have the user enter a number into an input and upon hitting save we would prepend tel: to the value. With a mailto url, we'll have three inputs, one for the email address, one for the subject and finally one for the body. Upon save we would combine those values to create the mailto url.
The problem
Upon pressing the save button in the parent component, we need to know whether the resultant url is valid, based on the value of the input(s) in the child component. For example, if we're constructing a telephone url and it contains an alphabetical character, we would refuse to save the url.
Solution 1: Two switch statements
type UrlType = 'email' | 'telephone';
const Form = () => {
const [urlType, setUrlType] = useState<UrlType>('telephone');
const [url, setUrl] = useState<string>('');
const [error, setError] = useState(false);
const clearError = () => setError(false);
const isValid = (() => {
switch (urlType) {
case 'email':
return isEmailUrlValid(url);
case 'telephone':
return isTelephoneUrlValid(url);
}
})();
...
const subForm = (() => {
switch (urlType) {
case 'email':
return (
<EmailForm
url={url}
setUrl={setUrl}
onSave={onSave}
onBlur={validate}
error={error}
clearError={clearError}
/>
);
case 'telephone':
return (
<TelephoneForm
url={url}
setUrl={setUrl}
onSave={onSave}
onBlur={validate}
error={error}
clearError={clearError}
/>
);
}
})();
return (
<div>
<select
value={urlType}
onChange={event => {
setUrlType(event.target.value as UrlType);
setUrl('');
}}
>
<option value="email" label="email" />
<option value="telephone" label="telephone" />
</select>
{url}
{subForm}
<button onClick={onSave}>Save</button>
</div>
);
One way to enable this behaviour is to have all the validation code live in the parent component, and have a switch statement on the url type (e.g. telephone/email/etc) which will determine how to validate the url. We would then also have a switch statement on the url type determining which child component we should render
Pros:
- Allows us to support unforseen new use cases easily because we're not locked into an abstraction (see solution 2 below)
Cons:
- Two switch statements is a code smell that we could be using polymorphism instead
- Validation logic is not properly paired with rendering logic
- parent component is quite bloated
- Supporting a new url type requires updating both switch statements as well as the permitted type for our
url state variable. A developer could easily forget to do one of these things leading to bugs.
Solution 2: Polymorphism with validation outside child components
This isn't really polymorphism as you would find in OO programming but it's close enough. The idea is to have a SubForm interface like so:
interface SubForm {
isValid: (url: string) => boolean;
component: React.FC<SubFormProps>;
}
const subForms = {
email: {
isValid: isEmailUrlValid,
component: EmailForm,
},
telephone: {
isValid: isTelephoneUrlValid,
component: TelephoneForm,
},
};
type UrlType = keyof typeof subForms;
const Form = () => {
const [urlType, setUrlType] = useState<UrlType>('email');
const subForm = subForms[urlType];
const SubformComponent = subForm.component;
const isValid = subForm.isValid(url);
...
return (
<div>
<select
value={urlType}
onChange={event => {
setUrlType(event.target.value as UrlType);
setUrl('');
}}
>
{Object.keys(subForms).map(key => (
<option key={key} value={key} label={key} />
))}
</select>
{url}
<SubformComponent
url={url}
setUrl={setUrl}
onSave={onSave}
onBlur={validate}
error={error}
clearError={clearError}
/>
<button onClick={onSave}>Save</button>
</div>
);
With this approach, supporting a new url type is as simple as creating a new component, a new validator function, and adding to our subForms array.
Pros:
- no more switch statements
- easy to extend
- validation and rendering is now explicitly paired via SubForm interface
Cons:
- validation is purely a function of our resultant url and only returns true/false: but we may want specific validation errors to appear on a per-input basis in our SubformComponents (e.g. the email address value is malformed in our EmailForm). If we have our validation functions return information that's only relevant to the corresponding SubformComponent, it begs the question of why we don't just have the validation handled inside the SubformComponent itself
Solution 3: Polymorphism with validation inside child components
With this approach, we move our isValid functions inside the child components themselves so the parent no longer needs to worry about how specifically to validate a url. This makes for better cohesion, but means we need to do some extra work to tell the parent component whether the url is valid upon clicking the save button.
Now our SubForm interface just contains the component:
interface SubForm {
component: React.FC<SubFormProps>;
}
const subForms = {
email: {
component: EmailForm,
},
telephone: {
component: TelephoneForm,
},
};
And our isTelephoneUrlValid function can be moved inside our TelephoneForm component: