Reputation: 196439
I have the following code I am trying to consolidate. (here are two examples) but with this repeated pattern of checking if fields are null then if they are different and if yes, then setting the new value into the old value.
What is the best way to rewrite this to avoid duplication?
if (String.IsNullOrEmpty(f.FirstName))
{
if (exisingPerson.FirstName != f.FirstName)
{
change = true;
exisingPerson.FirstName = f.FirstName;
}
}
if (String.IsNullOrEmpty(f.LastName))
{
if (exisingPerson.LastName != f.LastName)
{
change = true;
exisingPerson.LastName = f.LastName;
}
}
Upvotes: 1
Views: 130
Reputation: 17602
You can use delegates:
public static bool ChangeProperty(Func<Person, string> getter, Action<Person, string> setter, Person person, string value)
{
if (!String.IsNullOrEmpty(value) && !getter(person).Equals(value))
{
setter(person, value);
return true;
}
return false;
}
and call it with lambdas like this:
var barneyRubble = new Person();
change = ChangeProperty(p => p.FirstName, (p, v) => p.FirstName = v, barneyRubble, "Fred");
An even better thing to do would be to put the method in the Person
class and eliminate that third parameter altogether, replacing it with this
.
Probably overkill, but if you're making a lot of these kind of property changes it might be valuable, and I think it's an interesting pattern anyway.
Upvotes: 1
Reputation: 272217
If you're doing this a lot, you could use reflection to iterate through each field in the object, and perform the operation if it's a String
.
However, the downside of this is readability. Perhaps you're better off being explicit, and protecting against typos through copy/paste through extensive use of unit tests.
Upvotes: 0
Reputation: 10605
For just a couple of fields, your code may be the best. Short and simple.
Upvotes: 0
Reputation: 837936
I don't think you can do much to remove the duplication (at least not without introducing reflection which will probably just muddy the code rather than make it clearer).
However you could look at implementing INotifyPropertyChanged
which is a standard pattern for notifying about changes to an object instead of the boolean you are currently using:
If you look at the example code there it also has a certain amount of repetition.
Upvotes: 2