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

I am not quite sure how to formulate this question in a sentence, so it was difficult for me to find previous posts. This often arises for me, and I would like to get consensus on how to approach it.

Say you have two classes: ExampleClassand ExampleClassManager. ExampleClasshas a method Update(Data data)that is called from ExampleClassManager. However, it ExampleClasscan be in one of two states, and in the state Enabledit wants to process data, passed to it in Update, and in the disconnected state does nothing with the help dataat all.

Should I check the state in ExampleClassManagerand not pass dataat all if it is disabled, or do I need to pass it dataindependently and ignore it in ExampleClass?

Here is an example code if I havenโ€™t articulated 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);
            }
        }
    }
}
+5
source share
4 answers

Given that this depends on the property ExampleClass, I would choose option 1 and check inside ExampleClass.Update. Otherwise, any object with access to the object ExampleClasscan call Updateregardless of state. By checking the method Update, you will make sure that it will only work if the object is included. The question is, who can change the status of an object?

See the Law of Demeter :

: "" .

+3

" ?" 2 - "" - ExampleClass , .

, , - . , " ", . ExampleClass , .

1, , , - , 2.

- , ExampleClass.Enabled.get , , ? , , , . , , , 2 .

0

2, classManager , , . , ( ).

@caerolus: ... demeter

, , , , ?

0

Let's say you have two objects: a company and an employee. Do you have a company check when an employee is hungry, or do you have an employee check if he is hungry? It looks like you want the employee to check if he is hungry, right? But what if the company wants to order food for all employees, then the company must check whether the employee is hungry.

So, I want to say that it depends on the design and the context of when to check and who checks and why. In your example, I would say that it does not matter because the context is not set.

0
source

All Articles