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

    Join Date
    May 2012
    Rep Power

    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
  2. #2
  3. Impoverished Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Washington, USA
    Rep Power
    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
    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