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
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.
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
- Dedupe the Menu Renderer Easy Pro Starters, mains and desserts, rendered by three identical loops.
- Dedupe the Statistics Easy Pro Min/max/avg computed three times over three arrays.
- Split the JSON Writer Hard Pro The same string-escape block pasted for keys and for values.
- Tame the Elevator Hard Pro SCAN scheduling with two pasted min/max scans full of flags.