0

Assume I am populating an object's properties and I need to pass in one of the properties to another method, is it OK to reference a property from the new object or should I set a separate variable first and use it? Is one way better than the other? Keep in mind I have not called SaveChanges().

Method #1 (use property from new object)
=================================================
newObject.LegacyId = oldObject.Id;
newObject.NewId = GetNewIdFromLegacyId(newObject.LegacyId);


Method #2 (set separate variable)
=================================================
int legacyId = oldObject.Id;
newObject.LegacyId = legacyId;
newObject.NewId = GetNewIdFromLegacyId(legacyId);
webworm
  • 10,587
  • 33
  • 120
  • 217
  • They way you have it here both are the same. With more code the second method is actually passing the old (yet equal) value which could potentially be made not equal. See [pass objects by value/ref](http://stackoverflow.com/questions/8708632/passing-objects-by-reference-or-value-in-c-sharp). – Jasen Jan 09 '16 at 20:31

1 Answers1

0

I have to assume that both methods are equivalent.

The only thing that could make things different here is when there is more code in the getter or setter of newObject.LegacyId than just storing/returning a member variable, by which you'd return a different value than the set value. This would be highly insensible and unexpected. (And therefore unlikely you're actually doing this).

So it's really a matter of taste which method you prefer. I think personally I might prefer a third method:

int legacyId = oldObject.Id;
int newId = GetNewIdFromLegacyId(legacyId);

newObject.LegacyId = legacyId;
newObject.NewId = newId;

This is a micro-isolation of responsibilities: getting Id values and object initialization. This may seem nitpicking, but Single Responsibility (the S of SOLID) is one of the most important design principles and it can be applied at any level to make code better maintainable. It might lead you to separating the code in two parts that you can (unit) test separately.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291