开发者

Should a Form object posses the dual responsibilities of displaying and processing?

I have a prototype with a Form class which auto-generates an HTML form, and now I am plugging some processing functionality into the prototype.

Should the same Form class that gener开发者_如何学运维ates the HTML for the form also process the form? Doing so would make the class have two different, distinct...yet related purposes.

Should this be one class, or should it be split into two?


Depends on what you mean by "process the form". For example, it's perfectly reasonable to create a class which has a method CreateChildForm(), and another method ProcessChildForm(form).

It's also reasonable to create forms which process themselves. e.g. Form.Process().

In other words, it depends on what you're trying to do.


In OOD, the Single Responsibility Principle generally advises that a class should only have one reason to change. The example you describe seems to clearly fall into a case where you probably don't want to mix form generation and processing.

However, in your example, you seem to have three distinct responsibilities:

  1. A structural representation of the form, complete with field definitions, etc
  2. A form-to-HTML process, that converts the form into an HTML representation.
  3. A Form-submission process, that evaluates the submitted data and produces a "filled out" form record (which may even be a fourth area of responsibility).

It's, of course, possible to mix together any number of these responsibilities together, however - I think you'll find that separating may create value, including:

  • Decoupling of implementations
  • Extensibility points for the future
  • Separation of data representation from processing actions
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜