Looking for approach to design two classes and one interface - c#

public interface ISaveData
{
void DeleteFile(); // this is common method
//void ChangeBucket(); I don't need this method in GoogleCloudSaveFile. Should I remove this from here
// void AssignPermission(); // I don't need of this method in AzureSaveData. Should I remove this from here?
}
public class AzureSaveData : ISaveData
{
void ChangeBucket()
{...}
void DeleteFile()
{...}
}
public class GoogleCloudSaveFile() : ISaveData
{
void AssignPermission()
{...}
void DeleteFile()
{...}
}
I want to expose Interface to my presentation layer.
How can I design above three classes (2 classes and 1 interface) to expose all methods to my presentation layer.
All methods means:
Delete()
ChangeBucket()
AssignPermission()
Please ask me if you need more explanation
Presentation layer could be like
void Main()
{
ISaveData saveFiles = new GoogleCloudSaveFile(); // This is just example. I will inject this via Dependency Injection framework
saveFiles.Delete();
}
ChangeBucket() and AssignPermission() are just example methods. I wanted to say, our child classes could have different methods like these two.
One solution is I can define these two methods in interface and can leave method body empty of one method but I don't think it will be good approach

As far as I can think based on the information provided by you without getting into the nitty-gritty of what method would lie in which interface, this is the easiest I can think of:
public interface ISaveData
{
void DeleteFile(); // this is common method
}
public interface IPermission
{
void AssignPermission();
}
public interface IBucketOperation //or something else
{
void ChangeBucket();
}
public class AzureSaveData : ISaveData, IBucketOperation
{
public void ChangeBucket()
{
Console.WriteLine("AzureSaveData ChangeBucket");
}
public void DeleteFile()
{
Console.WriteLine("AzureSaveData DeleteFile");
}
}
public class GoogleCloudSaveFile : ISaveData, IPermission
{
public void AssignPermission()
{
Console.WriteLine("GoogleCloudSaveFile AssignPermission");
}
public void DeleteFile()
{
Console.WriteLine("GoogleCloudSaveFile DeleteFile");
}
}
You can use these as follows:
ISaveData x = new GoogleCloudSaveFile();
x.DeleteFile();
(x as IPermission).AssignPermission();
You can also check if the object you create is of the type before typecasting:
if(x is IPermission)
(x as IPermission).AssignPermission();
I am not sure if you are willing to take the following approach but I think this would be better:
public interface IGoogleCloudSaveFile : ISaveData, IPermission { }
public interface IAzureSaveData : ISaveData, IBucketOperation { }
It would be difficult for you to use a common interface and expect it to have different methods available for different type of objects based on the implementation unless you want to ignore design principals and put everything into one interface. In that case, just put everything in one interface, and while implementing it in the classes, just do a
throw new NotImplementedException();

Related

Choosing allowed methods from Abstract Class

I have an abstract class with methods with logic.
Then i have childs but not all childs can have all methods from the abstract class. I have been thinking of a design pattern that allows me to keep the logic instead of using interfaces but can't think of anyhting other then using a static class with methods. But it would make my code very sloppy.
Another way of formulating my question is: How do i use interfaces with logic in them...
public abstract class Company
{
public virtual void Dowork1()
{
//logic
}
public virtual void Dowork2()
{
//logic
}
public virtual void Dowork3()
{
//logic
}
}
public class ItCompany : Company
{
//DoWork2 NOT callable
}
public class ManagementCompany : Company
{
//DoWork1 NOT callable
}
A pillar of object oriented programming is Liskov substitution principle. In practical terms this means that any implementation of Company need to implement all the methods. I.e. one implementation of a company should be possible to substitute for any other.
You seem to be concerned about implementation inheritance, i.e. allow any of the implementations to reuse the same logic without the need to reimplement it. This can be problematic since it couples the base class to the derived classes. However, you should be able to do what you describe by making the implementations protected.
public abstract class Company
{
protected virtual void DoworkImpl1()
{
//logic
}
protected virtual void DoworkImpl2()
{
//logic
}
protected virtual void DoworkImpl3()
{
//logic
}
}
This lets each implementation define what parts they want to expose:
public class ItCompany : Company
{
public void Dowork1() => DoworkImpl1();
public void Dowork3() => DoworkImpl3();
}
You may also add different interfaces for each type of company if you want to, as shown in other answers. However, if Company does not expose any public methods, you cannot really do anything with a object of the base type, except check what specific type it is, and this is often indicative of a problem in the class design. I would recommend reading Eric Lipperts article on Wizards and Warriors for some perspective.
A possible replacement is to move logic to static methods, for example using extension methods or default interface methods:
public static class CompanyHelpers{
public static void Dowork1(this ICompany company){
// Logic
}
}
This can be very useful with well designed interfaces that expose a minimal set of functions, and provides most extra functionality via extension methods. See LINQ for an example. But it may or may not be applicable in your specific situation.
I think you are looking at the problem from the wrong side. Let me rename your methods to make it more clear.
public abstract class Company
{
public virtual void ManagementWork()
{
//logic
}
public virtual void ItWork()
{
//logic
}
public virtual void BuildCompany()
{
//general logic
}
}
public class ItCompany : Company
{
//ManagementWork NOT callable
}
public class ManagementCompany : Company
{
//ItWork NOT callable
}
It would be better this way
public abstract class Company
{
public virtual void BuildCompany()
{
//general logic
}
}
public class ItCompany : Company
{
public virtual void ItWork()
{
//logic
}
}
public class ManagementCompany : Company
{
public virtual void ManagementWork()
{
//logic
}
}
I guess this is the better way :
interface IDoableWorkOne
{
void DoWork1();
}
interface IDoableWorkTwo
{
void DoWork2();
}
interface IDoableWorkThree
{
void DoWork3();
}
interface ICompany
{
//Other Company Shared Logics
}
public class ManagementCompany: IDoableWorkTwo, IDoableWorkThree, ICompany
{
/// Do your Business
}
public class ItCompany : IDoableWorkOne, IDoableWorkThree, ICompany
{
/// Do Your Business
}
Hope this helps.
Trying to stick with inheritance in such situation makes me think that you are trying to use the wrong tool for your job.
You may achieve code reuse by favoring composition over inheritance and refactor your code as follow:
public sealed class Company
{
public void Dowork1()
{
//logic
}
public void Dowork2()
{
//logic
}
public void Dowork3()
{
//logic
}
}
public sealed class ItCompany
{
private readonly Company _company;
public ItCompany(Company company) => _company = company;
//Call DoWork1 and DoWork3 whenever you want from _company
}
public sealed class ManagementCompany
{
private readonly Company _company;
public ManagementCompany (Company company) => _company = company;
//Call DoWork2 and DoWork3 whenever you want from _company
}
This code has the same benefits of code reuse than inheritance but without the burden of trying to hide normally public inherited methods.
Also you can be sure that no one ever can alter Company's behavior (such a central piece of logic for you) since the class is sealed, unlike solutions trying to stick with inheritance that allow overriding DoworkX() methods.

Is it a good practice to cast from an interface to some concrete class when needed?

I'am developing a small system and i developed the classic generic repository. For now, i have the following architecture for my DAL.
public interface IRepositorio<T> where T : class
{
T Get(long id);
long Insert(T obj);
bool Update(T obj);
bool Delete(T obj);
}
public abstract class Repositorio<T> : IRepositorio<T> where T : class
{
public IDbConnection Connection
{
get
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["DBFila"].ConnectionString);
}
}
public T Get(long id)
{
//...
}
public long Insert(T obj)
{
//...
}
public bool Update(T obj)
{
//...
}
public bool Delete(T obj)
{
//...
}
}
My concrete repository looks like this:
public class FilaRepositorio : Repositorio<FilaRepositorio>
{
public FilaRepositorio()
{
}
public void SomeCustomMethod()
{
// Some custom method
}
}
I am also using Simple Injector to follow the IoC and DI patterns, for this reason, when i try to call "SomeCustomMethod()" i dont have access to it (obviously). Look:
public class Processador
{
private IRepositorio<FilaModel> _repoFila;
public Processador(IRepositorio<FilaModel> repoFila)
{
_repoFila = repoFila;
}
public void Processar()
{
_repoFila.SomeCustomMethod(); // <-- wrong
((FilaRepositorio)_repoFila).SomeCustomMethod();// <-- works
}
}
Given this i have some questions:
Is a good or acceptable practice to make that cast (FilaRepositorio)?
If its not a good practice, how to write good code for this case?
There are a few options available. The main problem with making the cast is that it is an implementation concern.
What would happen if the injected object was not a FilaRepositorio?
By making the cast you are tightly coupling the class to an implementation concern that is not guaranteed to be the inject dependency. Thus the constructor is not being entirely truthful about what it needs to perform its function.
This demonstrates the need to practice Explicit Dependencies Principle
The Explicit Dependencies Principle states:
Methods and classes should explicitly require (typically through
method parameters or constructor parameters) any collaborating objects
they need in order to function correctly.
One way to avoid it would be to make a derived interface that explicitly exposes the desired functionality of its dependents.
public interface IFilaRepositorio : IRepositorio<FilaModel> {
void SomeCustomMethod();
}
public class FilaRepositorio : Repositorio<FilaModel>, IFilaRepositorio {
public void SomeCustomMethod() {
//...other code removed for brevity.
}
}
and have the Processador depend on that more targeted abstraction.
Now there is no need for the cast at all and the class explicitly expresses what it needs.
public class Processador {
private readonly IFilaRepositorio _repoFila;
public Processador(IFilaRepositorio repoFila) {
_repoFila = repoFila;
}
public void Processar() {
_repoFila.SomeCustomMethod(); // <-- works
}
}
If you need to access a specific method from any part of your application, then that specific method must be part of your abstraction, or else there is no guarantee that you may use it when changing the concrete class.
I do not believe that your use of casting is a good idea at all, what is usually done in this case is to create a specific interface which defines any other method you could need to use:
public interface IFilaRepositorio : IRepositorio<Fila>
{
void SomeCustomMethod();
}
And than use and declare that specific interface in any part of your code where you believe you need to use it:
public class Processador
{
private IFilaRepositorio _repoFila;
public Processador(IFilaRepositorio repoFila)
{
_repoFila = repoFila;
}
public void Processar()
{
_repoFila.SomeCustomMethod();
}
}

Design point : is polymorphism appropriate in my case

I have a situation similar to the one that follows :
interface IAbstractPaymentService { void ProcessPayment(); }
interface IPaymentGateway1Service : IAbstractPaymentService { } // Do not define extra methods but needed for IoC container configuration
interface IPaymentGateway2Service : IAbstractPaymentService { } // Do not define extra methods but needed for IoC container configuration
public abstract class PaymentProcessor
{
protected abstract void ThisMethodNeedsASpecializedService(IAbstractPaymentService abstractPaymentService);
}
public class PaymentGateway1Processor : PaymentProcessor
{
protected override void ThisMethodNeedsASpecializedService(IAbstractPaymentService abstractPaymentService)
{
return ThisMethodNeedsASpecializedService(abstractPaymentService as IPaymentGateway1Service) // Don't worry, I do security checks
}
public void ThisMethodNeedsASpecializedService(IPaymentGateway1Service paymentGateway1Service)
{
paymentGateway1Service.ProcessPayment();
}
}
public class PaymentGateway2Processor : PaymentProcessor
{
protected override void ThisMethodNeedsASpecializedService(IAbstractPaymentService abstractPaymentService)
{
return ThisMethodNeedsASpecializedService(abstractPaymentService as IPaymentGateway2Service) // Don't worry, I do security checks
}
public void ThisMethodNeedsASpecializedService(IPaymentGateway2Service paymentGateway2Service)
{
paymentGateway2Service.ProcessPayment();
}
}
I'm not really happy with this abstraction, because the idea of polymorphism is that you don't care about the underlying type, you just want a certain behaviour to be applied. But here, even if I create a factory of PaymentProcessor, every time the consumer will need to call ThisMethodNeedsASpecializedService(), he will need to know the underlying type to inject the correct service.
I was thinking of storing the Service in an internal property, so that I could create a Factory that would inject the service at creation time and the consumer wouldn't need to know about the service used - and therefore, wouldn't care about the underlying type. But I have always seen the fact of storing a service instance in a property a bad practice, and am not sure if I should go that way.
What do you think about it, and would you do it differently ?
A better way to impement your structure is to inject IAbstractPaymentService via PaymentProcessor costructor. For example:
public abstract class PaymentProcessor
{
protected abstract void ThisMethodNeedsASpecializedService();
}
public class PaymentGateway1Processor : PaymentProcessor
{
private IPaymentGateway1Service paymentGateway1Service;
public PaymentGateway1Processor(IPaymentGateway1Service paymentGateway1Service){
this.paymentGateway1Service = paymentGateway1Service;
}
public void ThisMethodNeedsASpecializedService()
{
this.paymentGateway1Service.ProcessPayment();
}
}

Interface with implementation without abstract class?

I am writing a library and I want to have an interface
public interface ISkeleton
{
IEnumerable<IBone> Bones { get; }
void Attach(IBone bone);
void Detach(IBone bone);
}
The Attach() and Detach() implementation actually should be the same for every ISkeleton. Thus, it could essentially be:
public abstract class Skeleton
{
public IEnumerable<IBone> Bones { get { return _mBones; } }
public List<IBone> _mBones = new List<IBone>();
public void Attach(IBone bone)
{
bone.Transformation.ToLocal(this);
_mBones.add();
}
public void Detach(IBone bone)
{
bone.Transformation.ToWorld(this);
_mBones.Remove(bone);
}
}
But C# doesn't allow multiple inheritance. So among various issues, users have to remember to inherit from Skeleton every time they want to implement Skeleton.
I could use extension methods
public static class Skeleton
{
public static void Attach(this ISkeleton skeleton, IBone bone)
{
bone.Transformation.ToLocal(skeleton);
skeleton.Bones.add(bone);
}
public static void Detach(this ISkeleton skeleton, IBone bone)
{
bone.Transformation.ToWorld(this);
skeleton.Bones.Remove(bone);
}
}
But then I need to have
public interface ISkeleton
{
ICollection<IBone> Bones { get; }
}
Which I do not want, because it is not covariant and users can bypass the Attach() and Detach() methods.
Question: Must I really use an abstract Skeleton class or are there any or tricks and methods?
If you need to expose the Attach and Detach methods in your interface, there is always a way to bypass your intended implementations, as all objects implementing the interface can implement them on their own style.
You can let the abstract class Skeleton implement ISkeleton and all classes which are Skeletons do inherit from Skeleton, thus they implement ISkeleton as well.
public interface ISkeleton { ... }
public abstract class Skeleton : ISkeleton { ... } // implement attach and detach
public class SampleSkeleton : Skeleton { ... }
This way you can use your SampleSkeleton as ISkeleton, you don't have to implement these functions as long as you inherit from Skeleton and marking the methods as sealed does not allow overriding them (as long as they are instance methods).
On a side node: Do name your abstract class with Base at the end or mark the base class somehow else (but this is surely up to you).
I would make bones a special type that implements IEnumerable<T>. That way it doesn't violate the single responsibility principle.
public interface ISkeleton
{
AttachableEnumerable<IBone> Bones { get; }
}
public class AttachableEnumerable<T> : IEnumerable<T>
{
// implementation needed.
void Attach(T item);
void Detach(T item);
}
If you want to wrap ISkeleton behaviour, you could always make it a composite object instead of inheriting the behaviour:
public class Body : ISkeleton
{
private SkeletonImpl _skeleton = new SkeletonImpl;
public IEnumerable<IBone> Bones { get { return _skeleton.Bones; } }
public void Attach(IBone bone)
{
_skeleton.Attach(bone);
}
public void Detach(IBone bone)
{
_skeleton.Detach(bone);
}
}
May be you just have to use sealed methods on abstract Skeleton class?
This way they can't be overriden.
http://msdn.microsoft.com/en-us/library/aa645769(v=vs.71).aspx
You can create a wrapper class which implements the 'Attach' and 'Detach' methods and inject this Functionality to your Interface.

How can I factor out the code duplication here?

So, I'd like to hear what you all think about this.
I have a project where three different inheritance paths need to all implement another base class. This would be multiple inheritance and isn't allowed in C#. I am curious how I can implement this without code duplication.
EDIT: I don't own the three classes. The three classes are from 3rd party code. So I cannot make them all extend my base class.
Right now I am using three different classes, each one extending a different base class. Then I have the same code in each of the three abstract classes.
I could use a single interface, but I would still need to duplicate the code.
I could make some kind of static class that implements the code and then reference that in each of the 3 abstract classes. It would eliminate the duplication, but, I am not sure how I feel about this. I could implement Extensions methods on the interface, but then the interface itself would be empty and the extension methods (containing the duplicate code) would be in a totally different file, which seems not quite right. Plus I can't implement properties in extension methods...
How can I factor out the code duplication here?
EDIT, inheritance tree:
class Class1 : 3rdPartyBaseClass1 { }
class Class2 : 3rdPartyBaseClass2 { }
class Class3 : 3rdPartyBaseClass3 { }
I have code I want to be in each of the above Classes, but I cannot add it to the 3rdPartyClasses.
Create an interface that Class1, Class2, and Class3 can implement. Then put your code in extension methods so it will apply to all.
interface IMyInterface {
void Foo(); //these are the methods that these
//classes actually have in common
void Bar();
}
public class Class1 : 3rdPartyBaseClass1, IMyInterface {
// whatever
}
public static class IMyInterfaceExtensions {
public static void CommonMethod(this IMyInterface obj) {
obj.Foo();
obj.Bar();
}
}
public static class Program {
public static void Main() {
var instance = new Class1();
instance.CommonMethod();
}
}
OK, you can do something similar to my previous suggestion, and also similar to recursive's suggestion. For the functionality you require in all three of your derived classes, you can create a single Interface along with a single class (call it "Implementer" for kicks) that implements that Interface (and that has the actual code you want executed with each call).
In each of your derived classes, then, you implement the Interface and create a private instance of Implementer. In each of the interface methods, you just pass the call along to the private instance of Implementer. Because Implementer and your derived classes all implement your Interface, any changes you make to the Interface will require you to modify Implementer and the derived classes accordingly.
And all your code is in one place, except for all the lines passings the calls on to the private instance of Implementer (obviously multiple inheritance would be better than this, but you go to war with the army you have, not the army you wish you had).
Update: what about just adding a public instance of your class to each of the derived classes?
public class DerivedClass1 : ThirdPartyClass1
{
public MyClass myClass = new MyClass();
}
Or if you care who Demeter is and you get paid by LOC:
public class DerivedClass1 : ThirdPartyClass1
{
private MyClass _myClass = new MyClass();
public MyClass myClass
{
get
{
return _myClass;
}
}
}
Then you'd just call the MyClass methods like this:
DerivedClass1 dc1 = new DerivedClass1();
dc1.myClass.DoSomething();
This way, we could all go to sleep.
Similar to MusiGenesis's suggestion, if you need the functionality of the 3rd party classes but do not have to descend from them, you could use composition as follows:
class ThirdPartyBaseClass1
{
public void DoOne() {}
}
class ThirdPartyBaseClass2
{
public void DoTwo() { }
}
class ThirdPartyBaseClass3
{
public void DoThree() { }
}
abstract class Base
{
public void DoAll() { }
}
class Class1 : Base
{
public void DoOne() { _doer.DoOne(); }
private readonly ThirdPartyBaseClass1 _doer = new ThirdPartyBaseClass1();
}
class Class2 : Base
{
public void DoTwo() { _doer.DoTwo(); }
private readonly ThirdPartyBaseClass2 _doer = new ThirdPartyBaseClass2();
}
class Class3 : Base
{
public void DoThree() { _doer.DoThree(); }
private readonly ThirdPartyBaseClass3 _doer = new ThirdPartyBaseClass3();
}
This also gives you the freedom to define whatever interfaces you want and implement them on your classes.
Sounds like you need to insert the new abstract class into the inheritance tree at whatever point those three paths come together, but there really isn't enough information to tell. If you could post some of your inheritance tree, that would help a lot.
I think you may want to use composition instead of inheritance. Exactly how to do this depends on what the third party classes look like, and what your own code looks like. Some more specific code relating to your problem would be helpful, but for example, suppose you want to have three different third party GUI widgets that all need to be customized with your own initializer code.
Case 1: Suppose your third party widgets look like:
public interface IThirdPartyWidget {
public void doWidgetStuff();
}
public class ThirdPartyWidget1: ThirdyPartyWidget implements IThirdPartyWidget {
...
}
public class ThirdPartyWidget2: ThirdPartyWidget implements IThirdPartyWidget {
...
}
You can do:
public class MyWidget implements IThirdPartyWidget {
private IThirdPartyWidget delegateWidget;
public MyWidget(IThirdPartyWidget delegateWidget) {
this.delegateWidget = delegateWidget;
}
public void doWidgetStuff() {
delegateWidget.doWidgetStuff();
}
}
Case 2: Suppose you absolutely need to extend those widgets, and you have to refactor your own code:
public class MyWidget1: ThirdPartyWidget1 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
public class MyWidget2: ThirdPartyWidget2 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
This can become:
public class MyCodeRunner {
public void runMyCode() {
//...
}
}
public class MyWidget1: ThirdPartyWidget1 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
public class MyWidget2: ThirdPartyWidget2 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
Hope this makes sense!

Categories