Tuesday 15 March 2011

spring - Implicit (inherited objects) in Java, more suited way? -



spring - Implicit (inherited objects) in Java, more suited way? -

i have feeling using parent's variables kind of shabby. has way enforce visibility in subclass create more explicit.

public abstract class myclass{ @autowired object implicitobject; @test public void commontest(){ implicitobject.dosomethingbasic(); } } public class mysubclass extends myclass{ @test public void testsomethingelse(){ implicitobject.dosomethingelse(); } }

do think esteemed pattern? there optimal alternative?

protect field

exposing parent class fellow member not idea, unless field declared final (which impossible) can damaged or hidden kid class. it's preferable protect getter method. while create implicitobject more "visible" it's protected "malicious" kid classes.

public class myclass{ @autowired private object implicitobject; public final object implicitobject() {return implicitobject;} } public class mysubclass extends myclass{ public void dosomething(){ implicitobject().dosomething(); } }

is practice?

yes depends on what's behind implicitobject, if it's sort of context or resource api sound fine me.

control access visitor interface

if want add together more "constraint" there solution : expose implicitobject method parameter, adds more "visibility" implicitobject involve more boilerplate code. (inspired visitor pattern)

/** * class implement custom tests * enable access low-level implicitobject */ public interface customtest { void test(object implicitobject); } public class myclass{ @autowired private object implicitobject; @test public void commontest(){ implicitobject.dosomethingbasic(); } /** * method take visitor , give access implicitobject */ public final void customtest(customtest customtest) { // can prepare stuff before customtest.test(implicitobject); // can cleanup after } }

customtest way access implicitobject :

public class mycustomtest implements customtest { @override public void test(object implicitobject) { implicitobject.dospecificthing(); } }

then utilize visitor implementation.

public class mysubclass extends myclass{ @test public void testsomethingelse(){ super.customtest(new mycustomtest()); } }

it's verbose... worth effort? 1 time again depends on what's behind implicitobject.

use container

i don't know if it's possible/practicable spring container should able inject implicitobject method parameter.

public abstract class myclass{ @autowired object implicitobject; @test public void commontest(){ implicitobject.dosomethingbasic(); } } public class mysubclass extends myclass{ @test @autowired public void testsomethingelse(object injectedimplicitobject) { injectedimplicitobject.dosomethingelse(); } }

java spring inheritance junit polymorphism

No comments:

Post a Comment