【问题标题】:naming convention: What is the difference between "from" vs "of" methods [closed]命名约定:“from”与“of”方法有什么区别[关闭]
【发布时间】:2021-05-24 23:33:44
【问题描述】:

从命名约定和可用性: 类中的“from”与“of”方法有什么区别?什么时候创建每个?

【问题讨论】:

  • 为什么这是基于意见的?随着使用范围的扩大,我们在这个相当重要的话题上达成了越来越多的共识。
  • @BasilBourque,如果这个问题是在 Java 日期时间 API 的上下文中专门提出的,那么您的回答将是权威的。就目前而言,没有通用标准,甚至没有约定,程序员可以期望在所有 Java 中找到。每个公司甚至每个团队都会定义自己的约定,负责日期时间的 Oracle 团队也是如此。

标签: java design-patterns naming-conventions


【解决方案1】:

请参阅作为 the java.time tutorial 的一部分发布的指南 Method Naming Conventions,由 Oracle 提供。

引用:

of

创建一个实例,其中工厂主要验证输入参数,而不是转换它们。

……和……

from

将输入参数转换为目标类的实例,这可能涉及丢失输入中的信息。

有关实际示例,请参阅 java.time 类,例如 LocalDateLocalTimeInstantOffsetDateTimeZonedDateTimeLocalDateTime 等。

LocalDate x = LocalDate.of( 2021 , Month.MARCH , 27 ) ;  // Directly injecting the three parts of a date (year, month, day) without any need to parse or process the inputs other than basic data validation such as day within appropriate range of 1-28/31 for that year-month.

ZoneId zoneId = ZoneId.of( "Africa/Casablanca" ) ;       // This string is the official name of this time zone. Can be mapped directly from name to object, with no real processing, parsing, or conversions involved.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;
LocalDate y = LocalDate.from( zdt ) ;                    // Converting between types. Data loss involved, losing (a) time-of-day and (b) time zone.
LocalDate z = zdt.toLocalDate() ;

code run live at IdeOne.com

x.toString(): 2021-03-27
y.toString(): 2021-05-25
z.toString(): 2021-05-25

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2014-09-18
    • 2010-12-16
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2014-06-11
    • 2011-11-30
    相关资源
    最近更新 更多