日期和货币是否应该始终作为对象传递?
帮助我解决与同事的争论...
我们使用 Zend Framework 和 PHP,我们处理的大部分数据包括日期和价格。我一直认为,当检索数据(无论是从数据库还是 JSON)时,我们应该自动立即将日期属性转换为 Zend_Date 对象,将价格属性转换为 Zend_Currency 对象,以确保我们始终使用这些属性的功能操作/比较/显示数据时的类。我的观点是,它确保了一致性,并且我们始终知道数据的形式。
我的同事认为,我们应该在检索时保留数据原样(字符串),并且仅在模型或视图中使用时创建 Zend_Date/Zend_Currency 对象。
谁是对的,为什么?
(我确信有人会认为创建对象时会有一个小的速度优化损失,但在我们的例子中这并不重要。)
Help me settle an argument with a coworker...
We’re using Zend Framework and PHP and much of the data we deal with includes dates and prices. I’ve been arguing that when the data is retrieved (either from the database or JSON) we should automatically immediately convert the date properties to Zend_Date objects and the price properties to Zend_Currency objects so as to ensure that we are always using the abilities of those classes when manipulating/comparing/displaying the data. My argument is that it ensures consistency and we always know what form the data is in.
My coworker argues that we should just leave the data as is (strings) when retrieved and only create the Zend_Date/Zend_Currency objects when used in the model or view.
Who is right and why?
(I’m sure someone will argue that there is a small speed optimization penalty in creating the objects, but in our case that is not of concern.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在面向对象中,最佳实践肯定是使用对象,因为它们封装了您期望的货币/日期的状态和行为。
我对 Zend 没有经验,但我假设日期类会进行一些检查以确保日期是有效日期或引发异常。如果等到最后一刻才将日期转换为对象,则可能会更难找到错误的来源并始终传输受污染的数据。我的防御本性希望我尽快清理并非来自已知可信来源的数据。
In OO the best practice would surely be to use objects as they encapsulate the state and behaviour of what you expect a currency/date to be.
I am not experienced with Zend but I would assume the date class would do some checking to ensure that the date is a valid date or throw an exception. If you wait until the last minute to convert the date to an object you are potentially making it harder to find the source of the bug and transporting around tainted data the whole time. My defensive nature would want me to sanitize data as soon as possible that has not come from a known trusted source.