user3587180 user3587180 - 2 months ago 8
C# Question

Should it be an instance variable or a method variable in this example?

In this example should the Serializer object be an instance variable or a method variable in the two methods? What are the pros and cons of both approaches?

public class CustomerHelper
{

private _Serializer;
private JavaScriptSerializer Serializer {
get
{
if (_Serializer == null) {
_Serializer = new JavaScriptSerializer();
}
return _Serializer;
}


public Customer GetJsonLog(Customer Cust)
{
return GetFromLog(Serializer.Searilize(Cust));
}

public void WriteToLog(Customer Cust)
{
SaveToLog(Serializer.Searilize(Cust));
}
}


Edit - Ignore Thread Safety issues and assume that Seralizer object will be re-used.

Answer

It depends on what your use-case is. If the CustomHelper is long lived, meaning it will be kept around and re-used, then creating it as a Member Property (Lazy or not, or even a Field, doesn't matter), rather than a locally scoped method field is better. You'll only have to allocate the Serializer once, then re-use that instance.

Again though, it depends on your use-case. Imagine if you were instantiating something where the WriteToLog method mutated the state of CustomHelper, and it's Serializer property. Would you want that mutated Serializer property to be shared on all subsequent calls? If you want a fresh Serializer, then you'd just instance it in your method.

In your example, the CustomHelper is stateless, and I assume the Serializer is as well. If that is the case, then a problem doesn't exist. It is however something to keep in mind when making these kind of design decisions.

As a side-note, if the CustomHelper is long lived, I'd clean up the code a bit by removing the property and just use the private field. With it being long-lived, odds are the first time you instantiate the helper you'll use it. So instantiating the Serializer in the constructor won't really hurt. Even less so if you re-use the same CustomHelper instance on subsequent calls.

Comments