Private and internal classes


This post is not going to be about concurrent programming. It has been triggered by a Twitter initiated chat regarding how to write unit tests for private methods. The general consensus was you just don’t: one must test public methods, private ones are an implementation details.
What about private classes then, did I ask. One of the feedback I got was: are you sure private/internal classes are needed in the general case?

I definitely think so, so let me describe some uses.

Internal classes

As a reminder, internal classes in C# are classes that are accessible only from the assembly they are defined in (and friend assemblies, if any). Declaring a class public is a contract with anyone who may use this library: you must implement a quality service for the long run. It implies you provide documentation of some sorts as well as ensure the class will be published for the versions to come.

For example, in RAFTiNG I have classes that are used to implement the behavior of the node according to its current state. Definitely implementation details, not something I want to publish.

Private classes

As a reminder, private classes can only exists as member of other classes in C#. They are useful to implement specific collaboration scenarios. Going on with RAFTiNG examples, in the ‘leader’ state, a node must track the synchronization point for each of the ‘Follower’ nodes.

Implementing it directly in the ‘LeaderState’ class implies building up an array of follower state and managing them one by one. Definitely not very OO: no encapsulation!

So, the proper way to do it is to implement a dedicated class for that, a very specialized class that is only useful in that very state.

See LogReplicationAgent member class here.

Note also that member classes can access private members from their hosting class, which offer interesting collaboration model.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s