Say I have a SSN field in a form. I want SSN to be in format of xxx-xx-xxx.

I may just have a SSN formatter checking whether the input are all digits and adding dashes when necessary.

Another option is to have both SSN formatter and validator. SSN formatter doesn't check type or range, so it accepts asdfghjkl and formats to asd-fg-hjkl. Then regular expression validator kicks in, telling me the input doesn't matach pattern \d{3}-\d{2}-\d{3}.

I find some formatting libraries have built-in validation functions, eg. formatter.js and FieldKit.

If formatter does both formatting and validating, is it single responsibility?

  • 2
    SRP doesn't mean what you think it means. – Robert Harvey Oct 15 '15 at 0:22
  • @RobertHarvey So what does SRP mean? Too long to explain here, right? – Gqqnbig Oct 15 '15 at 17:09

The Single Responsibility Principle applies to classes of objects.

Robert Martin defines a "responsibility" as "a reason for the class to change," which basically means that a class can do more than one thing, so long as those things are related. For example, a data access class might have Create, Read, Update and Delete methods, but that doesn't mean it has four responsibilities, only one: that of data access.

Ergo, it's entirely reasonable for formatting and validation to be in one class, as both activities relate to the responsibility of managing UI input.

SRP goes hand-in-hand with the Open/Closed principle, which states that a class should be "open for extension, but closed for modification." Classes which adhere to SRP are easier to extend, because you're not dealing with multiple responsibilities but only a single one.

Further Reading
Single Responsibility Principle
Open/Closed Principle

  • Ok, makes sense. Is it really a good idea to format while validating? I think separating into two steps is clearer and easier to implement and maintain . – Gqqnbig Oct 15 '15 at 21:58
  • Then do it that way. – Robert Harvey Oct 15 '15 at 22:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.