Call a method in a class or pass it as a parameter to another class? FROM#

Suppose I am registering some data with the class "Job". (A list of business objects with various properties, for what it's worth.)

I want to be able to print this data, so I wonder if there is a more preferable design for this. At the moment, I have two ideas: calling the Print () method in the job itself or passing the job instance to some print controller class, for example:

job.Print();

or

PrintWidget pw = new PrintWidget(job);
pw.Print();

At the moment, I cannot plan to print anything other than data from this Job class. However, who knows what awaits in the future. With that in mind, would it be better to have separate Print () methods for any classes that I would like to print, or one print controller class that can handle different types of things to print?

How would you do that? Thanks in advance for any answers.

+3
source share
4 answers

Your problem fits into the principle of single responsibility (SRP) , one of the principles of SOLID .

, . , . , , - , , .

Job - , , , "" . , . .

, Job, . , "", Job, ( - ).

...

Job , PrintTo(Printer), Printer . Job , , .

SRP , , :

, "", .

, Job " " " ", .

+7

Job? , , , ( ..). , . , , - :

PrintWidget pw = new JobPrintWidget(); // perhaps via abstract-factory
pw.Print(job);

, PrintWidget... , , ( , Print ) .

, , 1 , .

( # 3) - :

static class PrintUtil {
    public static void Print(this Job job) {...}
}

job.Print(), Job.

+3

Extension Methods, # 3.0. , , . , Job . :.

static class PrintExtensions
{
    public static void Print (this Job job)
    {
        // TODO: print Job
    }

    public static void Print (this SomeOtherClass c)
    {
        // TODO: print SomeOtherClass
    }
}

, , , :

Job job = GetJob();
job.Print(); // call PrintExtensions.Print(this Job job)
+2
source

Personally, I would put the Print method in the Job class. If you create a separate PrintWidget class, it will need to know everything about the Job class. In any case, if it turns out that you need or need PrintWidget in the future, you can always create it and reorganize the print method of the job class into it.

0
source

Source: https://habr.com/ru/post/1724162/


All Articles