Use property as a factory method

I have a base class Base that should instantiate another type of TRequired , however, only derived classes from Base know how to build them.

Is it nice to use an abstract method as a factory method? eg.

 protected abstract TRequired NewTRequired { get; } 

Should I use the method for any reason? Is there any guide why I should / should not use the property here?

+4
source share
3 answers

You should definitely use the method because accessing this member does something. Calling a method is a good way for the code to speak on its own in this regard.

Or, if you prefer a different perspective: two subsequent member accesses return different results. A good rule is to use the method whenever this occurs, so as not to violate the principle of least surprise .

This is like reading the result of a variable, even if you know that NewTRequired is a property (as opposed to a field), you also know that it actually executes arbitrary code:

 var prototype = Factory.NewTRequired; 

I intentionally put the result in a variable called prototype to better show that even an informed reader of this code can be easily discarded: it would be unreasonable to see this and think โ€œrightโ€, so NewTRequired is the prototype of the object for X. โ€This reader was undoubtedly would be amazed at the result of this code:

 var eq = object.ReferenceEquals(prototype, Factory.NewTRequired); 

Contrast this with the factory method. Now this code may give a little smell:

 // hmmm... are we actually using this as a prototype? // because it sure looks like an instance created just for the occasion. var prototype = Factory.NewTRequired(); 

And this code will never surprise you:

 // obviously should be false, the code screams "I am creating new instances!" var eq = object.ReferenceEquals(Factory.NewTRequired(), Factory.NewTRequired()); 

A famous example of where this rule really should be followed, but was not , is DateTime.Now .

+8
source

Instead, I would recommend a method:

 protected abstract TRequired CreateRequired(); 

Creation means "work." This is better suited for a method versus a property, since the getter property implies that it will usually be returned quickly without a lot of code.

Even the title property of your question as a factory method implies that the factory method must be a method.

+5
source

Properties are for things that look like fields, such as the location of an object.

The property that returns a new instance every time you receive it is a very poor design.

You should use a method instead.

+4
source

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


All Articles