views:

78

answers:

5

I'm a student looking for resources which can help me further understand how to properly apply access modifiers to members/types as I code them.

I know (in C#) what restrictions access modifiers like private, public, protected, etc. put into place. When I code my own little projects I have a tendency to just make everything public. I'm certain this is an absolutely horrible practice as it just tosses encapsulation out the window. I just never know when it's correct to use something like internal vs. private.

Does anyone have any good resources to aid me in understanding the proper use of access modifiers?

+2  A: 

This is an experience type question. Start from the level of least privilege and promote up as necessary.

In other words, make everything private. Until you discover that it needs to be promoted to protected or public. Over time you will get a feel for the intended and later discovered usages of your classes.

Chris Lively
A: 

Start putting everything private. If you feel the need, change the modifier accordingly, until you have the feeling to choose the right type.

To make things easier, try using TDD, or you might get into even more trouble when you get to write unit tests...

Samuel Carrijo
A: 

I simply make everything's access as restrictive as possible:

  • Private by default
  • Otherwise internal, if it's an API exposed to other classes within this assembly
  • Or, public if it's an API exposed outside the assembly
  • Or, protected if it's intended to be called only from subclasses.
ChrisW
A: 

Any kind of tutorial or teaching material will give you the same guidance, namely the one that the other postings already gave you. So don't expect much useful information in this specific matter from "resources".

The primary resource that goes beyond that is code that other people have written. Take a large C# project (e.g. Mono, or SharpDevelop), and study how they specifically followed the principles that have been explained to you. Also, if you have a specific class to design, try to think of a similar class in the system libraries, and try to find out how it is implemented (either by looking at the Mono source, or by using the .NET reflector).

Martin v. Löwis
A: 

You should start by thinking about the interface of a class, that is the necessary and sufficient set of routines it needs to expose in order to achieve its purpose. Make that public. Everything else should be private.

Flavius Stef