Home > Uncategorized > Encapsulation


NOTE: The example is borrowed from a http://www.netobjectives.com streamzine.

Introduction to Refactoring

Often when you present a code snippet like this to someone and asked how would you make it better.

The immediate response from most is: make the public attributes properties.
Well property procedures are still a limited way of encapsulation. In one of the trainings I took, I presented the following example and asked for a better solution.

You are implementing a collection base class which uses an ArrayList as a backing store.

public class ListBase
    public ArrayList backingList;

    // other uninteresting stuff

People immmediately respond

public class ListBase
    private ArrayList backingList;

    public ArrayList BackingList
        get { return backingList; }

    // other uninteresting stuff

Now I presented the next question. What if I want to replace the ArrayList with a List<T> because we have upgraded to .NET 2.0?

Well now you retain the ArrayList Property but instead of returning the backingList (which is a List<T> now) directly return a backingList.ToArrayList() or something like that. The property procedures have given you the mileage, good isn’t it!

The actual problem is BackingList is a violation of encapsulation whether it is a public attribute or a public property. Assuming looping is your primary concern you are better off making backingList private and implement IEnumerable (or its generics equivalent) which lets you loop thru a collection without the calling code worrying about the actual implementation details ‘backing store is an Array, ArrayList, List<T> etc’. In fact modern languages / frameworks go one step further & have moved this looping stuff into the framework itself using closures. Array.Each, List<T>.Find family predicate methods are good examples of these. You just pass a block of code to these methods and you are done.

public class ListBase : IEnumerable
    private ArrayList backingList;

    // IEnumerable Implementation
    // other uninteresting stuff

So the moral is to use property procedures with caution. They are good but they may not be good enough. Think about the scenario at hand and apply a solution which makes sense.

Anyway the actual refactored code for the netobjectives example becomes

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: