I have common data across different instances of derived classes.
So to share the common data properties, I made them static in base class.
But the static common properties can not be declared in the interface.
If we try, we get the error:
"cannot implement an interface member because it is static."
Is there any known design pattern or a best practice for this kind of requirement?
You're better off using an abstract base class instead.
Interface defines just that, an interface. As soon as you have anything "real", be it method implementation or shared data, you need a class, an abstract one in this case.
Alternative would be to keep the interface, but add singleton to hold the data related to the classes which implement the interface. If you need to use an interface, then this is the way to go, I think. Just name the singleton so, that it is obvious it's logically linked to the interface, and document, that implemenations of the interface should use it.
In your case, static class with the data might be enough, instead of full singleton implementation, but I will not get into this here, the whole "static classes vs singletons" is somewhat controversial subject.
Related
I have 2 objects that inherit from an interface i created which worked nicely. The Objects are injected into another object calls the methods of both the object. The methods of the objects perform some simple XML manipulation which is then returned to the worker object.
I now have a change request which affects one object that inherits from the interface but not the other and I'm at a loss as to how I should handle this. I've created a couple of new methods and I simply throw a not implemented exception if its not used. This doesn't seem "Best Practice" to me. What is the best way to handle this scenario?
I think that this is a situation where the Interface Segregation Principle comes in place.
If you find yourself having two objects for which it does not make sense to expose the same set of public members, then probably they should not implement the same interface. Or at least not only the same interface. You have two options here, depending on your application's logic:
Leave the original interface as is, and the first class (the one not needing extra methods) unmodified. Define a new interface only for the new methods, and make the second class implement both interfaces.
Define a new interface that inherits from the old one and contains the new methods. Leave your first class unmodified, and have your second class implement the new interface.
Implementing an interface and doing nothing more than throwing an exception in some methods is indeed a bad practice, as it breaks the Liskov substitution principle.
An interface doesn't "need" to be fully implemented... Even in .NET there are classes that implement partially an interface (and that throw NotSupportedException() when used in an "illegal" way)... For example arrays are IList<> that don't support Add() or Remove()...
Or the Stream abstract class, that has an additional "pattern": CanRead, CanWrite, CanSeek, ..., so there are methods, and properties that tell if it is legal to use those methods.
Another way is to use an additional interface, and try casting it with as operator. The Entity Framework for example "returns" IQueryable<T>, that "are" IEnumerable<T>... But those objects even support the IDbAsyncEnumerable<T> interface... but not all the IQueryable<T> are IDbAsyncEnumerable<T>. You have to do a cast and see if the interface is present or not.
You could extend the interface like this:
public interface SimpleInterface
{
void SimpleMethod();
void OtherMethod();
}
public interface ExpandedInterface : SimpleInterface
{
void ExpandedMethod();
void OtherExpandedMethod();
}
That way you could declare, on your client code, if you really need an expanded interface implementer (in which case you should pass only an instance of the subset of concrete classes that implement ExpandedInterface) or it is enough to use a SimpleInterface implementer (in which case you can pass either).
The situation you presented (needing to add funcion to one object, but not other) has more to do with the client code than the interface implementers themselves. You have to think: "in this client class, what do I really need: an instance of SimpleInterface, or an instance of ExtendedInterface?"
Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.
There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)
For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
public abstract List<SoldProduct> FetchData();
public bool UploadData(List<SoldProduct> productsSold)
{
// here you can do code to save data in common destination
}
}
public class ExcelImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from excel
}
}
public class XMLImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from XML
}
}
public class AccessDataImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from Access database
}
}
and calling can be like this
static class Program
{
static void Main()
{
List<SoldProduct> lstProducts;
ExcelImporter excelImp = new ExcelImporter();
lstProducts = excelImp.FetchData();
excelImp.UploadData(lstProducts);
XMLImporter xmlImp = new XMLImporter ();
lstProducts = xmlImp.FetchData();
xmlImp.UploadData(lstProducts);
AccessDataImporterxmlImp accImp = new AccessDataImporter();
lstProducts = accImp .FetchData();
accImp.UploadData(lstProducts);
}
}
So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.
This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.
In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post
As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.
Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."
The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.
Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably. While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method. Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }
[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations. Unfortunately, I know of no plans to add any such functionality.
The compiler doesn't seem to mind it so far but I just wanted to double check whether I'm setting myself up for failure in any way by implementing certain methods in my abstract class.
An abstract class usually has one or more abstract method. So yes it can have some method implemented. The goal is to force the user to implement these methods to have an object working. Sometimes abstract classes are used to provide a 'base' implementation of some interfaces, leaving the final user to specify just the key methods. You can also have an abstract class without any abstract method: in this case you are asserting you must derive from that class in order to use it.
It's common to have some implementation in abstract classes.
If there is no implementation at all, consider using an interface instead of an abstract class.
Perfectly fine to implement some methods and leave others abstract.
If all methods had to be abstract, you might as well use an interface for it.
Yes. abstract class cannot be instantiated (you have to instantiate a class that inherits from your abstract class), but it can contains implementations.
it's fine and allowed, an abstract class has at least a member (method/property) not implemented so it cannot be instantiated.
an interface is also called pure abstract class which means it's 100% abstract, so does not allow you to specify any implementation.
keep in mind that there are lots of articles and opinions about never deriving a concrete class from another concrete class but only from abstract ones... at least this was the trend in C++ up to some years ago, then I moved to the C# side, started working more and had no time to keep reading those nice articles... :)
I have a project where quite a few functions and variable getters will be defined, abstractly. My question is should I use an abstract class for this(with each function throwing NotImplementedException), or should I just use an interface? Or should I use both, making both an interface and then an abstract class implementing the interface?
Note, even though all of these functions and such may be defined, it does not mean they will all be used in all use cases. For instance, AddUser in an authentication class may be defined in an interface, but not ever used in a website due to closed user sign up.
In general, the answer to the question of whether or not to use inheritance or an interface can be answered by thinking about it this way:
When thinking about hypothetical
implementing classes, is it a case
where these types are what I'm
describing, or is it a case where
these types can be or can do what I'm
describing?
Consider, for example, the IEnumerable<T> interface. The classes that implement IEnumerable<T> are all different classes. They can be an enumerable structure, but they're fundamentally something else (a List<T> or a Dictionary<TKey, TValue> or a query, etc.)
On the other hand, look at the System.IO.Stream class. While the classes that inherit from that abstract class are different (FileStream vs. NetworkStream, for example), they are both fundamentally streams--just different kinds. The stream functionality is at the core of what defines these types, versus just describing a portion of the type or a set of behaviors that they provide.
Often you'll find it beneficial to do both; define an interface that defines your behavior, then an abstract class that implements it and provides core functionality. This will allow you to, if appropriate, have the best of both worlds: an abstract class for inheriting from when the functionality is core, and an interface to implement when it isn't.
Also, bear in mind that it's still possible to provide some core functionality on an interface through the use of extension methods. While this doesn't, strictly speaking, put any actual instance code on the interface (since that's impossible), you can mimic it. This is how the LINQ-to-Objects query functions work on IEnumerable<T>, by way of the static Enumerable class that defines the extension methods used for querying generic IEnumerable<T> instances.
As a side note, you don't need to throw any NotImplementedExceptions. If you define a function or property as abstract, then you don't need to (and, in fact, cannot) provide a function body for it within the abstract class; the inheriting classes will be forced to provide a method body. They might throw such an exception, but that's not something you need to worry about (and is true of interfaces as well).
Personally, I think it depends on what the "type" is defining.
If you're defining a set of behaviors, I would recommend an interface.
If, on the other hand, the type really defines a "type", then I'd prefer an abstract class. I would recommend leaving the methods abstract instead of providing an empty behavior, though.
Note, even though all of these functions and such may be defined, it does not mean they will all be used in all use cases.
If this is true, you should consider breaking this up into multiple abstract classes or interfaces. Having "inappropriate" methods in the base class/interface really is a violation of the Liskov Substitution Principle, and a sign of a design flaw.
If you're not providing any implementation, then use an interface otherwise use an abstract class. If there are some methods that may not be implemented in subclasses, it might make sense to create an intermediate abstract class to do the legwork of throwing NotSupportedException or similar.
One advantage of abstract classes is that one can add to an abstract class new class members whose default implementation can be expressed in terms of existing class members, without breaking existing inheritors of that class. By contrast, if any new members are added to an interface, every implementation of that interface must be modified to add the necessary functionality.
It would be very nice if .net allowed for an interface to include default implementations for properties, methods, and events which did not make any use of object fields. From a technical standpoint, I would think such a thing could be accomplished without too much difficulty by having for each interface a list of default vtable entries which could be used with implementations that don't define all vtable slots. Unfortunately, nothing like that ability exists in .net.
Abstract classes should be used when you can provide a partial implementation. Use interfaces when you don't want to provide any implementation at all - just definition.
In your question, it sounds like there is no implementation, so go with an interface.
Also, rather than throwing NotImplementedException you should declare your method/property with the abstract keyword so that all inheritors have to provide an implementation.
#Earlz I think refering to this: Note, even though all of these functions and such may be defined, it does not mean they will all be used in all use cases. is directly related to the best way to 'attack' this problem.
What you should aim at is minimizing the number of such functions so that it becomes irrelavant (or at least not that important) if you use either or. So improve the design as much as you can and you will see that it really doesn't matter which way you go.
Better yet post a high level of what you are trying to do and let's see if we can come up together with something nice. More brains working towards a common goal will get a better answer/design.
Another pattern that works in some situations is to create a base class that is not abstract. Its has a set of public methods that define the API. Each of these calls a Protected method that is Overideable.
This allows the derived class to pick and choose what methods it needs to implement.
So for instance
public void AddUser(object user)
{
AddUserCore(user);
}
protected virtual void AddUserCore(object user)
{
//no implementation in base
}
I have a quite basic question:
When should we decide to use Interface or Class for a specific class?
For example: says we have 2 classes, Customer and Doctor.
In Inheritance (class): we could set these 2 classes to inherit from parent class Person.
Couldn't we do the same with Interface? Says we have InterfacePerson and have both Customer and Doctor implement the interface?
Thus, this lead to: when do we decide to use one over the other and vice versa?
Read the wikipedia article
Read a book, then read the chapters about OOP again
In your example, Person should be a class, because it contains implementation details that are common to both a Doctor and a Customer.
interfaces don't have (and don't need) implementation details - they only denote what objects which implement them are doing. Not how. Why is this useful? Because when you are using the object you don't care how it's going to do its job.
Let's take a look at a simple example - there is an interfaces Comparable (in Java at least). It denotes that its implementors can be compared with each other. So you can have two classes:
class Doctor implements Comparable {..}
class Customer implements Comparable {..}
Now you can have a common method which takes any set of objects which implement Comparable and call comparable1.compareTo(comparable2), because you know they can perform comparison - it's denoted by their interface.
Interface - describe the behavior
Class - do the behavior
A class extending another class inherits the behavior. On the other hand, implementing an interface just says it need to behave that way but the class still has to know the how-to.
Besides single inheritance limitations, code using interfaces are easier to refactor and test, e.g. provide a mock implementation for a database access object in unit tests.
So, the real answer is, it depends on your design.
It may be that you use interfaces to describe behavior, and abstract parent classes to implement the behavior that can be inherited by subclasses. Or maybe the subclasses are so different that each implements the interface in their own way.
Interfaces are used to enforce certain Methods/Properties. In a nutshell- an interface is a set of rules.
A class can be used to inherit/override base functionality.
Have a look at
Difference between class and
interface in C#?
C#: Interface vs. Class
Abstract Class versus Interface
interface (C# Reference)
In object modeling, one shouldn't use inheritance for people and their roles. One should instead model them with two associated objects. That is, using composition instead of inheritance.
So in a way, of three alternatives, your discussing the two wrong ones: inheritance and interfaces for modeling parties and roles.
A class is a template for a set of objects. Those objects have behavior, (and typically) state and characteristics. In regards to behavior, each object has an (implicit) interface already: the set of methods that can be externally called on it.
The question then becomes, why should you create a named interface, a subset of the interface already provided by an object?
One wants to represent a subset of behavior so different classes of objects can be treated polymorphically.
One wants to constrain the possible behavior of an object exposed to another, to a subset of its (implicit) interface because the object is acting in a different context.
Parent Class is the one which will have bare minimum properties common to all of its sub classes.
But Interface is a contract which tells its implantations to provide if it is not an abstract class.
And the One important difference between a class and interface is that
class inheritance will give relation between two common subclasses.
Where as Interface implementation gives a relation between two uncommon classes.
First thing to remember, Classes can be instantiated, Interfaces cannot.
Secondly, a Class can only extend ONE Class. Interfaces are not limited by this and so we can have multiple inheritance like so
public class foo extends Person implements Man, Mammal
foo is a Person. It is also a Man and a Mammal;
The only issue is Interfaces cannot have variables or method implementations where as a class(or abstract class for that matter) can.
Generally I would say stick with interfaces and avoid abstract classes if you can.
Simply put, you use classes when there is code/implementation involved and interfaces when it is just interface descriptions. When referring to objects in your code, prefer to refer to the interfaces as it makes it easier to replace the actual implementation (or add more and different implementations).
And yes, both Docor and Customer/Patient are likely to implement or extend Person.
Think of the interface as a contract. The class may commit to the contract (implement the interface)
Suppose you have class Person with subclasses Doctor and Patient. Then you'd have interface Treatable with the method getSymptoms() implemented by Patient and interface Treating with method cure(Treatable) implemented by Doctor. Most likely cure(Treatable) would call getSymptoms() at some point ...
In C#, multiple inheritance can be achived through Interface only.
Based on u r business requirement if there is a need that your class needs multiple inheritance going fwd, then use Interface else use class.
Also all members of Interfaces should be given defination in class i.e. interface members are must-implemented members.
class suggests that object that inherits base class is some kind of this class
if you use interface it only shows that your class have some common behaviour that interface describes