【发布时间】:2015-01-26 01:08:09
【问题描述】:
据说Java应用程序有过度请求当前时间的习惯。这是我十多年前写的一段代码:
public class Event {
public String name;
public Date startTime;
public Date eventStartTime;
public Date presaleStopTime;
public Date presaleStartTime;
/** Specific start time set? */
public boolean isPresaleNotYetStarted() {
if (presaleStartTime == null) { return false;}
Date now = new Date();
return now.before(presaleStartTime);
}
/** Specific end time set? If not, presale starts immediately */
public boolean isPresaleTerminated() {
if (presaleStopTime == null) { return false; }
Date now = new Date();
return now.after(presaleStopTime);
}
Date getLatestPossibleShipmentDate() {
Date now = new Date();
Calendar c = Calendar.getInstance();
c.setTime(eventStartTime);
c.add(Calendar.DAY_OF_MONTH, -5);
return c.getTime();
}
/** The ticket can still be delivered to the customer */
public boolean isShipmentPossible() {
Date now = new Date();
return now.before(getLatestPossibleShipmentDate());
}
public boolean isTicketInPresale() {
return isShipmentPossible()
&& !isPresaleNotYetStarted()
&& !isPresaleTerminated();
}
}
虽然这是一段关于可读性的完美代码,但它在可测试性、一致性和性能方面显然存在一些问题。
为了使故事更完整,下面是应用了抽象和实现隐藏思想的 Web 层的样子:
<% Event event = ...; %>
<% if (event.isTicketInPresale()) { %>
... display order button...
<% } else {
// display some meaningful reason to the customer,
// why ordering is not possible
if (event.isPresaleTerminated()) {
%>Sorry, presale is terminated<%
} else if (!event.isShipmentPossible() && new Date().before(event.startTime)) {
%>Sorry, shipment of the tickets is not possible any more.<%
} else if (!event.isPresaleNotYetStarted()) {
%>Presale not yet started, come back later<%
}
}
%>
这段代码运行时,会请求当前时间大约8次,最坏的情况。
对此有什么好的最佳实践解决方案或实施模式?
我也用 J2EE 标记了这个问题,因为这可能是业务应用程序中的常见问题。
【问题讨论】:
标签: java performance date jakarta-ee time