Micha
Micha

Reputation: 5163

How to avoiding calling redundancy in context of variable assignment?

I offten (like at the moment) come to the point to write c# (or vb.net) code like this:

someObject.field_1 = doSomething( 
                            anotherObject_1.propertyA, 
                            anotherObject_1.propertyB);

someObject.field_2 = doSomething( 
                            anotherObject_2.propertyA, 
                            anotherObject_2.propertyB);

// some more field in same schema.

someObject.field_X = doSomething( 
                            anotherObject_X.propertyA, 
                            anotherObject_X.propertyB);

Edit: anotherObject_1 .. anotherObject_X have same typ; someObject and anotherObject have normaly not the same typ.

The Problem is the expandability and maintainability. New field brings me to write nearly same code with only little differences in object naming.

With encapsulate the logic in doSomething(..) I avoid logic redundancy, but the calling redundancy is still annoying.

Is there a way (for example a pattern or a .Net (4.0) language-construct) to avoid this?

Upvotes: 2

Views: 187

Answers (2)

loopedcode
loopedcode

Reputation: 4893

You can use Reflection to reduce code duplication/repetition. If know that your target property would always be called "propertyA" and "propertyB", you can easily use reflection and get/set their value as needed. You can pass in your object as well, and manipulate it there with reflection also.

For example, you can write something like this (note: syntax not fully checked):

public someReturnType DoSomething(object myObject)
{
  if (null == myObject)
  { 
    throw new ArgumentNullException("myObject");
  }

  var propertyA = myObject.GetType().GetProperty("propertyA");
  if (null == propertyA)
  {
    //this object doesn't have any property called "propertyA".
    //throw some error if needed
  }

  var value = propertyA.GetValue(myObject); //You will need to cast as proper expected type

  // You can retrieve propertyB similarly by searching for it through GetProperty call.
  // Once you have both A and B, 
  // you can work with values and return your output as needed.

  return something;
}

Upvotes: 1

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

You can encapsulate set operation into different method

void SetField(ref int field, object anotherObjectX)
{
  field = doSmth(anotherObjectX...);
}

SetField(ref object.field1, anotherObject1);
SetField(ref object.field2, anotherObject2);
SetField(ref object.field3, anotherObject3);

but you still need to add the new line for the each new field

Upvotes: 3

Related Questions