Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface Design - Are there naming conventions for access methods? [closed]

Tags:

java

naming

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?

like image 968
Ralph Avatar asked Jul 20 '16 20:07

Ralph


People also ask

What is the naming convention for interface in Java?

Interface names should be capitalized like class names. Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.

How are interfaces named?

Network interface names are based on whether the interface is a physical or virtual network interface. Physical interfaces are assigned names based on the slot number of the adapter. Interface group names are user specified. VLANs are named by combining the interface name and VLAN ID.

How do you name an interface class?

Naming Interfaces Interfaces should be in the title case with the first letter of each separate word capitalized. In some cases, interfaces can be nouns as well when they present a family of classes e.g. List and Map .

What is the naming convention for classes?

Class names: concatenated words each starting with upper case. Objects: lower case separated by underscores. Ivars: lower case separated by underscores.


Video Answer


3 Answers

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.

like image 110
Mureinik Avatar answered Oct 06 '22 22:10

Mureinik


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/

like image 24
Alexander Petrov Avatar answered Oct 06 '22 22:10

Alexander Petrov


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();
like image 20
Basil Bourque Avatar answered Oct 06 '22 23:10

Basil Bourque