At my current workplace, I run across a lot of code that looks similar to the following example:
private void GetWidgets(ref List<Widget> widgets){
if(widgets == null){
widgets = new List<Widget>();
}
else{
widgets.Clear();
}
... code to fill widget list
}
and
public class Widgets{
private List <Widget> widgets;
... other private members
public Widgets(){
Clear();
}
public void Clear(){
if(widgets == null){
widgets = new List<Widget>();
}
else{
widgets.Clear();
}
... initialize other private members
}
}
I personally find the usage of the Clear method in these examples to make the code uglier and more complicated. I don't know if there is a performance increase in using the Clear method over simply creating a new List, but I would prefer code that look like this:
private List<Widget> GetWidgets(){
widgets = new List<Widget>();
... code to fill widget list;
return widgets;
}
and
public class Widgets{
private readonly List<Widgets> widgets = new List<Widget>();
... other private members
public Widgets(){
... initialize other private members
}
public Clear(){
widgets.Clear();
}
}
Code like this forces you to change your development patterns slightly, but I think it makes the code far more readable and reduces the complexity.
Aside from the fact that this is a piece of hastily written sample code, I rampantly used concrete classes instead of interfaces, etc.; What are your opinions? What are the pros and cons of each?