MatteS
MatteS

Reputation: 1542

Tell don't ask and shared state between tasks

In this simple example (ofcourse my real world problem is a tad more complex, although the basics are the same), how do I enforce tell dont ask to the max? Id like to maximize tell dont ask in the process method, in its current state its harder to mock and test.

public class Processor
{
    public void Process()
    {
        var data = new Task1().DoStuff();
        new Task2().DoStuffToData(data);
    }
}

public class Task1
{
    public Data DoStuff(){return new Data();}
}

public class Data {}

public class Task2
{
    public void DoStuffToData(Data data){}
}

EDIT: Updated sample more DIish

public class Processor
    {
public Processor(ITask1 task1, ITask2 task) {...}
        public void Process()
        {
            var data = task1.DoStuff();
            task2.DoStuffToData(data);
        }
    }

Upvotes: 0

Views: 701

Answers (2)

Marijn
Marijn

Reputation: 10557

This code doesn't seem too bad from a tell-don't-ask perspective.

Tell-don't-ask basically means you shouldn't query an object about it state, make a decision based on it's state and then tell the same object what to to. If the object has all the information it needs, it should decide for itself.

You get data from task1 and consume this information with task2, without telling task1 what to do. So I'd say this OK from tell-don't-ask perspective.

With regard to Processor.Process: nothing wrong there either. A client would call myProcessor.Process and thereby tells it what to do, without asking.

Tell-don't-ask looks OK, maybe there is something else about the code you don't like? For instance, you could consider putting the DoStuffToData in the Data class, thereby combining state and behavior. But whether this is better depends on the model and its context.

Upvotes: 2

cofiem
cofiem

Reputation: 1414

One option is to use Depenancy Injection (DI). However, ensure that this does not over-complicate your code. DI can be useful for unit testing and mocking, but it can also lead to classes that are too small.

Upvotes: 0

Related Questions