<= Home

Encapsulation 101

Posted about about 1 year ago

Just cause you have state class doesn't mean you achieved object orientation

  public class State
  {
      readonly int Id;
  }  

The following breaks encapsulation

  public void DoStuffWithState(State targetState)
  {
      if(state.id == targetState.id)
      {
           ....
      }
  }

This is much better

  public void DoStuffWithState(State targetState)
  {
      if(state == targetState)
      {
           ....
      }
  }

Using Operator Overloading is key to achieve proper encapsulation

public class State
{
    private readonly int Id;
    
    public static  bool operator ==(State x, State y)
    {
        return x.Id = y.Id;
    }
    
}