Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I Prefer a Closed or Open List<> System?

Tags:

c#

.net

list

I've got a class in my project that stores a List<> of elements. I'm trying to figure out whether I should allow the user to add to that List directly (e.g. Calling the native add/remove methods) or lock it down by declaring the List private and only allowing a handful of methods I choose to actually alter the List.

It's a framework, so I'm trying to design it as robustly as possible, but I also want to keep it as simple and error-free as possible.

What's the best practice in this situation?

Thanks, Tyler

like image 333
Tyler Murry Avatar asked May 22 '10 16:05

Tyler Murry


2 Answers

For a framework, I'd recommend to encapsulate the list completely and create methods to retrieve and add elements to it.

If the need arises to check the elements which are added, or events need to be fired for some actions, you'll be able to do that.

If you prefer to store those elements differently for whatever reason, you can.

On the other hand. if you allow to access the list directly, it will be difficult to go back and encapsulate it, or to change that and use something else. Code which uses this framework may depend exactly on that direct access to the list.

like image 149
marapet Avatar answered Sep 25 '22 06:09

marapet


Keeping the list private gives you more control and may make it more robust (you can check values before accepting them into the list)

But keep it public is the simplest.

like image 37
Shiraz Bhaiji Avatar answered Sep 25 '22 06:09

Shiraz Bhaiji