design patterns - Java Constructor of a class with fields that are are end user fed -
my question is: best way write constructor of java class fields initialized through stdin
?
for example suppose have employee
class looks like:
public class employee { private int empid; private string empname; private list<role> emproles; {....} }
i can write setters , getters class. of course, role
class have own file.
also suppose make setters first 2 fields follows, in order enable end user initialize fields:
public void setempid() { system.out.println("please enter employee id"); scanner s = new scanner (system.in); this.empid = s.nextint(); public void setempname() { system.out.println("please enter employee name"); scanner s = new scanner (system.in); this.empname = s.next(); }
then:
- can use such setters in constructor overrides default constructor.
- is best way write such constructors?
- is better move
scanner
object creating in each setter constructor , make argument setters
e.g:
public void setempname(scanner s) { ... this.empname = s.next(); }
as can see, may design question rather "coding".
many help.
actually, don't rely on way uses specific constructor populate fields of object no arg constructor.
indeed chose setter approach populate fields of employee
instance after invoking new employe()
.
setter approach complex mix many responsibilities : taking user input , setting state of object.
can use such setters in constructor overrides default constructor.
no, makes no sense : constructor , setters 2 distinct ways , cannot override 1 other.
invoke setters constructor relying on scanner
instance take user input actual setters approach, seems awkward approach gives many responsibilities constructor.
is best way write such constructors?
using constructor populates fields, :
employee emp = new employe(id, name, roles)
makes sense if object designed immutable once created.
in actual case, if object not designed immutable using constructor or setters valid in case, should provide setters.
so answer question, should separate responsibilities (taking user input , setting object state) , use either setter or constructor approach according requirements on instances of employee
:
employee emp = new employe(id, name, roles)
or
employee emp = new employe(); emp.setid(...); emp.setname(...); emp.setroles(...);
Comments
Post a Comment