Skip to main content

Pure functions in JAVA



Pure function:

A pure function is a function, where

1. The return value only depends on its arg and always return the same value for the same argument. 
2.  They do not have any side effects.
3. They do not modify arguments, which are passed to them.

Example of a pure function:


Below are not a pure function:

Example 1:


public static  int count=0;
public static int getCount() {
return count++;
}

 Here getCount() returns different value on each invocation.
 Hence it's not a pure function.



Example 2:


private static int count=0;
public static int getCount() {
return count;
}

Even though the getCount method return 0 in every invocation it is not dependent on its argument(s), which is inface in this case is void. Hence its not a pure function. 


Example 3:

public List addItem(List list,Integer i{
list.add(i);
return list;

}



Modifies the argument. Hence it has a side effect. 
To make it pure function you can write code like this









Comments

Popular posts from this blog

About this blog

This blog is mainly for developers who are passionate about programming and new tech. Though as the name suggests most of the posts are going to focus java but many posts will focus on common design problems which will be programming language independent. So without further delay let's dive into it .. :) 

Write a RequestQueue In Java

Let's say you have a client-side application. It can be an android application or it can be your java application which invokes 3rd party API internally. And let's say for n number of reasons which are mentioned below, you want to throttle down number API request a time. How do you do it? Simple! You need to implement a Request Queue. What is it? As the name suggests, it's a queue of Http request. There is a dispatcher thread, which controls how many threads to be executed at a time. It has other functions as well which we are going to discuss later. Is there an existing implementation ? Yes, android has Volly library  which has it's own implementation of request queue . However here we will implement a  simpler version of request queue.