function - Should a property/field always have a setter and getter method or can you combine them? -


if have user object properties/fields 'firstname' , 'lastname'. best set , each field firstname , lastname getter/setter, or simple 'name' getter/setter acceptable?

it largely depends on language you're planning use these variables in. in languages accessors (gets) , mutators (sets) written out hand , aren't inherently present, there number of ways handle these functions.

public variables frowned upon, provide direct access use , change values. people can argue or against public , protected variables, general consensus in oop should keep data yourself. since have mentioned get/set, we'll assume you're not going doing this.

another way address access variables return reference, in first example, mileage may vary. there's lot of responsibility in providing direct access , lot of left directly on user's shoulders. if you're planning have people other working class, it's not safe give them such access.

standard getname() , setname() functions simplest way handle , provide format can updated without changing interface. once program decent size, refactoring interface changes can become nightmare. route allows gut functions without changing else in code.

in languages support it, can write overloaded functions decide based on syntax whether want retrieve data or change data. follows same basic idea standard get/set, calling syntax more akin user.name("joebob peoplesmith") or name = user.name(). way of going varies language language, ability.

finally, languages have built-in access variables declared in ways. example objective-c's property, can synthesized private variable direct access get/set interface. in format, access nsstring *m_pfirstname, can create @property nsstring *firstname , @synthesize firstname = m_pfirstname. get/set implicitly handled user.firstname if local variable.

as combining firstname , lastname, personal choice , should decided based on whether or not ever want/need change individually. ask yourself:

  • do ever need change firstname or lastname?
  • do ever need access firstname or lastname?
  • how plan return firstname + lastname? (an array? combined string?)
  • who using these functions? (other developers? other classes?)
  • will self-explanatory newcomers? (easy understand? easy use? 'fool-proof'?)
  • is there data structure can me?

overall, need research options based on language restrictions , plan out how using variables before making decisions. avoid having refactor mid-development if @ possible. hope helps!


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -