James Raitsev
James Raitsev

Reputation: 96391

Controlling when object is created

Suppose i need to create an object as follows and set some values

    FileMetaData fileMeta = fileContainer.getMetaData();

    fileMeta.setFileName("file name");
    fileMeta.setServer("my box");
    fileMeta.setDirectory("/path/to/dir");
    fileMeta.setFileType(FileType.PROPERTIES);

I later intend to use this object reference to do something useful.

I'd like to recognize the fact that it is possible for the user of the system to not set some fields, for instance, one may forget to

    fileMeta.setDateModified(12345);

Is it somehow possible to guarantee that all (or some specific) fields are set before making the object available?

Upvotes: 1

Views: 46

Answers (3)

AlexR
AlexR

Reputation: 115328

Basically I can classify the following 3 ways.

First is based on the class itself. You can add method isReady() to your class. This method will perform all checks and return true or false.

Other way is to use Factory or Builder pattern and probably objects repository. Both factory and builder guarantee to create object in ready state. Repository can be used to "publish" ready objects there, so other code requests objects and receives them in ready state only.

Other approach is to use Wrapper (Decorator) pattern.

interface Foo {
    public void foo(); //business method
}

class FooImpl implements Foo {
    public void foo(){} // does the work
}


class FooDecorator implmeents Foo {
    Foo foo;
    public void foo(){
        if (isInitialized()) {
            foo.foo();
        }
        throw IllegalStateException("Not initialized");
    } 
}

This solutions may be implemented using dynamic proxy or using AOP framework as well.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

There is nothing in the language to enforce this (except for having a lone visible constructor that takes all the required parameters), but you can do it idiomatically, with a variation on the builder pattern and some method chaining:

FileMetaData fileMeta = new FileMetaDataBuilder(fileContainer.getMetaData())
    .setFileName("file name")
    .setServer("my box")
    .setDirectory("/path/to/dir")
    .setFileType(FileType.PROPERTIES)
    .build();

The build() method can ensure that all the required fields are set before calling the appropriate constructor of FileMetaData with all the required parameters.

Upvotes: 2

Jeff Watkins
Jeff Watkins

Reputation: 6359

Use the builder pattern and pass the reference to the builder around. When you're done adding extras on top, call .build and capture the returned instance of FileMetaData.

You could constrain it by not allowing the build to succeed until all of the pre-requisites are set.

Upvotes: 1

Related Questions