Thursday, 15 March 2012

What is the difference between using callback functions and calling a static function directly in java? -



What is the difference between using callback functions and calling a static function directly in java? -

i know question has been asked before. want understand difference perspective of code.

so here scenario.

i have class main.java. class calls different class secondary.java . on particular method in secondary class, want values in main class updated. there 2 ways this.

1) 1 way doing through callback functions in java. 2) sec if define static function in main class, phone call static function secondary class.

here 2 approaches.

approach 1

interface callback.java

public interface callback{ public void updatevalues(); }

main.java

public class main implements callback { static int a=1; public static void main(string args[]) { callback callback = new main(); secondary obj = new secondary(callback); obj.onclick(); } public void updatevalues(){ = 4; } }

secondary.java

public class secondary{ private callback callback; secondary (callback callback) { this.callback=callback; } //on method click, want update values in main class public void onclick(){ callback.updatevalues(); } }

approach 2

public class main { static int a=1; public static void main(string args[]) { sec obj = new second(); obj.onclick(); } public static void updatevalues(){ = 4; } } public class secondary{ secondary () { //on method click, want update values in main class public void onclick(){ main.updatevalues(); }

}

so want know approach better? when callback functions useful?

note: illustration understand difference between 2 concepts.

which approach better? reply depends on context, there cases break every rule. said, keeping coupling low , code simple , unit tested usual priorities.

static method pros: simple, , direct disadvantages: static method cannot substituted other implementations. callback approach pros: easy substitute callbacks, mocking in tests cons: little more overhead callback (although jvms can optimise them out) , little more conceptual cost developers; low if not abused.

judging selection of example, suspect working on gui. big applications, static method approach not tend scale without becoming brittle change. while application small, find static method approach simple , tempting. application grows, , add together more people project need create changes growing code base of operations @ same time need ways isolate parts of application , unit test parts. callback approach shines.

the danger callback approach becomes on used. avoid nesting callbacks much possible (there patterns functional world create great technique, perhaps post) , callback must not know caller. cyclic dependency tends complicate code @ non-linear rate.

java callback

No comments:

Post a Comment