#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Posts
    1
    Rep Power
    0

    Manipulating Instance Variables


    Hi Everyone,

    I have been into software development for a few years now but have recently started learning the Object-Orientated Style of development. I was wondering; with this style, what is the most effective way to access an objects/classes instance variables: Via direct manipulation or through the use of methods to read/ manipulate them?

    Thanks in advance
    George
  2. #2
  3. Transforming Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,112
    Rep Power
    9398
    IMO there is no simple answer to that. It depends on the language, the requirements, the developer, and the audience (ie, other developers).

    Two languages I'm most familiar with are PHP and C#.

    C#: Supports "properties", which are member variables accessed through getter and setter methods, but those methods are hidden with syntactic sugar and it looks like you're accessing them directly. 99% of classes should use them; I personally tend to use fields (non-property variables) on structs more often.

    PHP: Doesn't support properties so you'd have to write actual getter and setter methods. I don't like doing that. In my opinion external code should do due diligence to make sure it's not accessing or manipulating things in a way it shouldn't. That said there are exceptions, like when the external code can't know what's valid or not (without extra work it shouldn't have to do) and variables that it simply should not have access to.

    I don't believe you should ever write getters and setters that don't have any special logic. The downside is that if there has to be logic added later then all other code has to be rewritten as a method call instead of a variable access. There might be ways around that in the language, like how C#'s properties are very simple
    Code:
    public string Name { get; set; }
    and PHP has the magic __get() and __set() methods.


    I'm best at answering these kinds of questions in the context of various situations. Is your question sparked by anything in particular?

IMN logo majestic logo threadwatch logo seochat tools logo