在API中使用java.util.Date的好原因 [英] Good Reason to use java.util.Date in an API

查看:111
本文介绍了在API中使用java.util.Date的好原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何具体的原因在API中使用Date类(例如,在员工出生日期字段中),而不是长或长。



这里有一些讨论:
java-date-vs-calendar ,但是我想特别知道如果使用日期有任何理由,当long(或Long)看起来更简单。



当然,我会使用TimeZone和SimpleDateFormatter在GUI中解析和显示日期,也可能会在Calendar中执行操作,但我只关心存储和表示日期在这个问题的数据模型/ API。



更新:一个我不选择日期的一个原因的例子是它是可变的所以如果我在我的API中公开一个Date,调用者可以调用setTime(long),这似乎是一个基本封装的违反。对我来说,这似乎超过了使用Date提供的更加清晰的好处,因为我可以调用long属性timeInMillisecondsSinceEpoch并将相同的信息传达给调用者。

解决方案

Date 类是API的一部分,如果符合您的目的,这是一个有效的选项。有许多不赞成的方法被 Calendar 类替换,所以请确保避免使用这些方法。



<答案将取决于你需要完成什么。如果您只需要按日期排序,则 long 将是足够的。一个日期值会增加一些可读性,但不会增加功能。使用 Date 也不会有害,所以应考虑可读性因素。



如果该字段将是私有的你实际上可以把它存储一段很长的时间,并且有一个getter和setter,它使用 Date

  private long mDOB; 

public Date getDOB(){return new Date(mDOB);}
public void setDOB(Date dob){mDOB = dob.getTime(); }


Are there any specific reasons to use a Date class in an API (for example, in an employee birth date field) rather that a long or Long.

There is some discussion of this in: java-date-vs-calendar, but I would like to know specifically if there is any justification for using Dates, when a long (or Long) seems so much simpler.

Of course I would use TimeZone and SimpleDateFormatter to parse and display dates in a GUI, and maybe Calendar to perform manipulations, but I am concerned only about the storage and representation of date in the data model/API in this question.

Update: An example of one reason why I would not choose Date is that it is mutable. So if I expose a Date in my API, callers can call setTime(long) and this seems to be a violation of basic encapsulation. To me this seems to outweigh the benefit of the added clarity that using a Date provides, since I could just call the long property timeInMillisecondsSinceEpoch and communicate the same information to callers.

解决方案

The Date class is part of the API and as such a valid option if it fits your purpose. There are many deprecated methods in it that were replaced by the Calendar class, so make sure you avoid using those methods.

The answer will depend on what is what you need to accomplish. If you just need to sort by the date, a long will be more than enough. A Date value would add some readability to it, but not more functionality. Using Date will not be detrimental either, so the readability factor should be considered.

If the field will be private, you can actually store it as a long and have a getter and a setter that use Date :

private long mDOB;

public Date getDOB () { return new Date(mDOB);}
public void setDOB (Date dob) { mDOB = dob.getTime(); }

这篇关于在API中使用java.util.Date的好原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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