Java SE 8 comes with a new mechanism for dates, introducing LocalDate
, LocalTime
and LocalDateTime
classes to represent instants of time. To manipulate such instants, a set of methods are given: LocalDate.plusDays(...)
, LocalDate.minusDays(...)
and so on.
I've always thought that good practice was naming methods after verbs describing their purpose, as methods are, actually, operations to be executed, something that will perform an action. Just to mention, if you consider classes like StringBuilder
, for instance, methods' names are append
, insert
, delete
…
This is why to me it doesn't sound right naming a method plusDays
instead of sumDays
, minusDays
instead of subtractDays
. It's just me finding it very annoying? What do you think?
The only reason I can think of is that dates are immutable objects, so by calling plusDays
you're not adding days to the original object but creating a new one with new properties, but that's very very subtle.
Best Answer
This is exactly the reason. Imagine you had some kind of api for manipulating ranges of dates for scheduling purposes. It might expose methods letting you make a statement like:
This reads very similarly to the English statement: "The workday schedule is the initial schedule without weekends". It doesn't imply changing the initial schedule, it implies the work schedule being a different, new thing.
Now instead imagine it was named:
This is confusing. Is initial schedule being modified? It certainly sounds like it, because it sounds like we're removing weekends from it. But then why are we assigning it to a new variable? Although these two naming schemes are very similar, this one is much less clearly evocative of what's happening. This would be more appropriate if
removeWeekends
did change the initial schedule, and returned void- in which casewithoutWeekends
would be the confusing option.This is essentially a declarative vs. imperative distinction. Are we declaring that the
workdaySchedule
is a particular thing, or are we carrying out a list of imperative instructions (like "remove") to make that particular thing? Usually, imperative naming makes more sense when you're mutating values, and declarative makes more sense with immutable values, as the above example demonstrates.In your case, you have exactly the same thing. If I saw:
tomorrow.plusDays
, I wouldn't imagine thattomorrow
was being mutated, whereastomorrow.addDays
, I'd think it might be. This is somewhat subtle- but not necessarily in a bad way. Without having to think about it too hard, this naming naturally sets your thinking along the right lines in terms of whether or not you're mutating. To make this distinction between these imperative and declaritive styles clearer: "add" (and "remove") are verbs, whereas "plus" (and "without") are prepositions.