Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to check the state of an object, general OOP, example in C#

Tags:

c#

oop

I'm not quite sure how to word this question in a sentence so I had difficulty searching previous posts. This comes up frequently for me and I'd like to get consensus on how to approach it.

Say you have two classes, ExampleClass and ExampleClassManager. ExampleClass has an Update(Data data) method which is called from ExampleClassManager. However, ExampleClass can be in one of two states, and in the Enabled state it wants to process the data passed to it in Update, and in the disabled state it doesn't do anything with the data at all.

Should I be checking for the state in the ExampleClassManager and not passing the data at all if it is disabled, or should I pass the data regardless and ignore it within ExampleClass?

Here's a code example in case I didn't articulate it clearly.

public class ExampleClass {
    public bool Enabled {
        get;
        set;
    }

    public void Update(Data data) {
        if(Enabled) {
            //do stuff with data
        }
    }
}

public class ExampleClassManager {
    private List<ExampleClass> exampleClassList=new List<ExampleClass>();

    public void UpdateList() {
        foreach(ExampleClass exampleClass in exampleClassList) {
            exampleClass.Update(data);
        }
    }
}

or

public class ExampleClass {
    public bool Enabled {
        get;
        set;
    }

    public void Update(Data data) {
        //do stuff with data
    }
}

public class ExampleClassManager {
    private List<ExampleClass> exampleClassList=new List<ExampleClass>();

    public void UpdateList() {
        foreach(ExampleClass exampleClass in exampleClassList) {
            if(exampleClass.Enabled) {
                exampleClass.Update(data);
            }
        }
    }
}
like image 852
tmakino Avatar asked Oct 21 '22 13:10

tmakino


1 Answers

Given that it depends on a property of ExampleClass, I'd choose option 1 and check within ExampleClass.Update. Otherwise, any object with access to an ExampleClass object could call Update regardless of the state. By checking within the Update method, you make sure it will only proceed if the object is enabled. The question here is who can change the object's status?

See the Law of Demeter:

Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.

like image 97
Julián Urbano Avatar answered Nov 15 '22 07:11

Julián Urbano