Input Kludge Anti-Pattern

As an anti-pattern, input kludge describes a poor user interface that either rejects or incorrectly handles valid input.

How to Identify

The most obvious code smell that may point to this pattern is ad-hoc input validation routines.

Look for:

  • JavaScript validation function defined directly in web page or view code.
  • Server-side validation routine defined in the presentation layer or the controller.

Example

$('form').on('submit', function(event) {
    if (!(/^.*@.*\.(com|edu|net|org)$/g.exec($('#email').val()))) {
        alert('You must enter a valid email address.');
        return false;
    }
})


Our first indication that there might be a problem is that the validation routine (regex in this case) is defined ad-hoc for this specific input. This doesn’t immediately mean there is a problem, but this is a code smell that means we should investigate more.

Upon investigation, it is pretty clear that this is definitely an input kludge. Any valid email addresses with a less common domain suffix (email@ddress.us, for example) would be rejected.

Furthermore, invalid email addresses would pass (@.com, for example).

Solution

The solution to this (and most input kludges) is to use a shared, widely used and thoroughly tested library for all of your standard validation.

Here is our example refactored using a fictional validation library (that has been thoroughly tested, of course):

$('form').on('submit', function(event) {
    if (!$.isValid.email($('#email').val())) {
        alert('You must enter a valid email address.');
        return false;
    }
})

Exceptions

There are situations when the hallmarks of this anti-pattern are actually beneficial or necessary.

For example, if you have a form input which has custom business rules to define validity, then a custom validation routine is necessary, but should be implemented as a standard validation routine in the model/business object or as an extension to a standard library, not ad-hoc in the presentation layer. See below:

$('form').on('submit', function(event) {
    if (!(/^(opossum|koalas|kangaroo|walaby)$/g.exec($('#nameonemarsupial').val()))) {
        alert('That animal is not a marsupial!');
        return false;
    }
})

Input Kludge (doesn’t accept valid entries like wombat, also wallaby is misspelled)

$('form').on('submit', function(event) {
    if (!$.isValid.marsupial($('#nameonemarsupial').val())) {
        alert('That animal is not a marsupial! Try again!');
        return false;
    }
})

Refactored Validation (validation library extended.) Hint: the validation routine calls a web-service to get complete list of marsupials.

One Response to “Input Kludge Anti-Pattern”

Leave a Reply