java - Is it generally considered a bad practice to alter the object's state via its getter method? -


i've been thinking while during past development.

i kind of against doing such things, i've declared separate method explicitly handle logic.

e.g.

if class has method return list of objects, think bad idea modify collection directly via getter method.

 public class reportgenerator{      private list<configurations> configurations;      list<configuration> getconfigurations (){       return this.configurations;     }      } 

i think doing following bad practice:

getconfigurations().remove(1); //remove configuration via getter 

i use following appoach:

 public class reportgenerator{              private list<configurations> configurations;            public  list<configuration> getconfigurations (){               return collections.unmodifiablelist(this.configurations);             }             public void removeconfiguration(int index) //logic explicitly handle remove               {                this.configurations.remove(index);             }            } 

however there 1 more thing comes mind if configuration object has getter , setter, can't prevent others doing

  reportgenerator.getconfigurations().get(0).setttitle("test"); 

they can still change state of configuration object using getter method of reportgenerator, think shouldn't allow that. if want prevent have declare more methods in reportgenerator class forward call configuration object, , use defensive copy.

so question if have object contains object b using composition , both have getter , setter, prefer change object b's state via a's getter method? e.g.

a.getb().settitle(""); 

or prefer add method change b's state (basically forwarding call b)

e.g.

a.setbtitle(""); 

and internally in method, call b.settitle("");

sorry long question, think not sure want ask. hope can understand. :p

that may work smaller classes, shudder @ how have main more complex object hierarchy. imagine if a had several objects fields. think idea right wrapper around each of them? , think of doing each object becomes more complex. doing a.getb().getc().setthingamabob() easier writing a.setsomething() calls b.setcfield() calls c.setthingamabob().

if think object should not mutable, remove setters. if consumer of a not need change b @ all, not provide getb() method , instead provide similar a.setthingy(), not mention whatever being set part of b.

your api contract not mean classes have provide getters/setters of properties. if properties not meant read/modified directly consumers, not provide ways of doing so.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -