What does the programming term "identity function" have to do with identity? (Java-oriented)

1.4k Views Asked by At

I just read Bloch's Effective Java and there was one section talking about an "identity function" in the Generics chapter.

public interface UnaryFunction<T> {
    T apply(T arg);
}

// Generic singleton factory pattern
private static UnaryFunction<Object> IDENTITY_FUNCTION = new UnaryFunction<Object>() {
    public Object apply(Object arg) { return arg; }
};

// IDENTITY_FUNCTION is stateless and its type parameter is
// unbounded so it's safe to share one instance across all types.
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
    return (UnaryFunction<T>) IDENTITY_FUNCTION;
}

I already read "Why is it safe to suppress this unchecked warning?" and the answers explain the unchecked warning question, but leave me totally unhappy with the concept of the "identity function" when it seems the identity function has nothing to do with identities.

Bloch just assumes I know what it is, but in the implementation he uses to illustrate it, it has nothing to do with identity or identities.

I checked it out on wikipedia: Identity Function @ wikipedia but the pure theoretical description of it tells me nothing about what it has got to do with identities either.

I searched on google, and some people refer to the .equals() and .hashCode() methods as identity functions which makes a bit of sense, but of course their implementation is completely different from Bloch's method which returns the input parameter untouched. What does that have to do with identity?

Other people talked about database functions as identity functions, giving a new ID on each call, which makes more sense as well, but is obviously very limited in scope.

2

There are 2 best solutions below

2
On

An identity function, in the context of the code in your question, is simply a function that returns the same argument passed to it :

In math you can denote it as:

f(x) = x
2
On

Identity functions are similar to other "identity" concepts, i.e. an operation that effectively does nothing.

As an example: in math you have identity matrices which if multiplied with a vector/matrix result in the same vector/matrix as if the multiplication never happend.

The same applied to an identity function: it returns the parameter as is and effectively does nothing when it comes to logic. It's as if the function never had been called - as I said from a logic point of view, you might still see some technical impact, e.g. a few instructions being executed.