Rylander
Rylander

Reputation: 20179

Can a Constructor Use a Builder

I am refactoring a class to use a builder with a private constructor instead of public constructors. I want to have the old, deprecated, public constructors use the builder as shown below. (this is an example of the behavior I am try to achieve)

// old public construcor
@Deprecated
public MyClazz(){
    return new MyClazzBuilder().Build();
}

This give a "Cannot return a value from a method with void result type"

Is this type of functionality possible in Java? How could this be achieved?

Update: This code is part of a distributed jar, deleting the old constructors is not an option because I need to maintain backwards compatibility

Upvotes: 1

Views: 207

Answers (2)

Mel Nicholson
Mel Nicholson

Reputation: 3225

No. Constructors operate on an object, they don't return it. [footnote 1]

One way to get this sort of functionality is with an init() method.

@Deprecated
public MyClazz() {
  init();
}

public void init() {
  // do the actual work
}

Now your builder can call the same init() method to avoid having the code in two places.

Because you are keeping the deprecated signatures around, it's hard to avoid splitting the logic for preparing an instance into multiple places. That's not ideal, but it's the price of deprecation and maintaining backwards compatibility.

[footnote 1] The lifecycle of a java object is that first the object memory is allocated, but all the fields have junk content. Next a constructor is run on the memory to get it into a consistent state by changing all those meaningless values into real values. Note that the memory the constructor works on is already there, so you can never substitute another object in place of the one being constructed. A return value from a constructor would be exactly this sort of substitution, which is not supported by the language. If that trick is needed use a factory/builder instead of a constructor -- constructors can never do that.

Upvotes: 3

Woot4Moo
Woot4Moo

Reputation: 24336

Constructors don't return values. Notice how there is no "declared" return type in a constructor signature. You have a few options:

1) Mark the constructor private and resolve compilation errors immediately
2) Deprecate the constructor, and leave the original implementation there.

I recommend number 2. What you have done is deprecate a constructor, and then changed the implementation. That is not how deprecation works.

Upvotes: 1

Related Questions