Active vs. Passive code bases

time to read 8 min | 1553 words

I was review code at a customer site, and he had a lot of classes that looked something like this:

   1: public class ValidationData
   2: {
   3:     public string Type {get;set;}
   4:     public string Value {get;set;}
   5: }

In the database, he would have the data like this:

image

This is obviously a very simple example, but it gets the job done, I think.

In his code base, the customer had several instance of this example, for validation of certain parts of the system, for handling business rules, for checking how to handle various events, and I think you get the picture.

I seriously dislike such codebases. You take an innocent piece of code and make it so passive it… well, you can see:

image

Here is why this is bad. The code is passive, it is just a data holder. And that means that in order to process it you are going to have some other code that handles that for you. That likely means a switch statement of the equivalent. And it also means that making any sort of change now have to happen on multiple locations. Puke.

For fun, using this anti pattern all over your codebase result in you have to do this over and over again, for any new interesting thing that you are doing .It is a lot of work, and a lot of places that you have to change.

But you can be a hero and set the code free:

You do that by making a very simple change. Instead of having passive data containers that other pieces of the code need to react to, make them active.

   1: public class AvoidCurseWordsValidator : IValidator
   2: {
   3:    public string[] CurseWords {get;set;}
   4:    public void Validate(...) { }
   5: }
   6:  
   7: public class MaxLenValidator : IValidator
   8: {
   9:    public int MaxLen {get; set;}
  10:    public void Validate(...) { }
  11: }
  12:  
  13: public class InvalidCharsValidator : IValidator
  14: {
  15:    public char[] InvalidChards {get;set;}
  16:    public void Validate(...) { }
  17: }

Now, if we want to modify / add something, we can do this in only one spot. Hurray for Single Responsibility and Open Closed principles.

SO… don’t let your codebase be dominated by switch statements, parallel hierarchies and other nasties. Make it go active, and you’ll like the results.