Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention for marking methods as pure functions in Java

Reading code of some complex application I thought it could often be helpful to recognize if a method has side effects just by looking on its signature. And after inspecting some of such methods I thought it could be nice to mark them as purely functinal or not in order to make life easier for people reading this code in future.

Is there some convention in Java world (javadoc, method naming pattern etc.) which identifies method as pure function?

like image 735
ipbd Avatar asked Oct 30 '14 12:10

ipbd


People also ask

What are pure functions in Java?

The functions that do not return a value when it is invoked. Here you can observe through the highlighted part that both the functions are doing the same task but the upper one is pure as it is returning the value of f whereas the lower one is not returning anything but simply printing the value of f. What is scanner in Java ?

What are conventions in Java?

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc. But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape.

What is convention not rule in Java?

So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape. All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention.

What is main () method in Java?

As the name suggests the method is supposed to be primarily method which indeed it is as main () method in java is the method from where the program begins its execution.


1 Answers

You have the JavaBeans Conventions. See http://docstore.mik.ua/orelly/java-ent/jnut/ch06_02.htm

. The JavaBeans framework facilitates this process by establishing naming conventions. One such convention, for example, is that the getter and setter accessor methods for a property should begin with get and set.

However, you can always javadoc or annotate your methods like for example.

/** 
 * This method is read only!
 */
@ReadOnly
public void setX(Object x)

The programmatic/safe way, would be using polymorphism, implementing "read only" and "read/write" interfaces. Related: How to create two interfaces to a Java class one read-only, one read-write?

IMO, if you dont want to mess with interfaces, the JavaBeans convention and/or the javadoc should be enough to guess what functions have side effects or not.

like image 151
Andrés Oviedo Avatar answered Oct 07 '22 09:10

Andrés Oviedo