java - How to decouple code using shared information -
hopefully, i'm not asking duplicate. tried searching , didn't find anything, have been keyword choice (i can't think of keywords use).
frequently, while coding, encounter situations following:
public void dostuff() { string sharedvalue = getvalue(); // code block 1 uses sharedvalue // code block 2 uses sharedvalue } private string getvalue() { // code sharedvalue } for example, hash table class, , getvalue() corresponds hashing function.
ideally, code block 1 , code block 2 modularized 2 separate methods so:
public void usevalue1() { string sharedvalue = getvalue(); // code block uses sharedvalue } public void usevalue2() { string sharedvalue = getvalue(); // code block uses sharedvalue } now, problem if call usevalue1() , usevalue2(), getvalue() runs twice. using java's hashmap example:
public class clazz { map<string, list<string>> map = new hashmap<string, list<string>>(); public void ensurelistexists(string key) { if (!map.containskey(key)) map.put(key, new arraylist<string>()); } } hashmap.containskey() , hashmap.put() calculate same hash key twice. in case, calculating hash key not expensive of operation, not hard imagine more expensive.
objective: decouple 2 blocks of code share information semantically distinct (without recalculating information).
here few solutions thought of , why don't them:
> use cache: solution of choice in cases, perhaps long-lived objects (e.g. keep cache of database queries done , results). on smaller scale, don't idea of creating instance variable solely serve cache couple methods , used maybe once or twice. plus, cache comes own overhead.
> extract string sharedvalue parameter usevalue1(string) , usevalue2(string) , call getvalue() calling method so:
public void usevalue1(string sharedvalue) { // code block uses sharedvalue } public void usevalue2(string sharedvalue) { // code block uses sharedvalue } string sharedvalue = getvalue(); usevalue1(sharedvalue); usevalue2(sharedvalue); - this forces
getvalue()public, forces calling method handlesharedvaluemanually. should automatic , hidden implementation detail - not maps implemented hash tables. - this doesn't work if
sharedvaluemultiple variables. knows multiple return values sucks (in java @ least). create class encapsulates of variables, creates more clutter using instance variables.
can think of elegant solution problem? see time. perhaps there no other solution , i'm being picky. i'm willing accept answer.
note: recognize may seem pre-optimization, think see enough warrant having nice solution handy whenever happens.
Comments
Post a Comment