java - Return child class from parent class -


i have builder class returns methods allow daisy-chaining. make work child classes, want parent methods return instances of child child methods available chain end.

public class basebuilder<t extends basebuilder<t>> {     public t buildsomething() {         dosomework();         /* option #1: */ return this;     // "type mismatch: cannot convert basebuilder<t> t"         /* option #2: */ return t.this;   // "type mismatch: cannot convert basebuilder<t> t"         /* option #3: */ return (t) this; // "type safety: unchecked cast sqlbuilder<t> t"     } }  public class childbuilder extends basebuilder<childbuilder> {} 

options #1 , #2 result in compilation errors, , option #3 warning (albeit 1 can suppressed @suppresswarnings("unchecked")). there better approach here? how can safely downcast basebuilder childbuilder?

the declaration childbuilder extends basebuilder<childbuilder> somehow indicates code smell , seems violate dry. in example basebuilder can parametrized childbuilder , nothing else, should redundant.

i rather rethink whether want over-architecture , try put methods child builders basebuilder. can return this methods supporting chaining.

if still think benefit separating specific groups of builder methods own classes, give preference composition, because applying inheritance code reuse not recommended.

suppose have 2 subclasses of basebuilder:

class buildera extends basebuilder<buildera> {    buildera buildsomethinga() { return this; } }  class builderb extends basebuilder<builderb> {    builderb buildsomethingb() { return this; } } 

what if need arises chain buildsomethinga , buildsomethingb like:

builder.buildsomething().buildsomethinga().buildsomethingb(); 

we not able without moving subclass methods basebuilder; imagine there builderc methods don't make sense , shouldn't inherited basebuilder.

if nevertheless move these 2 methods superclass, , next time 3 other methods , next time... we'll end superclass responsible 90% of duties of entire hierarchy plenty of code like:

if ((this instanceof builderb) && !flag1 && flag2) {    ... } else if ((this instanceof builderc) && flag1 && !flag2 && thing != null) {    ... } else if ... 

the solution more dsl like:

builder.buildsomething1().buildsomething2()    .buildera()       .buildsomethinga1().buildsomethinga2()    .end()    .buildsomething3()    .builderb()       .buildsomethingb()    .end(); 

here end() returns builder instance can chain more of methods or start new sub-builder.

this way (sub)builders can inherit whatever need (otherwise must extend basebuilder) , can have own meaningful hierarchies or compositions.


Comments