java - 命名约定 : What is the difference between "from" vs "of" methods

标签 java design-patterns naming-conventions

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

3个月前关闭。




Improve this question




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

最佳答案

看指南Method Naming Conventions作为 the java.time tutorial 的一部分发布由 Oracle 提供。
报价:

of

Creates an instance where the factory is primarily validating the input parameters, not converting them.


… 和 …

from

Converts the input parameters to an instance of the target class, which may involve losing information from the input.


有关实际示例,请参阅 java.time 类,例如 LocalDate , LocalTime , Instant , OffsetDateTime , ZonedDateTime , LocalDateTime , 等等。
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

关于java - 命名约定 : What is the difference between "from" vs "of" methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67680011/

相关文章:

java - java中不正确的对象创建

multithreading - 是否准确地说每个响应输入的程序都有一个无限循环的主线程?

data-structures - 一组中 "find, remove and return an element"的术语?

haskell - haskell 中的字符串与字符串?

java - 字符串 - Java 中的栈和堆

java - 将原始输入字符串保留为 CustomAnalyzer 中的标记/术语

java - 如何为默认的 Spring Boot 2 指标定义附加或自定义标签?

C#工厂模式和IoC的区别

c++ - 构建可重用代码

java - Java中方法名前的下划线是什么意思?