Private class method or interface? [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 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.

Related

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.

Correct way of implementing composition (Composition with 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 4 years ago.
Improve this question
I am confused with these implementations .In an interview,interviewer asked me what is composition and I gave him typical definition then I wrote this part of code for him.
public class Foo {
private Bar bar = new Bar();
}
But he claimed this implementation is correct
interface IFoo
{
int DoSomthing();
}
class Bar : IFoo
{
public int DoSomthing()
{
throw new NotImplementedException();
}
}
Which one is correct?
Edit: I realize now that both you and your interviewer were correct; answer updated accordingly.
From the wikipedia page on Composition over inheritance:
Composition over inheritance...is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class.
Polymorphism is
the provision of a single interface to entities of different types.
So what you did (having Bar be a property of Foo) is Composition because Bar has an instance of Foo through having it as a property.
What your interviewer did was also Composition because, through the interface IFoo, Bar implements the same functionality, and it didn't use inheritance to do so. This appears to be the way it's documented on the linked wiki page but doesn't mean your way is wrong either.
Which method you use for implementing the same functionality in different places would depend on whether it makes sense for Bar to be a property of Foo or not.
Composition denotes a "is-a-part-of" relationship between objects. For example,
class Engine
{
//....
}
class Car
{
Engine engine = new Engine();
//.....
}
we can see, Engine is-a-part-of Car. Composition and inheritance are two different concepts and you probably shouldn't accept a job offer where he would be your boss. :)

Why do we re-implement parent interface of derived interface on class which implement derived 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 5 years ago.
Improve this question
I was studying about UOW pattern on Microsoft Docs and saw following code
interface IStudentRepository: IDisposable
{
void SomeMethod();
}
// Interface Implementaion
class StudentRepository: IStudentRepository, IDisposable
{
public void SomeMethod(){}
public void Dispose(){}
}
Now my question is why do we re-implement parent interface of a derived interface on a class which implements derived interface? For instance, IStudentRepository interface derived from IDisposable interface but when we implement IStudentRepository interface on StudentRepository class we implement IDisposable as well in addition to IStudentRepository interface.
What benefits will it provide?
which problem does it solve?
Or it is totally unnecessary/redundant?
NOTE: I have tried this code without reimplementing IDisposable again and the tried casting back and forward; everything worked as it works with re-implementation.
Specifying IDisposable on the class that implements IStudentRepository is redundant. It has no effect at all.
It is not necessary to do:
class StudentRepository: IStudentRepository, IDisposable { }
Just write:
class StudentRepository: IStudentRepository { }
If you view this in Resharper it will tell you that stating IDisposable again is redundant.
I can think of a few reasons this might be a good idea:
Some inheritance-checking algorithms, especially reflection-based, will fail to discover inherited types in certain scenarios, like parent interfaces. This can be a bug or expected behavior (inheritance chains can be quite long, hurting performance of graph-walkers or other reflective type-checking algorithms). In these cases, if you need to be sure the method will figure out that the object is IDisposable quickly, then reimplement.
The parent interface might be refactored to remove the Disposable implementation, but the child class will still require it. As chris said in his comment, this isn't a great reason; once an object implements IDisposable it's fairly problematic to remove it from the parent but keep the implementation in the child classes.
It reminds developers perusing the source code that the object is IDisposable. It's not obvious at a glance that IStudentRepositories are IDisposable, but if this is central to the preferred usage (i.e. the repository should be the focus of a using block), then every piece of information helps.
It is, as you've found, not necessary though; if you remove IDisposable from StudentRepository, the class is still IDisposable due to the inheritance on IStudentRepository.
There is one reason I can think of, where that would make sense.
The client of the interface (StudentRepository) has disposable members, which it would like to dispose of too. And it re-implements the IDisposable interface to be protected from future breaking changes on the IStudentRepository interface. In other words, may in the future the IStudentRepository not be IDisposable, there would be no change required on the client side.

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.

preferred implementation style for factory pattern? [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 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.

Categories