Friday, 15 July 2011

Java: passing static variables to constructors? -



Java: passing static variables to constructors? -

i have classa lot of static variables.

does create difference if access these variables in classb in static manner, i.e. calling classa.variable or if i'm passing these static variables constructor of classb (and assign static variables in classb later usage)? 1 use?

duplicating many fields bad thought because complicates maintenance.

if these fields genuinely variable, rather constants, have identically named variables in 2 different classes. have remember update both copies of each value in places in code update either 1 of them.

even if fields constants, duplicating them muddles meaning , purpose. ideally there should 1 place in programme these values defined, should class relevant , meaningful do.

another consideration is, how closely related classa , classb? if reason want pass these values parameters because classb might want used different class instead of classa, makes sense pass parameters because can't hardcode references original fields in classa. if there many such parameters, unwieldy. in case, can utilize separate class hold configuration state shared classes. classa (and classes it) create , initialize instances of configuration class, , pass single parameter classb. configuration class place many variables need declared , documented.

on other hand, if 2 classes intended 2 inseparable pieces of same application, classb can count on classa beingness there, indirection not necessary. question 1 time again becomes, want duplicate these fields in classb?

if want cut down typing classa. in front end of things, utilize static import @ top of classb:

import static packagename.classa.*; // imports static members import static packagename.classa.fieldx; // imports specific thing selectively

then can refer things field1, rather classa.field1. usage frowned upon can create confusing find variables coming from, win clarity if there few variables beingness used many times.

java constructor static

No comments:

Post a Comment