.NET Code Reviews - Classes
Few days ago, i started a series for code reviewing .NET applications. Follow this link to read the first article about C# code reviews. Today, we will proceed by writing down some of the patterns i see often with .NET Classes.
Singleton Pattern
public class Helper
{
private Helper () {}
static Helper helper = null;
public static Helper Instance
{
get
{
if (helper == null)
{
helper = new Helper();
}
return helper;
}
}
public void Output(string s)
{
Console.WriteLine(s);
}
}
The same can be achieved in a more elegant way as follows.
public static class Helper
{
static Helper()
{
}
public static void Output(string s)
{
Console.WriteLine(s);
}
}
// Client Code
Helper.Output("Hello World") is better than Helper.Instance.Output("Hello World");
Excessive Derivation
- Creating multiple layers of inheritance for it’s own sake is adding complexity.
- Complexity does not mean cleverness. Clarity is more important to me as Software Developer. You can add a property called 'Type' for classA instead of creating a class that inherits from ClassA. Sure, where applicable.
- Reduce the number of levels as much as you can when deciding what classes your system includes.
Auto properties vs. private members
- Define a private variable and a relevant property only when you have business logic to be written inside the property getter and setter.
- Use auto properties when you are dealing with dummy entities. The code would be much cleaner.
Next Article
We will either talk about ASP.NET or Software Architecture review. Tell me which one you prefer ? Happy coding till then,,,
It's my first comment so I will start by admiring your articles in general that I always read. Regarding singleton, your example is valid (when a void method that only outputs a parameter), but what do you think about a singleton that writes to a store? (saying caching) Also I would like the next article to be on the software architecture review topic thanks!