7

I have a question about the design of a java interface concerning the naming off access-methods. Usually I use often the "get" prefix for access methods in my Interfaces, also when I have no setter methods.

For example:

public MyObject getTask(int id, String version);

I think about a lot of refactoring affecting also my Interfaces by renaming the method into

public MyObject findTask(int id, String version);

My question is: Are there any reasonable rules for deciding whether an interface method should be designed as a finder or getter method? Or is that something rather arbitrary?

Ralph
  • 4,500
  • 9
  • 48
  • 87
  • What distinction are you making between “getting” and “finding”? – Basil Bourque Jul 20 '16 at 20:52
  • Often, if `MyObject` has not been *found* for provided `id` and `version`, `getTask` *throws exception* when `findTask` just *returns* `null`. – Dmitry Bychenko Jul 20 '16 at 20:54
  • The decision between returning 'null' or throwing an Exception when no result was found, seems to be a useful criteria - thanks. – Ralph Jul 20 '16 at 21:01

3 Answers3

2

Yes "getter" of an attribute means that you directly return its value. You can also read about properties. Field access Property access.

This is more or less legacy from the JavaBeans

Finder means that you have a criteria to search for a value of interest.

example implementation

public class User{
  private List<Category> categories;

   public void getCategories() {
      return categories;
   }

   public void findCategory(String categoryName) {
       // your logic here
   }

   public void findCategory(Predicate predicate)  {
        // your logic here
   }

}

Also having getters in your interfaces might be a bad idea. It should be the opposite. It is the finder methods that are supposed to be in the interfaces.

But It depends. There is only one reason I can think of to have getters in the interfaces and it is if you are following the JavaBeans principles and at the same time you want to support multiple implementations of your beans. Which I dislike by definition.

Here you can find some interesting material over when getters should be present in the interfaces. Java Interface Usage Guidelines -- Are getters and setters in an interface bad?

Fluent API I would also recommend you to read about what is a FLUENT api. This is in the context of @Basil coming with the java.time package example. https://blog.jooq.org/2012/01/05/the-java-fluent-api-designer-crash-course/

Community
  • 1
  • 1
Alexander Petrov
  • 9,204
  • 31
  • 70
  • A method that takes arguments is by definition (as defined by Java beans) not a "getter" method, even if the method name starts with `get` or `is`. – Andreas Jul 20 '16 at 21:21
  • The author of the question has explicitly used "getter" in the headline. He has used second time getter in the question body with hyphens. – Alexander Petrov Jul 20 '16 at 21:24
2

getXYZ methods usually convey a meaning that the information they return is easily accessible by the instance. More often than not these methods just return [possibly read-only copies] of data members, or very simple manipulations of them. The behavior this notion drives is that you don't need to overthink using the method - it's cheap to call, and not worth another thought.

findXYZ methods convey a meaning that although the instance is able to retrieve this information, it's not readily available - it needs to go find it - e.g., by querying a database or a service directory. This notion drives a behavior of thinking twice and thrice before calling such a method, and making an effort to save or cache its results.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • That's a good point! But I think I've never worried about the internal implementation details when a called an access method ;-) – Ralph Jul 20 '16 at 21:05
  • +1 Especially your hint "very simple manipulations" hit it. Although getters must not contain logic does not mean that they cannot contain Collections.unmodifiable... or Optional.ofNullable-wrappers – Jan B. Jul 20 '16 at 21:05
2

tl;dr

Prefix with:

  • get… & set…
    For access to simple piece of object’s state with no side-effects or complications.
  • fetch… & submit
    When access to the object involves substantial workload, side-effects, or likely Exceptions/nulls.

No strict rules

No rules on naming such methods have been written in stone.

JavaBeans

The "get" & "set" methods are commonly used in Java in the tradition of JavaBeans spec. Usually this is intended for accessing simple parts of the object’s state, or calculated/formatted forms of that state, with virtually no side-effects. Side-effects means affecting other state or objects that might be an unpleasant surprise to the calling programmer.

“fetch” & “submit”

For myself I use the prefix "fetch" when there is a relatively heavy amount of work being done, such as database call(s), or where the values returned are quite dynamic, rapidly changing such as a data feed, or dependent on externalities that may be changing such as calls into JNDI resources. Example:
fetchCurrentMonthTimeSheets( java.time.YearMonth yearMonth )

Going the other direction, if a “set” type method is doing substantial work, or has side-effects, or is highly dynamic or somewhat unpredictable in its results, I use “submit” as a prefix. Example:
submitTimeSheetForPayroll( TimeSheet timeSheet )

I also use these where a null value or Exception is commonly possible or even likely. The get/set is for quick-simple-easy while fetch/submit is for complicated-heavy situations.

java.time conventions

The builders of the java.time framework built into Java 8 and later put much thought into their naming conventions as explained in the Oracle Tutorial. I can imagine their guidelines might be followed in other libraries.

They define eleven words with specific meanings. Some are for instance methods, some static (class) methods. The java.time classes eschew instantiating with the new command, instead use static factory methods.

Keep in mind that java.time uses immutable objects exclusively for clean logic and automatic thread-safety. Immutability is not always appropriate of course, so this list may or may not fit your own designs.

Static factory methods

  • 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.
  • parse
    Parses the input string to produce an instance of the target class.

Instance methods

  • format
    Uses the specified formatter to format the values in the temporal object to produce a string.
  • get
    Returns a part of the state of the target object.
  • is
    Queries the state of the target object.
  • with
    Returns a copy of the target object with one element changed; this is the immutable equivalent to a set method on a JavaBean.
  • plus
    Returns a copy of the target object with an amount of time added.
  • minus
    Returns a copy of the target object with an amount of time subtracted.
  • to
    Converts this object to another type.
  • at
    Combines this object with another.

Example usage

If those descriptions are vague, peruse the java.time classes to see how they are used. Here is a bit of example code using to, of, at, with, and get.

Converting from old outmoded java.util.Date class to java.time.Instant.

Instant instant = myUtilDate.toInstant(); 

Assign a time zone to get a new kind of object, ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );

Adjust to another day-of-week.

ZonedDateTime followingTuesday = zdt.with( TemporalAdjustors.next( DayOfWeek.TUESDAY ) );

Interrogate for parts: the year and month and day-of-month.

int year = zdt.getYear();
int month = zdt.getMonthValue(); // Or handy Month enum…  zdt.getMonth();
int dayOfMonth = zdt.getDayOfMonth();
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154