preferred implementation style for factory pattern? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
what is your preferred implementation style for a factory pattern? For example, consider a website where I want to use a factory pattern to save to 2+ external systems. This is my first impression for a clean implementation:
Create a class named ExternalSystemManagerFactory
In the constructor of this class pass in an enumeration to indicate the target external system. For example: ExternalSystemManager.System1 or ExternalSystemManager.System2
Create a property on this class named ExternalSystemManager of type IExternalSystemManager
The constructor would set this property value based on the constructor argument
Create a method stub on IExternalSystemManager named SaveToExternalSystem
Create 2 concrete classes for my external systems that implement IExternalSystemManager (EsmSystem1, EsmSystem2)
Then in my client class, I could save to ExternalSystem1 like this:
new ExternalSystemManagerFactory(ExternalSystemManager.System1).ExternalSystemManager.SaveToExternalSystem();
Does this seem like a reasonable implementation? Do you see any potential issues with this implementation? Is this a fairly common implementation style or is there a general trend towards a different implementation style?

In my opinion when it comes to patterns, it typically has to do with how it "feels" when you use it. If you are comfortable with accessing your data in the way you have written it, then by all means go for it. I'm a firm believer that there really isn't a perfect way to implement a pattern and I actually avoid them unless my code blatantly has a need and they emerge naturally. So my advice is...Don't force it, but if it feel good, then do it.

The approach that you describe is ok, if it is only about two implementations. If the number of external systems that you want to access increases, you'd always have to change
the enum
the switch statement in the constructor that chooses the concrete implementation.
In the abstract factory pattern that the Gang of Four describes, you'd get rid of the enum and implement it like this:
An abstract base class/interface for the factory.
An implementation of the factory for each concrete external system.
You create the concrete factory at one spot in your code and always access it through the interface.
An advantage of this implementation is that you can easily configure which factory to create instead of using a switch statement in your code. Besides that you wouldn't have to adjust the switch statement each time you connect a new external system, it also allows you to create implementations for new systems without touching the assembly of the factory at all.
Another approach you might want to consider if you have lots of dependencies you want to create is to use an Inversion of Control Container. You register the types that should be created for an interface at the beginning of your application and ask the IOC container if you need an instance or inject it in the constructors of the classes. There are several IOC containers available, e.g. Microsoft Unity, Ninject, AutoFac, .... This will save you lots of time if you have several or huge factories.

Related

Private class method or interface? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
I'm working on an app which uses the Factory pattern to create new objects. In the Factory Class I've added a new Private method called SendApprovalEmail() and I am calling this from within the Process() method.
There are other Factory classes which will have their own implementation of SendApprovalEmail(). Therefore should I make an interface (containing a SendApprovalEmail() method) which these factory classes can inherit from? Or is it an acceptable approach to have a private method on each factory class which is just called from their Process() method?
Looking around the app, they tend to use interfaces when extending the factory classes. Unsure what the pros and cons of this are?
I would not put this in an interface. This would be a good situation to use a protected virtual function — if this method is intrinsic to your factory design (i.e. should be included in all factory classes) rather than just part of this particular factory implementation.
The reason for my suggestion is that you say the function is private. You wouldn’t usually put private methods in an interface.
If it really is private then that would suggest that it is not going to be defined in a similar way for other factories I.e. it is just part of this particular factory’s implementation.
However you other comments sound like it is going to also be a necessary part of the design for other factories. In that case you would make it virtual (or abstract) protected so that it can be redefined in other factory classes.
A private member makes no sense as part of an interface. An interface is there to define a set of methods, a role, an object must always implement. Private methods, on the other hand, are implementation details, not intended for public consumption.
I agree with #sjb-sjb. Depending on what you want to accomplish an interface or abstract method would be way more appropriate. These two options would enforce implementation per class inheritance. An abstract method on a base class would offer far more flexibility. Yeah, but that method cannot stay private if you want to implement inheritance.

Why creating Constructor when Default can do the all? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Hope you are fine. I started learning C# about 2 weeks ago.I’ve been watching videos since now. Now he is teaching Constructions . I don’t get it. When you can use all strings and all numerical values, why restricting them? I mean does it make things bad if you just let it to be default? I tried many ways but I couldn’t find my proper answer. Your reply is so much to me and I really like to know why?!
There are many reasons why one might want to use a constructor, but they are optional and depend on what the developer wants to do.
Constructors can receive parameters and set values based on the
passed values/objects. So you can have many different constructors setting up the object in different ways
Constructors can also include logic to determine how fields/properties should be set. If at all
Constructors can call other constructors of the same class
Constructors are needed if you are using dependency injection, or
readonly fields/properties.
If you want to create copies of your class object, then constructors
can be very useful way to do this. Especially deep copies.
You can also have a static constructor. It is invoked only once in
the class and it is invoked during the creation of the first
reference to a static member in the class.
Constructors can also be private. And you can have a mix of public
and private constructors.
Constructors are useful in inheritance, to ensure that parent
fields/properties are still set correctly no matter what the child does (the child can then change these of course
Sometimes it is as simple as if you are setting many default values,
it can be easier to read if they are all in the same place where you can group them together can comment on them together
BTW: Even if you don't create a constructor, the compiler will create a default one for you.
So simply put, C# provides you with lots of different options. It is up to you to select the one which suits you best for this specific task & class.
There are several topics you can explore that will show where it is necessary...
Dependency injection and Private Readonly Properties for example.
It can also just be convenient
new Uri(pathNameString) will generate the Uri object you can put in an http request by just providing the string at instantiation.

Do you inject dependencies in the constructor even if the class does not own these dependencies, but uses them in methods? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
If a School class relies on an EmailSender class you might have to inject this EmailSender through it's constructor with a generic interface like IMessagable or IMessageSender or even IEmailSender so that it can be swapped out for something else in the future.
In order to do this you would create a read-only private field in the School class.
But then you're saying that the School HAS-A MessageSender but surely it just USES it in a few of it's methods??
Any property/member a class declares, is something a class HAS.
The Has-A is here to differentiate from the Is-A of inheritance.
The uses-a property, is more related to class cohesion rather than composition. If the class has-A property but it does not use it, or uses it in a small percentage of functions, it has low cohesion.
Both HAS-A and IS-A are dependencies of the class. That's why we strive to have them both as abstractions, to loosely couple the two.
Any class/interface definition without which your class won't compile, is a dependency. Even if it doesn't have a HAS-A relationship and it's just passed as a function parameter.
Even if a class only uses one of many methods in a passed-in object, the entire object is still considered a dependency of the class.
This becomes evident when you change the API (the method signatures) of an object. By handing that object to a class, you essentially guarantee that object's "contract." If you change that object's API, you risk breaking classes that depend on it.
That's why we often use Interfaces to pass dependencies to classes. The interface enforces the contract between the class and its dependency, and encourages decoupling because the passed in object has to conform only to the interface's methods.
The nomenclature IS-A and HAS-A is used primarily to distinguish inheritance from composition.

Can we replace Abstract Classes with Interface having Extension Methods? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
We are about to start a project right from scratch. As per the design discussions i am thinking to bring this topic.
Most of the times,I have seen that Abstract classes were being used just to provide some default/common behavior with some concrete methods.
So, i thought of defining those concrete methods as Extension methods for the Interface i am going to develop in place of Abstract classes.
Can someone guide me regarding my design decision. If you are not going to agree with my point please justify your argument with possible scenario/issues which we can face in case of doing so. So, that it will improve my knowledge.
Both approaches are very very different.
Using an abstract class and though abstract/virtual methods, you allow the derived classes to override a behavior which is not the case for extension method. Extension methods are extensions at the end of the day, they are not part of the type and are hard to spot when someone is examining the API and the features the type provides.
Second point, creating an extension method for a type that you create yourself is not that logical IMHO. Using a base Abstract class keeps your hierarchy clear and keeps your model open for modifications of overridden behaviors.
Extension methods were introduced in C# because a very particular requirement.
When they were designing LINQ they realized that they wouldn't want to create a new interface which would contain all known LINQ methods like Where or Select, because it would mean that any enumerable or collection implementation would need to implement it.
Above mentioned fact has an important drawback: it would need to extensively change the source code of a lot of classes from the Base Class Library and any third-party library or project implementing custom collections couldn't take advantage of LINQ at all.
Then they thought about an approach that could directly work with iterators (i.e. IEnumerator<T>) and that could be compatible with any IEnumerable<T> without having to modify any existing code but just adding new code to new assembly members.
And they invented extension methods, which would be implemented like static methods and they would act as instance members of a given type.
Since the inception of extension methods, they've been implemented in many other scenarios, but they always cover these two use cases:
I've a large code base and I want to offer a functionality to all types deriving (classes) or implementing (interfaces) some other type without having to modify them implementing a new interface across a lot of code (increasing the chance of introducing new bugs).
I don't own the source code of some project and I want to extend some types to support some new methods.
Anything outside these use cases is an abuse of extension methods.
Extension methods aren't a replacement to regular class-based object-oriented programming.
Basically you could extend every class or interface - nothing else is done with the Linq-extension methods.
However you can not define those methods directly in the interface, you allways need a static public class that contains those extensions.
To answer your questions I doubt that defining a default-behaviour within extension-methods is a good thing as it completely compromizes the actual intention of that interface. When creating an extension-method all instances of that (extented) class/interface share those methods, thus what you´re doing is to say every instance of my interface is able to be treated as my abstract class.
Having said this you should differ between the behaviour (the interface) and the actual processing (the class). Mixing both will eventually make your design quite complicated.
Next is by defining extension-mtehods you completely bypass inheritance. So what if you want to override the default-behaviour? You would be lost defining them as new or any different wewird workaround because your design was not open for inheritance at all.
Last point from my view is that you should use extension-methods for classes you don´t have control about. However when you can modify the code you´ll probably won´t use them.

Why does the .NET framework rely on interfaces? [duplicate]

This question already has answers here:
Why would I want to use Interfaces? [closed]
(19 answers)
Closed 8 years ago.
I am working on learning C# in depth. I am mostly confused by the frequent implementation of interfaces. I always read that this class implements this interface. For instance, SqlConnection class implements IDbConnection. What is the benefit for developers in this case?
the interfacing is based on object-oriented principles, e.g. see SOLID. You should not rely on implementation of other classes you're working with - it should be sufficient for you to know only what they do and what they should return. A good example with the SqlConnection would be that you may be able to change the DB you are using quite simply (to e.g. MySQL or Oracle) by changing the implementation on just one place, providing that your code is correctly using the interfaces and propagating the instances.
An interface contains definitions for a group of related functionalities that a given type must implement (a sort of Method Signature Contract). It does not, however, guarantee the specific behavior of those implementations.
Interfaces are particularily useful as they allow the programmer to include behavior from multiple sources in programming languages that do not support multiple inheritance of classes like C#.

Categories