Is a static builder incompatible with inheritance?

Started by
1 comment, last by TheChubu 11 years, 1 month ago

Hi! So I have this copy of "Effective Java" and right at the beginning there is the description of a static builder class.

Say you have a class that has many parameters, and most of them are optional parameters. So making several constructors with all the different combinations of parameters becomes a lot of work.

Instead you make a single private constructor with all the parameters and a static nested class (a "builder" ) that has methods for setting up each parameter and a build method that constructs a new instance of the object once you have set up the parameters you want.

It would be something like this:

[spoiler]

    public class OuterClass
    {
        mandatory params
        optional params
        
        static class Builder 
        {
            //builder can hold all the data to construct an OuterClass
            mandatory params
            optional params
            
            public Builder(params)

            {
                this.mandatoryparams = params;
            }

            
            public optionalParam (param) 
            {
                this.param = param;
                return this;
            }
 
           //few more of optionalParam methods.
 
            public OuterClass build()
            {
                return new OuterClass(mandatoryParams,optionalParams);
            }
        }
    }
[/spoiler]

I've implemented this with my Mesh class. Since it has many parameters and several configurations (normals, no normals, indexed, non indexed, etc).

So for instancing a Mesh object i'd call

Mesh lamp = new Mesh.Builder([mandatory parameters]).indices(lampIndices).normals(lampNormals).build()

and I'd get an indexed lamp model with normals without calling the constructor with 15 or so parameters. Each Builder method returns the builder itself so you can "concatenate" method callings.

This is all and great until I need more specific functionality out of my mesh objects. I wanted to implement conventional character movement (ie, not a floating camera) and for that I need to retrieve positions from the ground. For that I'd need to add some methods to the object that holds my terrain data, say, a new MeshTerrain class that inherits from Mesh.

It seems that the static factory wouldn't allow me to subclass Mesh at all, given the private constructor. And even then I'm not sure how that would work, could MeshTerrain use Mesh static builder?

And I have another question. I don't understand exactly the business with the nested static class.

For example, by making the call "new Mesh.Builder()" what I am exactly instantiating there? A Builder object? How that could be if its an static class? How the static Builder class can have a constructor? Or am I instantiating an enclosing Mesh object? But then, wouldn't that mean I'm instantiating two Mesh objects since I call "new Mesh" in the build() method?

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

Advertisement

In Java, inner classes contain an implicit reference to the enclosing class (and this is why they are instantiated via this, or an instance). Static inner classes, on the other hand, behave exactly as inner classes in most other languages, and they do not contain an implict reference to the enclosing class. Thus, they are created just by their name (either new Builder() inside Mesh, or Mesh.Builder(), which is the only way to access the Builder class, as it is inner to Mesh. You could say that a class behaves like a package for its static content, including static inner classes). Note that I'm not talking about anonymous inner classes.

Let's go back to your case. If you want to inherit Mesh, you should change your constructor to be protected, so that it can be accessed via the inheritor.

And about the Builder pattern. Like any design pattern, it should be understood and applied. This means that patterns are a means to an end, and are not religion to be followed blindly. I'd take the Mesh builder class and make it a regular class, not an inner static class, and I'd call it MeshBuilder. Then I'd have MeshTerrainBuilder, which would inherit from MeshBuilder. Thus you'd have clear inheritance path, and would be able to override the builder behaviour.

I hope this is clear enough. I think that Effective Java is one of the best programming books I've read... but don't accept everything on faith just because Bloch is saying it.

And about the Builder pattern. Like any design pattern, it should be understood and applied. This means that patterns are a means to an end, and are not religion to be followed blindly.

Yes but patterns have very defined advantages and disadvantages. Most of the time by modifying the pattern myself I'm invalidating most of their advantages. One for example is that if you use the Builder as it is, you just can't create an unusable object unless you deliberately try to do so (ie, passing null to a mandatory parameter, and even then you can make a check somewhere and plain refuse to create the object).

That is not so much of a problem by me, I know what the mandatory parameters are, its my code, but you can see my point here.

Thanks for the input. So even if its static it needs to be instanced because its enclosed in another class. I think some of the "every file is a class" thing () is little weird sometimes.

Turns out that it's even more complicated than I had hoped. I made the constructor protected like you said, extended Mesh, and inside it, extended Mesh.Builder. I thought that I could just override build() and I'd be set up but it turns out that the builder stops working as it should.

See, if I call MeshTerrain.Builder(params).normals(params).build() it will fail since the inherited normals(params) returns a plain Mesh, not a MeshTerrain, when I call the build() it will construct a plain Mesh object. So I'd need to override every Builder method, call its superclass method, and cast the result to MeshTerrain so it works.

That would be cumbersome though. For every change in the parameters of the superclass I'd need to update every subclassed Builder (basically, re implementing it most of the time), thus making the

If I made a separate MeshBuilder class it would have the same issues. The subclass MeshTerrainBuilder would had all the methods returning plain Mesh objects and I'd be in the same position.

So I'll try to use composition instead of inheritance. My MeshTerrain will contain a Mesh object and a few methods to manipulate it (ie, getHeightAt(x,y) for example). If that fails along the road I'll find another way of constructing my Mesh objects :D Thanks again for your answer!

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

This topic is closed to new replies.

Advertisement