When building classes, my rule of thumb is to always pass parameters, unless the caller has no access to them. For example, I always prefer this:
class Foo(FooData data)
{
private FooData _data;
public Foo(FooData data) { _data = data; }
pubic string GetSomeValue()
{
var result = ProcessData(_data);
return result;
}
private static string ProcessData(FooData data)
{
// do something with data and return the result
}
}
Over this:
class Foo(FooData data)
{
private FooData _data;
public Foo(FooData data) { _data = data; }
pubic string GetSomeValue()
{
var result = ProcessData();
return result;
}
private string ProcessData()
{
// do something with _data and return the result
}
}
I have come across the second example many times in the wild have never identified a good reason. Under what circumstances would accessing instance variables directly (as shown in the second example) be preferred? Or is this simply a matter of personal preference?
One benefit I have seen is shorter signatures, but a long signature is probably a smell of other design issues and therefore this is just masking it.
Aucun commentaire:
Enregistrer un commentaire