Article:
  10 Reasons We Need Java 3.0
Subject:   Functional Methods
Date:   2002-12-16 19:14:24
From:   anonymous2
I suggest addition of functional (as in "functional programming" i. e. without side effects). This could be specified by method modifier "functional" (in the language) and by special bit in the "access_flags" field of "method_info" structure in class file (there are some unassigned bits).


A functional method should not be allowed to modify objects it did not create or obtained from other method as a return value. See example below: a method adding a number to each member of an array of integers


"Traditional approach"


void addNumber(int[] arr,int n)
{
for(int i=0;i {
arr[i]+=n;
}
}


"Functional" approach:


functional int[] addNumber(int[] arr,int n)
{
int[] arret=new int[arr.length];
for(int i=0;i {
arret[i]=arr[i]+n;
}
return arret;
}


Only functional methods may be called from functional methods, and I/O probably must be very limited for functional methods.


This corresponds to concept of modern functional languages that use monads (their way to define sequentiality) on the top level where I/O is allowed, and "regular" functions called from within monadic level that are prohibited to do I/O and any other action assuming sequentiality (a very rough description though).


Absence of side effects gives big advantages in simplifying garbage collection. Only objects referenced via return statement need to be kept; the rest of objects that might have been created by the method can be disposed of immediately upon method termination (reduces background GC job). Functional methods may even run in parallel thus giving alternative to threading. A thread running in functional mode can be safely terminated (destroyed), and an upper level method should just catch this as an exception. If object(s) a method returns are created by the method, they are not referenced from anywhere and thus can be moved safely to compact the heap.


This suggestion is drawn from my personal experience when I tried to create a straightforward implementation of JVM, and from some other Internet sources.


Dimitry Golubovsky


dimitry at golubovsky dot org

Main Topics Oldest First

Showing messages 1 through 2 of 2.

  • Functional Methods
    2004-01-07 17:52:56  anonymous2 [View]

    Why not just use a language that was functional at its inception (e.g. Haskell)?
  • Functional Methods (correction)
    2002-12-16 19:45:51  anonymous2 [View]

    Sorry, Java code in the examples does not look as expected. I'll try to use HTML tags.


    "Traditional approach"

    void addNumber(int[] arr,int n)
    {
    for(int i=0;i<arr.length;i++)
    {
    arr[i]+=n;
    }
    }

    "Functional" approach:

    functional int[] addNumber(int[] arr,int n)
    {
    int[] arret=new int[arr.length];
    for(int i=0;i<arr.length;i++)
    {
    arret[i]=arr[i]+n;
    }
    return arret;
    }
    </pre>