java - Method Caller and Callee, circular class level method invocations -
what problems doing method caller , callee of 2 different classes doing circular class level different method calls. pass "this" reference, parameter other class instance method , callee doing further method invitation on caller passed parameter.
one reason doing that, in factory class, different implementations needs different kinds of data, put data needed multiple contracts/interface methods , have caller implement them. if have 1 class easier implement encapsulation, different classes require different sets of data.
following simple example of such, here studentservice calls mathclassscorer's topscorer method in turn calls studentservice's getstudentlist method. in complex scenario, might calling multiple methods of parent caller.
public interface istudentdata { public list<student> getstudentlist(); } public class studentservice implements istudentdata { private list<student> studentlist; public string gettop() { // factory returns mathclassscorer iscore scorer = classscorerfactory.get(); return scorer.topscorer(someotherdata, this); } @override public getstudentlist() { // , return studentlist; return studentlist; } } // iscore contains topscorer method public class mathclassscorer implements iscore { @override public string topscorer(map someotherdata, istudentdata data) { list<student> studentlist = data.getstudentlist(); //do before , after return something_after } }
the question is, there problem in above approach ?
well, whole topic of oo bit controversial i'm afraid. in opinion problems above code start naming of classes. istudentdata
not object. holding data not responsibility, , objects need responsibilities.
then design requires iscore
objects know internal data content of istudentdata
, disregarding object completely. code suggests iscore
needs know internal workings of student
too.
a oo design objects have responsibilities, , data visible little possible, ideally not @ all.
so, without knowing details, here objects like:
public class student { public boolean isbetteratmaththan(student other) { ... } } public class students { // or studentrepository public student getbeststudentatmath() { return students.stream().max(tocomparator(student::isbetteratmaththan)).get(); } }
or, if want generalize on couple of different comparable skills, still can without exposing data students:
public class students { public student getbeststudentat(comparator<student> skillcomparator) { return students.stream().max(skillcomparator).get(); } }
the point is, student
should not expose data, offer operations, or create other objects can do stuff. similarly, students
(the service in code) should not expose list of students, instead should provide methods do stuff.
Comments
Post a Comment