Search code examples
javadesign-patternsnaming-conventions

naming convention: What is the difference between "from" vs "of" methods


From naming conventions and usability: What is the difference between "from" vs "of" methods in a class? when to create each one?


Solution

  • Conversion, possible loss of information

    See the guide Method Naming Conventions posted as part of the java.time tutorial provide by Oracle.

    To quote:

    of

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

    … and …

    from

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

    For realistic examples, see the java.time classes such as LocalDate, LocalTime, Instant, OffsetDateTime, ZonedDateTime, LocalDateTime, and so on.

    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() ;
    

    See code run live at IdeOne.com.

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