When I think about the simplest yet powerful API in .Net I immediately remember the ADO.Net. This API is ruled by the KISS principle and it does not have more or less than necessary, just the enough. I say simple because the core functionality is made of less than 30 classes (but maybe only 3 of them are widely used) and powerful because it has served as the basis for advanced API’s like the Entity Framework or LINQ.
The most used classes and methods of the ADO.Net library has been the same since the .Net Framework 1.0. Few pieces of code remain the same for over 10 years. Now think about a well know class and remember how many constructors has. A class like the SqlCommand has 4 constructors and all of them make obvious the expected behaviour as follows:.
public SqlCommand(); public SqlCommand(string cmdText); public SqlCommand(string cmdText, SqlConnection connection); public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction);
Your constructors should be just like that, few enough to remember their existence (less than 7, more is a Feature Creep symptom) and just enough for avoiding your clients have to think about their usage. The API design should make look implementation obvious and should improve readability.
Think again about the SqlCommand object, you may infer that it makes a lot of work but it’s simple enough to expose only 10 attributes and work pretty well with at least two parameters at initialization. Now check your code. Do you have initializations with NULL values? Do you have initializations with empty strings?
Every time you instance an object you should use one of the available constructors. If none of them suit you, maybe you’re coupling your consumer. If still necessary to do a new constructor wait and think about how the internal behaviour is modified. If less parameters then you need more default values, if more parameters then you need more validations. A good reason to have a new constructor is because there are for at least two consumers, other wise it may indicate a red flag.
[Update 12/Nov/2012: constructor’s parameters should be primitive types or enumerations.]
Javier Andrés Cáceres AlvisMicrosoft Most Valuable Professional – MVP Intel Black Belt Software Developer