Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify repeating if-then-assign construction?

Tags:

c#

.net

lambda

I have the following method:

protected override bool ModifyExistingEntity(Product entity, ProductModel item) {     bool isModified = false;      if (entity.Title != item.Title)     {         isModified = true;         entity.Title = item.Title;     }      if (entity.ServerId != item.Id)     {         isModified = true;         entity.ServerId = item.Id;     }      return isModified; } 

I wonder if you could suggest a better way to implement the method.

The problem is obvious: 5 lines of almost copy-pasted code per property is too much. May be there's a solution using Func-s / Expression-s out of my vision.

like image 888
Sergey Metlov Avatar asked Apr 28 '15 07:04

Sergey Metlov


2 Answers

You have a case of temporal coupling there, i.e. you're mixing the check whether the entity has changed with the assignments. If you separate the two, your code becomes much cleaner:

protected override bool ModifyExistingEntity(Product entity, ProductModel item) {     bool isModified = this.IsEntityModified(entity, item);      if (isModified)     {         this.UpdateEntity(entity, item);     }      return isModified; }  private bool IsEntityModified(Product entity, ProductModel item) {     return entity.Title != item.Title || entity.ServerId != item.ServerId; }  private void UpdateEntity(Product entity, ProductModel item) {     entity.Title = item.Title;     entity.ServerId = item.Id; } 

Doing any smart and funky stuff (TM) with Func<> or anything like that, doesn't seem helpful in this case as it wouldn't transport your intention as clearly.

like image 137
bstenzel Avatar answered Sep 21 '22 16:09

bstenzel


Something like this should work

protected bool ModifyExistingEntity(Person entity, ProductModel item) {     bool isModified = CompareAndModify(() => entity.Title = item.Title, () => entity.Title != item.Title);     isModified |= CompareAndModify(() => entity.ServerId = item.Id, () => entity.ServerId != item.Id);      return isModified; }  private bool CompareAndModify(Action setter, Func<bool> comparator) {     if (comparator())     {         setter();         return true;     }     return false; } 

Not sure if this is readable. It is subjective.

like image 37
Sriram Sakthivel Avatar answered Sep 22 '22 16:09

Sriram Sakthivel