Design pattern for inter-dependent values

design-patterns

Summary: Is there a good design pattern to reduce duplication of information among tightly interdependant values?

In my line of work its fairly common to have a relationship among quantities such that you can derive one of the quantities if you know the others. An example could be the Ideal gas law:

Pv = RT

You could imagine creating a class to represent the state of an ideal gas. The class would have 3 properties, naturally Pressure, Temperature, and SpecificVolume each of an appropriate type.

For the user of an object of this class, it would seem natural to expect that if you set values for both Pressure and Temperature, you could then read out a value for SpecificVolume and expect the object to have calculated that for you.

Likewise, if you set values for both Pressure and SpecificVolume, you could then read out Temperature, etc.

To actually implement this class however requires some duplication of information. You would need to explicitly program all variations of the equation, treating a different variable as dependent in each case:

  1. T = P * v / R

  2. P = R * T / v

  3. v = R * T / P

which seems to violate the DRY principle. Though each expresses the same relationship these cases require independent coding & testing.

In real cases the logic I'm thinking of is more complex than this example, but exhibits the same basic problem. So there would be real value if I could express the logic only once, or at least fewer times.

Note that a class such as this would probably also have to deal with making sure it was properly initialized before values would be read out, but I think that is a secondary consideration.


Though I gave a mathematical example the question is not limited only to mathematical relationships among data. That just seemed to be a simple example to make the point.

Best Answer

There is no issue from an OO perspective. You could have a static class GasLaw offering methods

GetVolume(R, T, P) 
GetPressure(R, T, v)

et cetera

and there would not be a duplication issue. There is no object, no data members. Just behaviors that are all different.

You may regard the gas law as "one thing" but the operations are all distinct. There is nothing wrong with having a method for each of the law's use cases.

Related Topic