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.
Related
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();
}
}
EDIT
Ive rephrased the question so it better reflects what im trying to do
I'm trying to create a suite of classes that all inherit from 1 "superclass" or "baseclass".
However i'm looking for a way around having to implement the code for each method, in every single class since it seems to be theres a lot of duplication.
Here is the Super class:
public abstract class WebObject
{
string Id { get; set; }
string Name { get; set; }
public void Click() { Console.WriteLine("Clicking object"); }
public string GetAttribute() { return "An attribute"; }
public void SetAttribute(string attribute, string value)
{
//code to set attribute
}
}
I've also created a couple of interfaces:
interface IReadable
{
string GetText();
}
interface IWriteable
{
void SetText(string value);
}
Here is an example derived class:
public class TextBox: WebObject, IWriteable, IReadable
{
}
Of course the above class contains an error. It does not implement IWriteable or IReadable.
So I could do something like:
public class TextBox: WebObject, IWriteable, IReadable
{
public void SetText(string value)
{
//Implemented code
}
public string GetText()
{
//Implemented code
return "some value";
}
}
Which would compile fine...
However the problem here is that SetText and GetText contain a lot of code. I don't want to have to copy this every single time I want to implement the method. Id rather just write the code once and have it called any time I need to use that method.
I know we cant do multiple inheritance in C# and Java. So my original thought was simply to create a suite of static classes with the code for SetText and GetText Shown here:
public static class Setter
{
public static void SetText(string value)
{
//Code to set text
}
}
public static class Getter
{
public static string GetText()
{
//Code to get text
return "";
}
}
Then changing my TextBox class to the following:
public class TextBox: WebObject, IWriteable, IReadable
{
public void SetText(string value)
{
Setter.SetText(value);
}
public string GetText()
{
return Getter.GetText();
}
}
I cant help but feel this is a pretty long winded solution. It accomplishes what I want in that TextBox has the vanilla methods plus the 2 it implements itself.
But my question is, can I achieve the same goal using a more concise design?
Footnotes
Each object actually implements several of common methods. Take TextBox, ComboBox and SelectBox they all should be able to SetText, however only CombBox and SelectBox should be able to use Select.
The cleanest way to do what you are asking is to implement protected helper methods within your base class that decompose the problem of "a lot of duplication" into smaller pieces that can be composed in your concrete method implementations, like this:
public abstract class WebObject {
protected void SetTextImpl() { /* Implementation */ }
protected void GetTextImpl() { /* Implementation */ }
}
Then in your derived classes, implement only the applicable interfaces and appropriate methods:
public class TextBox: WebObject, IWriteable, IReadable {
public void SetText() { SetTextImpl(); }
public void GetText() { GetTextImpl(); }
}
public class Span: WebObject, IReadable {
public void GetText() { GetTextImpl(); }
}
If you know that all the subclasses will be IReadable, you can simplify further:
public abstract class WebObject : IReadable {
protected void SetTextImpl() { /* Implementation */ }
protected void GetTextImpl() { /* Implementation */ }
// Implement IReadable -- this could be combined with GetTextImpl() but
// is implemented separately for consistency.
public void GetText() { GetTextImpl(); }
}
public class TextBox: WebObject, IWriteable {
public void SetText() { SetTextImpl(); }
}
public class Span: WebObject, IReadable {
}
If the code for those two methods will always be the same or mostly the same, you could create another abstract class (ex: WebObjectReadWrite) that inherits from WebObject and implements the interface.
public abstract class WebObjectReadWrite : WebObject, IReadable, IWritable
{
// Could be made virtual if some subclasses need to overwrite default implementation.
public void Read()
{
// Implementation
}
// Could be made virtual if some subclasses need to overwrite default implementation.
public void Write()
{
// Implementation
}
}
public class TextBox : WebObjectReadWrite
{
}
This could, however, lead to multiple inheritance problems or inheritance relationships that don't make sense. Another option is to use the strategy pattern (in way) to delegate the read / write operations to other classes that can be reused.
public class TextBox : WebObject, IReadable, IWriteable
{
private IReadable _readable = new TextReader();
private IWriteable _writeable = new TextWriter();
public void Read()
{
_readable.Read();
}
public void Write()
{
_writable.Write();
}
}
public class Span : WebObject, IReadable
{
// Reused class.
private IReadable _readable = new TextReader();
public void Read()
{
_readable.Read();
}
}
public class TextReader : IReadable
{
public void Read()
{
// Reusable implementation
}
}
This isn't quite the strategy pattern because you are not allowing the caller to choose the implementation of IReadable and IWriteable. However, it does allow you to reuse IReadable and IWriteable classes.
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.
I have a abstract class named Vehicle:
public abstract class Vehicle {
public void run() {
addToRunningVehicleList();
}
}
I want that every classes that extends Vehicle must call super.run() if they override run method. For example:
public class Car {
#Override
public void run() { // Error here because does not call super.run()
carRunningAnimation();
}
}
Is it possible in OOP concept, or Java/C#?
EDIT: Following Petar Ivanov, I have this code:
public abstract class Vehicle {
public final void run() {
Log.e("Run", "Add To List");
runImp();
}
public void runImp() {}
}
public class Car extends Vehicle {
#Override
public void runImp() {
Log.e("Run", "Run in Car");
}
}
However, it's not very good for public APIs. When extending Vehicle, the end-users must override runImp, but then they have to call run() method, so I have to make public both run and runImp, which make nothing better.
Here is how I would do it (C#):
public abstract class Vehicle {
public void Run() {
//code that will always run
addToRunningVehicleList();
//code that can be overriden
RunImpl();
}
protected virtual void RunImpl() { }
}
public class Car : Vehicle {
protected override void RunImpl() {
carRunningAnimation();
}
}
You can make the RunImpl protected to make sure it can't be called outside the subclasses of Vehicle.
If you need to require certain code to run in addition to the child class' implementation, perhaps you need to split this into multiple methods:
(C# example)
public abstract class Vehicle
{
public void Run()
{
// Code that always runs before...
RunCore();
// Code that always runs after...
}
protected virtual void RunCore()
{
}
}
Remember who you are designing for. If it's an internal piece of code a comment will suffice. If it's a public API and you want people to inherit then you need to write a piece of documentation telling them to do it.
In C# you can do some sneaky stuff with virtual and non-virtual methods but in Java as all inheritence is virtual it's a lot harder to enforce this without using an abstract base class.
Using an ABT may limit your ability to provide further inheritence and force modification of other code.
I have a c# Class that has lots of virtual methods, some of these methods are essentially abstract ( they are fully implemented in subclasses and the base class is empty).
To get it to compile i am throwing an InvalidOperationException in the base class with a comment on what should be done. This just feels dirty.
Is there a better way to design my classes?
edit:
It is for the middle tier of an application that will be ran in canada, half of the methods are generic hence the virtual. and half of the methods are province specific.
Public class PersonComponent()
{
public GetPersonById(Guid id) {
//Code to get person - same for all provinces
}
Public virtual DeletePerson(Guid id) {
//Common code
}
Public virtual UpdatePerson(Person p) {
throw new InvalidOperation("I wanna be abstract");
}
Public Class ABPersonComponent : PersonComponent
{
public override DeletePerson(Guid id)
{
//alberta specific delete code
}
public override UpdatePerson(Person p)
{
//alberta specific update codecode
}
}
hope this makes sense
Mark the base class as abstract, as well as the methods that have no implementation.
Like so
public abstract class BaseClass
{
public abstract void AbstractMethod();
}
public class SubClass: BaseClass
{
public override void AbstractMethod()
{
//Do Something
}
}
You can't have abstract methods outside of an abstract class. Marking a class as abstract means you won't be able to instantiate it. But then it doesn't make any sense to. What are you going to do with a class that doesn't implement the methods anyway?
Edit: From looking at your class, yeah I'd make PersonComponent abstract along with the UpdatePerson method. Either that, or if UpdatePerson just doesn't do anything for a PersonComponent keep it as is, but make the UpdatePerson method empty for PersonComponent.
Think about your object hierarchy. Do you want to share common code for all your derived classes, then implement base functionality in the base class.
When having shared base code, please notice the Template pattern. Use a public method and chain it to a protected virtual method with the core/shared implementation. End the shared implementation methodname with "Core".
For example:
public abstract class BaseClass
{
protected virtual void DeletePersonCore(Guid id)
{
//shared code
}
public void DeletePerson(Guid id)
{
//chain it to the core
DeletePersonCore(id);
}
}
public class DerivedClass : BaseClass
{
protected override void DeletePersonCore(Guid id)
{
//do some polymorphistic stuff
base.DeletePersonCore(id);
}
}
public class UsageClass
{
public void Delete()
{
DerivedClass dc = new DerivedClass();
dc.DeletePerson(Guid.NewGuid());
}
}