The dirty flag behavioral pattern allows you to avoid expensive operations that would just need to be done again anyway.

This is a simple pattern that really just explains how to add a bool value to your class that you can set anytime a property changes. This will let your class know that any results it may have previously calculated will need to be calculated again when they’re requested. Once the results are re-calculated, then the bool value can be cleared.

Even though this is a simple design pattern, there are some things you’ll need to consider:

  • Do you need it? This design pattern works well when the results to be calculated are difficult or resource intensive to compute. You want to save them. You also don’t want to be calculating them several times in a row when only the last one counts.
  • When do you set the dirty flag? Make sure that you set the dirty flag within the class itself whenever an important property changes. This property should affect the result of the calculated result and by changing the property, that makes the last result invalid.
  • When do you clear the dirty flag? It might seem obvious that the dirty flag should be cleared whenever the result is calculated with up-to-date information. But there are other times when you might want to clear the flag.

What's on your mind?
On a scale of 0 to 10, how likely are you to refer us to friends?