3
votes

Lets say I have an class with two properties of type string

  1. Prop1
  2. Prop2

And there are the following restrictions

  1. Prop1 can not be equal to "Test1" if Prop2 value is "Test2"
  2. Prop2 can not be equal to "Test22" if Prop1 value is "Test11"
  3. Set Prop1= "Test111" if Prop2="Test222"

What is the best way to define the properties whose value is dependent on one another and also changes made in one property should trigger setter property of the other?

4
I guess this should get the homework tag - if it were still around? @Paul> I think you will need some "ifs" and then throw exceptions (or do nothing) in case of trying to set "Test1" or "Test22". - Laoujin
@Laoujin The homework tag has been deprecated. - Ryan Gates

4 Answers

5
votes

You need to add validation in the property setter.

   string prop1;
   string prop2;

   string Prop1 
   {
      get { return prop1;}
      set 
      {
         if (!( Prop2 == "Test2" && value == "Test1"))
         {
             Prop1 = value;
          }
         ... Add other condition here
      }
   }

   string Prop2
   {
      get { return prop1;}
      set 
      {
         // set Prop2 based on Prop1
       }
   }
3
votes

You have lots of choices here:

  • Make both properties read-only, and add a method that sets them both simultaneously.
  • Make both properties read-write, let them throw an exception when they are not set consistently, and add a method that sets them both simultaneously.
  • Make both properties read-write, and add a method that lets you turn off validation temporarily. Make a "guard" that switches the validation back on upon destruction, and use the guard in a using statement.
  • Add transactional semantic to your object: pay attention to an ambient transaction, store pending sets in a queue when a transaction is "in progress", and apply all changes at once when the transaction is committed.
0
votes

you are in charge of coding the "logic" you need perhaps in the property setter (kind of validation)

I would use the specification patter to extract the validation logic and make it testable as well

http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx

0
votes

You could implement this logic in the setters for each property, but I would question the wisdom of that.

It would probably be better to either have a Validate method on the object that would check the state of those properties or have another object responsible for performing the validation and either returning errors or making changes to the object as appropriate.