In Java, when should we use a single, comprehensive getter method that can return many objects rather than a bunch of smaller getter methods? -


to clarify, mean:

public image getrespectiveimage(int temp) {     switch(temp){     case 1:return one;     case 2:return two;     case 3:return three;     case 4:return four;     case 5:return five;     }     return null; } 

compared to

public image getone(){return one;} public image gettwo(){return two;} public image getthree(){return three;} public image getfour(){return four;} public image getfive(){return five;} 

i tend prefer former because seems simpler reason, seems use latter. there reason why use bunch of getter methods?

it's not "which better or worse" -- if properties writing getters not, nature, indexed, make no sense write indexed getter them. if properties not of same type, clue indexed representation isn't going helpful.

if properties using do make sense store indexed list, sure, means -- use array field (consider: if array type not appropriate field, perhaps indexed getter not actually appropriate either).

you generally want getters , setters reflect fields have declared. use getter/setter takes int index parameter when field array type (which conforms javabeans spec, section 8.3.3).

you want 2 reasons. first, on conceptual level, if fields different getters/setters, while there tons of valid reasons this, may want take @ how you've organized fields see if can refactor more accurately represents purpose of object (it assumed public getters/setters representations of purpose). may indication of bigger design issues.

secondly, , more being aware of doing, getters , setters affect interaction apis operate on beans, , affect interaction apis use reflection. example, hibernate can configured persist objects database using getter/setter properties, or direct field access. depending on configuration there, have @ least aware of getter/setter vs. field setup.

the take home point here is: don't try come @ idea there set of rules defining when 1 way better or worse. consider nature of objects working with, , properties mean (semantics), , write public interface makes sense.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -