Skip to content
Katabench
Try free

Dedupe the Field Validators

Easy About 10 min Free, no account needed

Three fields, three identical validation blocks.

The brief

Validate(username, email, phone) checks the three fields in that order and returns the first problem found, or "ok":

  • an empty (or null) value → "<field> missing";
  • longer than 20 characters → "<field> too long".

The same six lines appear three times, with only the field name changing.

Refactor without changing behavior until every gate passes: one Check(value, fieldName) helper called three times.

Starter code

C#
using System;

public class Solution
{
    // First validation error, or "ok". Copy-paste, paste, paste.
    public string Validate(string username, string email, string phone)
    {
        var value = username;
        var field = "username";
        if (string.IsNullOrEmpty(value))
        {
            return field + " missing";
        }
        if (value.Length > 20)
        {
            return field + " too long";
        }

        value = email;
        field = "email";
        if (string.IsNullOrEmpty(value))
        {
            return field + " missing";
        }
        if (value.Length > 20)
        {
            return field + " too long";
        }

        value = phone;
        field = "phone";
        if (string.IsNullOrEmpty(value))
        {
            return field + " missing";
        }
        if (value.Length > 20)
        {
            return field + " too long";
        }

        return "ok";
    }
}

How it is graded

Behavioral tests have to stay green while the grader measures complexity, nesting, method length, and duplication from your source.

C# refactoring exercises →

Related guides

What it practices

Remove duplication
Extract the shared shape of pasted blocks and keep the real differences visible.
Extract method
Pull named steps and named conditions out of a long method so each piece does one thing.

Related katas