When reading questions on Stack Overflow or Stack Programmers, I often see answers which state that you should avoid (or at least have very little) global state in your programs. I’m writing a little program at the minute and I was concerned that I was introducing a lot of global state. Allow me to show you an example piece of code.
public class ContactUpdater
{
//this is used in a few method and requires a web request so it's fairly
//expensive to populate - therefore we only want to do it once.
private Group _group;
public ContactUpdater
{
_group = GetGroup();
}
}
This approach meant that my code was littered with _group which felt ugly and wrong so I decided to use a property like so:
public class ContactUpdater
{
private Group _group;
private Group Group
{
get
{
if (_group == null)
{
_group = GetGroup();
}
return _group;
}
}
public ContactUpdater()
{
}
}
Now I have an empty constructor and wherever I need to use the group, I now just call Group rather than _group.
I have a couple of questions:
- Am I using global state in both of these code snippets?
- Does the second example avoid global state?
- Is one of the code examples the preferred way of coding?
As @Conrad Frix pointed out, it depends on what GetGroup() does. I would normally decouple the group from the updater with an interface and use constructor injection:
This way ContactUpdater can be tested independently of Group and GetGroup() by passing in a fake or mock implementation of the IGroup interface.
You can create ContactUpdater manually, passing in the result of GetGroup(), or use a dependency injection framework.
I personally don’t use private properties for encapsulation often (I do sometimes), and I use the same underscore convention you do. I don’t have a strong opinion on this. Try both and see what’s easier to read and maintain.
Update: Since GetGroup() calls an external service, I would absolutely decouple that.