我的域对象是否应该具有isValid()方法以返回对象的当前状态? [英] Should my Domain Objects have an isValid() method to return the current state of the object?

查看:84
本文介绍了我的域对象是否应该具有isValid()方法以返回对象的当前状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近将表单数据验证移到了模型层,特别是在域对象设置器中(这是对还是错?).当我在User服务中并且执行此操作

I have recently moved my form data validation to the Model layer, specifically in the Domain Objects setters (is this right or wrong?). When I am in my User service and I do this

$user->setFirstName($firstName);

并且输入太长(超过25个字符),我应该在Domain Object中将某种state变量设置为不稳定(也许= 0),并在Model中设置错误消息以在View中进行检索吗?

and the input is too long (over 25 chars) should I set some sort of state variable in the Domain Object to unstable (maybe = 0) and set the error message in the Model for retrieval in the View?

我将通过运行isValid()方法检查视图中对象的状态.

I would check the state of the object in the View by running the isValid() method.

这是正确的方法吗?

谢谢.

推荐答案

这更多是关于体系结构的问题,并且有很多答案. Grails网络框架对此采取了类似的方法,但是自动将validate()添加到域对象. CodeIgniter是否让您推出了自己的类似游戏.

This is more of an architectural question, and there are many answers. The Grails web framework takes a similar approach to this but auto-magically adding validate() to Domain Objects. CodeIgniter has you roll your own similar.

就我个人而言,我喜欢将验证逻辑放入设置器/构造函数中,如果不满足我的先决条件,则抛出异常.这意味着用户必须确保他们输入有效数据或在不有效时进行显式处理,而不是通过查看对象来查看其是否有效.

Personally, I'm a fan of putting validation logic in setters/constructors and throwing exceptions if my preconditions aren't met. This means that rather than having an object your views have to interrogate to see if it is valid, your users must ensure they enter valid data or explicitly handle when they don't.

这篇关于我的域对象是否应该具有isValid()方法以返回对象的当前状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆