Anirban Paul
Anirban Paul

Reputation: 1165

How to define properties that are dependent one one another

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?

Upvotes: 3

Views: 3025

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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.

Upvotes: 3

Eric Petroelje
Eric Petroelje

Reputation: 60498

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.

Upvotes: 0

Tilak
Tilak

Reputation: 30698

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
       }
   }

Upvotes: 5

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

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

Upvotes: 0

Related Questions