Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Using C#/.Net, I have a page where the user can enter data and save these data by clicking a button.

To save data, the user needs to enter a valid date, this means a date which has a certain format.

The page contains amongst others two modules.

The ValidateDate-Event has the responsibility two check the format of the date-field. So it checks the format and displays a message if the date is not well formed.

The Save-Event has to save user entries. To successfully complete the task, a well formed date is needed. So I designed the module to check the date format. This has the advantage that the module can never crash and is not dependent of the Validation-module. But I realized that in fact I do the same thing twice, in two modules.

I am just curious, how do you handle this matter? What do you think is the best way to do it?

1) ValidateDate

Reponsibility: Check format of date field (, inform user)
Sub-Task: Check format of date field

2) Save

Reponsibility: Save data
Sub-Task: Check format of date field

share|improve this question

closed as too broad by Thomas Owens Jul 16 '15 at 12:01

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

up vote 10 down vote accepted

Doing the same thing twice is nearly always a bad idea. (see DRY) You have to change it in two places if your validation changes increasing your chance of bugs.

My advice would be have both Save and Validate call another method that validates the input. Its still a good idea to check on save as well as validate as you should never trust user input. They could for example be malicious or there could be some bizzare browser bug causing/allowing them to submit bad data.

share|improve this answer
+1 In short, refactor date format check to another method. – Lionel Oct 18 '11 at 10:58

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