Object-Oriented Design – Role and Importance of Static Methods in OOP

conceptslanguage-designobject-orientedobject-oriented-designtdd

Background

Thinking about OOP I feel that it binds data and behavior together, taking the real world example we already have array data type which is a collection of homogeneous type and in Java we have build a nice abstraction over it hence, we have methods like clone which does its job perfectly i.e. we have data and we have associated an operation to it making client code simple and logic of clone encapsulated behind a nice API.

Hopefully I am correct till now.

Question

So, suppose we need to sort an array, it would be good to have sort method exposed as the API which does sorting on the array elements whose ordering is based on the element type which seems perfect but wait I see no such methods on Array ADT and here comes the confusion we have page full of documentation here which lists a number of static methods. If I remember properly it is a most hated pattern in TDD community to have static methods because it makes testing a hell, even we ignore their concern then also I see a violation of OOP concept here, we already have data then why not have all these methods in the array itself?

Update

The presence of Array example here doesn't mean that I am confused about the Array in Java, my main concern is regarding the static method in general. Normally I get myself in the situation where I think it would be best to have a static method but many times I have seen community go against it hence there should be a solid reasoning about whether my design is flawed or static method is the best alternative in that situation.

Best Answer

This is a Java-specific design. For example in D, sort is an instance method on arrays, not a static method as in Java.

But in Java arrays are special. They are defined as objects, but they are not instances of classes. The only instance methods they have are the ones inherited directly from Object. There are no Array-specific instance methods since there is no Array class where they could be defined. (Note that the Arrays class you link to is just a utility class - arrays are not instances of this class.)

A more logical design would be to have arrays be instances of the class Array<T>, but since the initial version of Java did not have generics, this design was not possible.

On the generic lists (like List<E>) the sort method is an instance method. So we can conclude the designers of Java agrees sort should ideally be an instance method, but it was not possible for Arrays due to limitations in the core language design.

In C# a different design was chosen, and arrays are actually instances of an Array class, which allows array-specific instance methods (Sort is still defined as static though, for whatever reason).

In short: Arrays in Java are not "true" OO, so they cannot confirm to OO design principles.