in reply to Does one encapsulate a class from itself?

I prefer to use the object's accessors even within the object itself. As you say, it provides the benefits of encapsulation inside the class. In particular, I can change the representation of some part of it without too much disturbance. If performance becomes a demonstrated issue, I might go back on that, but usually I spend a lot more time waiting for things outside my code than I do dragging my feet inside. YMMV.

  • Comment on Re: Does one encapsulate a class from itself?

Replies are listed 'Best First'.
Re^2: Does one encapsulate a class from itself?
by amarquis (Curate) on Mar 06, 2008 at 20:24 UTC

    Side question: you linked profiling information, but I used benchmark, should I have gone with profiling instead? I reasoned that just knowing where time was spent wasn't valuable to me (since, for example, maybe more time spent in accessors was less time spent in subroutines. I know I could have subtracted one from the other, but it was seeming pretty approximate when I was thinking about it).

    What I did do was make up versions of important subs made to use accessors and benchmark, for example, iterations of a sub versus it's getter/setter-using counterpart. Seemed to do the trick, wish I'd left the modified subs around now, though, so I'd have something to share.

      There's not much point in optimizing something if it's only called once. Likewise, you may have something that's very fast but called a million times, so it could be worth trying to make it even faster.

      Of course, if you can take some item and Benchmark two solutions for it and pick the faster one, that will be better for performance in all cases. However, the time you spend doing that might have been better spent working on something else. That's what profiling will tell you—where your program actually spends its time in a real run.

      If you're writing a module, you can't always tell how it will be used. Otherwise, test your program to see where it really spends its time, and optimize those places where it will make the biggest difference. There's no reason to guess about it if you can test it easily.

      As for your concern about approximations and calls within calls, the profiling tools can give you meaningful statistics either way. You can look at time spent only in a certain function or in the full cumulative time spent in that function and everything it calls.