views:

96

answers:

3
Class Outer
{
 ...
    private class Node
    {
      private T data;
      ...

      private T getData()
      {
         return data;
      }
    }
}

What's the purpose of using set and get methods if the outer class can access inner class private members? What's the purpose of making inner classes private? Package access?

A: 

You could skip trivial getters and setters, but often those methods are non-trivial (a common case is the 'lazy load' pattern).

Edited to add: Lazy load is when you only instantiate a member when the data is requested. It's used when getting the data is not always needed and is expensive to get.

class a
{
private:
    int m_aNumber;
    bigDeal *m_pBig;

public:
    a() { m_aNumber = 0; m_pBig = NULL; }
    ~a() { if (m_pBig) delete m_pBig; }

    // trivial
    int get_aNumber() { return m_aNumber;}
    void set_aNumber(int val) { m_aNumber = val; }

    // lazy load
    bigDeal *get_Big()
    {
        if (m_pBig == NULL)
        {
            // bigDeal::bigDeal() downloads data from Mars Rover
            // takes 20 minutes, costs $1.2 million dollars to run
            m_pBig = new(bigDeal); 
        }
        return m_pBig;
    }
    void set_Big(bigDeal *val)
    {
        m_pBig = val;
    }
}
egrunin
Can you expound on this?
ShrimpCrackers
Um, downvotes? Is there an error? He asked about 'lazy load'...
egrunin
A: 

Private Inner classes are written when you do not want the class to be exposed to external classes within or outside the package. They are used only inside the outer level class.

The getters and setters generally do not make sense inside a private classes because you can access the instance variables anyways.

Snehal
A: 

First of all, I would say to treat inner public/protected/internal classes the same way you would treat any other "outer" class. Meaning, use the same design principles.

As for inner classes, when I'm using inner private classes they usually end up just being a heap of bytes... meaning they don't do actual processing. They are just there to make writing code for the outer class easier.

I'm not telling you to write bad code, but you can be much more lax in your design with inner private classes. As a general rule, they should be simplistic and lightweight... don't go overboard with OO on inner classes. Besides, if you end up having to change anything in the inner class you'll only have to update references in the outer class... which TBH isn't a big deal at all.

Polaris878