If I have a User object with the properties/fields ‘firstName’ and ‘lastName’. Would it always be best to set and get each field with a firstName and lastName getter/setter, or would a simple ‘name’ getter/setter be acceptable?
If I have a User object with the properties/fields ‘firstName’ and ‘lastName’. Would it
Share
It largely depends on what language you’re planning to use these variables in. In languages where accessors (gets) and mutators (sets) are written out by hand and aren’t inherently present, there are a number of ways to handle these functions.
Public variables are generally frowned upon, but provide direct access to use and change the values. People can argue for or against public and protected variables, but general consensus in OOP is that you should keep your data to yourself. Since you have already mentioned get/set, we’ll assume you’re not going to be doing this.
Another way to address access to the variables is to return a reference, but as in the first example, your mileage may vary. There’s a lot of responsibility in providing direct access and a lot of that is left directly on the user’s shoulders. If you’re planning to have people other than yourself working with this class, it’s not especially safe to give them such access.
Standard
getName()andsetName()functions are the simplest way to handle it and provide a format that can be easily updated without changing the interface. Once your program is a decent size, refactoring interface changes can become a nightmare. This route allows you do gut the functions without changing anything else in your code.In languages that support it, you can write overloaded functions that will decide based on syntax whether you want to retrieve the data or change the data. This follows the same basic idea as your standard get/set, however the calling syntax would be more akin to
user.name("Joebob Peoplesmith")orname = user.name(). The way of going about this varies language to language, as does the ability.Finally, some languages have built-in access for variables that are declared in certain ways. A good example is Objective-C’s
property, which can be synthesized with a private variable for direct access as a get/set interface. In this format, to accessNSString *m_pFirstName, you can create@property NSString *firstNameand then@synthesize firstName = m_pFirstName. The get/set is implicitly handled byuser.firstNameas if it were a local variable.As for combining your firstName and lastName, that is a personal choice and should be decided based on whether or not you would ever want/need to change anything individually. Ask yourself:
Overall, you need to research your options based on language restrictions and plan out how you will be using your variables before making your decisions. Avoid having to refactor mid-development if at all possible. Hope this helps!