当前位置: 首页 > 科技观察

Java8下更好地使用枚举

时间:2023-03-18 02:30:29 科技观察

在我们的云使用分析API中,返回格式化的分析数据(这里指的是生成分析图)。最近,我们添加了一项功能,允许用户选择时间段(最初只能按天)。问题是代码的时间部分是高度耦合的......例如,下面的代码:privatestaticListcreateListWithZerosForTimeInterval(DateTimefrom,DateTimeto,ImmutableSet>metrics){Listpoints=newArrayList<>();for(inti=0;i<=Days.daysBetween(from,to).getDays();i++){points.add(newDataPoint().withDatas(createDatasWithZeroValues(metrics)).withDayOfYear(from.withZone(DateTimeZone.UTC).plusDays(i).withTimeAtStartOfDay()));}returnpoints;}注意:日、分、时、周和月出现在代码的后面部分。这些代码来自Joda-TimeJava时间和日期API。甚至方法的名称也没有反映(各自的功能)。这些名称与天的概念紧密相关。我也尝试过使用不同的时间段方法(例如月、周、小时)。但是我已经看到代码中偷偷摸摸的坏开关/案例。你要知道switch/case=sin已经深入我的心里了。我在大学期间的两次实习经历中已经这样想过。因此,我会不惜一切代价避免使用switch/case。这主要是因为它们违反了开闭原则。我深信遵循这一原则是编写面向对象代码的最佳实践。我不是唯一这样想的人,RobertC.Martin曾经说过:在许多方面,开闭原则是面向对象设计的核心。遵循这一原则可以从面向对象的技术中获得巨大的好处,例如可重用性和可维护性。(http://www.objectmentor.com/resources/articles/ocp.pdf)我告诉自己:“我们可能会使用Java8来发现一些新特性,以避免出现swtich/case的危险场景”。使用Java8的新特性(不是很新,但你明白我的意思)。我决定使用枚举来表示不同的可用时间段。publicenumTimePeriod{MINUTE(Dimension.MINUTE,(from,to)->Minutes.minutesBetween(from,to).getMinutes()+1,Minutes::minutes,from->from.withZone(DateTimeZone.UTC).withSecondOfMinute(0).withMillisOfSecond(0)),HOUR(Dimension.HOUR,(from,to)->Hours.hoursBetween(from,to).getHours()+1,Hours::hours,from->from.withZone(DateTimeZone.UTC).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0)),DAY(Dimension.DAY,(from,to)->Days.daysBetween(from,to).getDays()+1,Days::天,from->from.withZone(DateTimeZone.UTC).withTimeAtStartOfDay()),WEEK(Dimension.WEEK,(from,to)->Weeks.weeksBetween(from,to).getWeeks()+1,Weeks::周,从->from.withZone(DateTimeZone.UTC).withDayOfWeek(1).withTimeAtStartOfDay()),MONTH(Dimension.MONTH,(from,to)->Months.monthsBetween(from,to).getMonths()+1,Months::months,from->from.withZone(DateTimeZone.UTC).withDayOfMonth(1).withTimeAtStartOfDay());privateDimension<时间戳>维度;privateBiFunction<;DateTime,DateTime,Integer>getNumberOfPoints;privateFunctiongetPeriodFromNbOfInterval;privateFunctiongetStartOfInterval;privateTimePeriod(Dimensiondimension,BiFunctiongetNumberOfiodger,NgetPReableInteger,FunctionPReadin,函数getStartOfInterval){this.dimension=dimension;this.getNumberOfPoints=getNumberOfPoints;this.getPeriodFromNbOfInterval=getPeriodFromNbOfInterval;this.getStartOfInterval=getStartOfInterval;}publicDimensiongetDimension(){returndimension;}publicintfromPointTimes;}publicintgetNumberDateTimeto){returngetNumberOfPoints.apply(from,to);}publicReadablePeriodgetPeriodFromNbOfInterval(intnbOfInterval){returngetPeriodFromNbOfInterval.apply(nbOfInterval);}publicDateTimegetStartOfInterval(DateTimefrom){returngetStartOfInterval.apply(from);}}通过枚举,我举修改代码,允许用户给图表数据点指定的时间段最初是这样调用的:for(inti=0;i<=Days.daysBetween(from,to).getDays();i++)变成这样调用:for(inti=0;i

最新推荐
猜你喜欢