score:1

Accepted answer

The answer is very simple.

The static read method allows you to call the method on the actual class and return an instance. So, instead of doing:

MyWritable writer = new MyWritable();
writer.readFields(input);

You can just do:

MyWritable writer = MyWritable.read(input);

And achieve the same result. It's for convenience.

Then, it returns a MyWritable because otherwise you'd never get the object! The first method can return void because you have already created an object instance, but in the latter, it has to return the instance it creates for you.

score:0

Effectively, it looks as though they are trying to create a simple entry point for reading these items instead of 'new' ing up the unknown writable. So: MyWritable.read(dataInput);

which creates an instance in memory of MyWritable (lets call it myWritable1). So then they invoke 'myWritable1.readFields' and allow it to 'read' and 'populate' itself.

MyWritable.read(dataInput) will RETURN myWritable1 (created above).

The static read method is completely unnecessary and probably not even a good idea. It makes it easy to use, but it's not really saving much work. new MyWritable().readFields(dataInput) would work just as well.

score:0

  • It returns a MyWritable so you can do stuff with it after you read, like look at the data.
  • It's static because it's a factory/convenience method.
  • The others don't because you'd already have an instance if you were calling instance methods.

score:0

In this case the read(DataInput) method is a factory method that creates a MyWritable based on some data. It has a return type because it returns the object it creates. It is static because a non-static factory method does not make much sense (how would you call a method on an object which has not yet been created?)

score:1

This design implements a very simple factory method pattern: the users would call read, rather than calling new MyWritable() followed by readFields().

To complete the factory method pattern implementation, make the constructor private, and return the constructed object by interface:

private MyWritable() {} // Disallow external instantiations

// Use the Writable interface rather than MyWritable as the return type
public static Writable read(DataInput in) throws IOException {
    MyWritable w = new MyWritable();
    w.readFields(in);
    return w;
}

Related Query

More Query from same tag