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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With