I am trying to setup a scenario where we can create a common set of models for our workgroup and then implement or extend them if/when needed.
I have the following setup:
namespace Workgroup.DomainClasses
{
public abstract class WorkGroupOrder
{
private ICollection<WorkGroupItems> _items;
protected WorkGroupOrder()
{
_items = new List<WorkGroupItems>();
}
protected int OrderId { get; set; }
protected virtual ICollection<WeAccount> Items
{
get { return _items; }
set { _items = value; }
}
}
}
I would prefer that users not use the base WorkGroupOrder so would like to set this up so they are required to implement their own version of the class. If all is good with the base class it would simply be an empty class calling the base constructor but otherwise properties and functionality could be added. The idea for this is that the Workgroup domain is much larger than may be necessary for a single project but we'd like to drive all work from this common model.
using Workgroup.DomainClasses;
namespace Project.DomainClasses
{
public class Order : WorkGroupOrder
{
public string OrderComment { get; set; }
}
}
The issue I'm having is that I'm required to reference both domain models to implement. There is an error below in the Testing() method that I must also reference Workgroup.DomainClasses in order to instantiate the class. I'm not that familiar with abstract classes so is this just the nature of the abstract type? I'd prefer to remove this dependency if possible.
using Project.DomainClasses;
namespace Project.DataLayer
{
public class Testing
{
public void Testing()
{
Order o1 = new Order();
}
}
}
A few questions.
Does this organization make sense or is there a better way to
support my desire of providing a common model that could potentially
be extended?
How would I access the properties of both the base
abstract class and the concrete class? In my Testing() method I am unable
to access `o1.OrderId` for example.
I'd like to remove meta-knowledge of the abstract class from the developer. How would it be best to execute the constructor without explicitly requiring the developer to do so?
Ultimately I'd like to require developers to create their own instance of the class to avoid implementing the base model directly. I'd also like to build in the proper visibility to prevent them from going directly to the Workgroup objects.
It seems like there are a few different issues in play here.
Firstly, using a namespace to try to segregate out base functionality is not a viable option because all derived classes will need access to the namespace of the base class by default (in order to inherit). Any developers extending your base classes will need access to the namespace containing the base classes.
Controlling access to functionality or data is generally best accomplished using access modifiers (eg, public, protected, or private) or public properties with public get{ } and protected set{ } or private set{ } (ie, getters and setters with different acccess levels). If you wish to hide implementation details from the end users, then an interface is the right approach to take (like an API, for example).
Secondly, by marking any class abstract you will automatically deny other developers the ability to instantiate that class directly. They will be forced to create a class derived from the abstract class (aka, a "concrete" class) in order to use the abstract base class's methods and properties.
Third, the reason you couldn't access property o1.OrderId in your test code is because that property has an access modifier of protected. This means that only the base class and its derived classes can internally access this property. To expose it to the end user, it must be marked public.
Unfortunately, I do not really understand what you mean with "setup a scenario where we can create a common set of models for our workgroup and then implement or extend them if/when needed". What is a workgroup in your context? And why should (all) other classes derive from it?
Anyway, you cannot use o1.OrderID because this property is protected which means it is only visible within the scope of WorkOrderGroup and subclasses that derive from it. Make this property public and you can access it everywhere.
Furthermore, and please take no offence, but it seams that you somewhat struggle with the object-oriented concepts of encapsulation and inheritance. I would advise you to have a look at these concepts (you can e.g. start here) and get a good understanding what they do and how to use them when implementing functionality. With the current information, I would not advise you to structure your code like you explained in your question.
Finally, some general hints on practices in object-oriented languages:
Favor composition over inheritance: this means that you should extend existing classes by encapsulating them instead of inheriting from them. In most cases this is more flexible.
Take a look at the SOLID princples: they provide really good instructions that you should consider on every class you write.
Take a look at Design Principles and maybe Domain-Driven-Design: there is a lot of guidance on the internet out there with a lot of examples. With every examples you get a better feeling how to approach new problems and how to model them in OOD.
I hope this answer guides you in the correct direction.
Related
Is it good practice to define an interface, implement the interface in a base abstract class, give it default behavior and then inherit from the base class?
Or it that overkill?
Whether to use an interface or an abstract class are two entirely different questions. It might happen that the answer to both is yes but one has nothing to do with the other.
Unless you're absolutely certain that you're going to need multiple classes that inherit from a base class and share certain methods, I wouldn't plan up front to use inheritance. When we start off envisioning some perfect textbook class hierarchy it often gets complicated and doesn't work out. It often makes more sense when you're refactoring or if you find yourself writing a similar class and don't want to duplicate code.
Writing an interface and then implementing it is a good practice when you're creating something that another class is going to depend on (which is very often.) For example, if you know that your class is going to depend on another class that "does something" then you can momentarily pause working on the first class to write the IDoesSomething interface, and finish the first class that depends on IDoesSomething. You haven't figured out what the implementation is yet, but it doesn't matter because the class you're already writing just depends on the interface. (Inversion of Control - good practice.) Then you can write a class that implements IDoesSomething.
Just to expound on that with an example. Suppose I'm writing a class that provides a Menu object which contains a nested list of MenuItem objects:
public class MenuProvider
{
public Menu GetMenu(string menuId)
{
//code that gets the menu
return menu;
}
}
Then I realize that I'm going to need to filter out certain menu items before returning it. That might be based on configuration settings, the particular user, or anything else.
I might write this interface:
public interface IMenuFilter
{
void FilterMenu(Menu menu);
}
and then modify my original class like this:
public class MenuProvider
{
private readonly IMenuFilter _menuFilter;
public MenuProvider(IMenuFilter menuFilter)
{
_menuFilter = menuFilter;
}
public Menu GetMenu(string menuId)
{
//code that gets the menu
//filter the menu
_menuFilter.FilterMenu(menu);
return menu;
}
}
I don't know what the implementation of IMenuFilter is going to be. In practice it might end up being a composite of a bunch of separate classes that each perform one type of filtering. But the point is that I don't need to stop what I'm doing on MenuProvider to figure that out. I can write this class and even test it with a mocked IMenuFilter, and then move on to write the specifics of that filter.
Do you have common functionality that you want to share amongst implementations of this interface? If so, then create an abstract base class. Otherwise, don't worry about it now. You can always add one later. But programming to interfaces is almost always a good idea.
Generally, you will use either an interface or inheritance. I don't normally don't use both with the same class.
Use inheritance when you want to inherit functionality from the base class.
Use an interface when you want disparate classes to implement some same core functionality, but not necessarily share code.
Imagine that we have classes as such:
public abstract class WebPage
{
public WebPage()
{ ... }
}
public class LoginOrSignUpWebPage : WebPage, ILogin, ISignUp
{
private Info _loginInfo;
private Info _signUpInfo;
public readonly Info LoginInfo { get { return _meats; } }
public readonly Info SignUpInfo { get { return _legs; } }
public class LoginOrSignUpWebPage(Info loginInfo, Info signUpInfo) : base()
{ ... }
}
We can see that WebPages would want to have different ways of being instantiated based on different interfaces they implement.
Whilst it'd feel okay implementing individual constructions for each class, I would prefer to use inheritance to base the object construction upon. The reason for this is because another object may implement the same interfaces and would have the same way of being instantiated.
I have thought about using some sort of (abstract?) Factory method, but I'm not sure how this would work.
Question:
Right to the point, what do you think would be the best way to base construction of an object based upon what interfaces it inherits? This would include (potentially) different parameters, and at minimum different data passed depending on the implemented interface.
We can see that WebPages would want to have different ways of being instantiated based on different interfaces they implement.
No, they wouldn’t. Interfaces define how types should look like to the outside. They provide no implementation detail and also no information about the constructor or the construction process. If you have an object of the type of an interface, all you know is that you can access the properties and methods that were defined in the interface.
The way you declare your WebPage type, it is fixed to implement both ILogin and ISignUp. As such it is absolutely required to implement whatever these two interfaces specify. And every object of type WebPage will always provide what both interfaces require.
It is not necessary to make the construction of an object based on the interfaces it is implementing, simply because the interfaces you are implementing is known at compile time and can’t be changed later. So for the type implementing an interface, you just specify directly how that is constructed.
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.
I really don't get it.
If the base class is abstract and only intended to be used to provide common functionality to public subclasses defined in the assembly, why shouldn't it be declared internal?
I don't want the abstract class to be visible to code outside the assembly. I don't want external code to know about it.
UPDATE: This question was the subject of my blog on November 13th of 2012. See it for some more thoughts on this issue. Thanks for the great question!
You're right; it doesn't have to be that way. Other OO languages allow "private inheritance", whereby the fact that D inherits from B can only be taken advantage of by code that has the ability to see B.
This was a design decision of the original C# designers. Unfortunately I am away from my desk right now - I'm taking a couple of days off for the long weekend - so I don't have the language design notes from 1999 in front of me. If I think of it when I get back I'll browse them and see if there is a justification for this decision.
My personal opinion is that inheritance should be used to represent "is a kind of" relationships; that is, inheritance should represent the semantics of the domain being modelled in the language. I try to avoid situations where inheritance is used as a code sharing mechanism. As others have mentioned, it's probably best to prefer composition to inheritance if what you want to represent is "this class shares implementation mechanisms with other classes".
By inheriting from a class, you expose the functionality of the base class through your child.
Since the child class has higher visibility than its parent, you would be exposing members that would otherwise be protected.
You can't violate the protection level of the parent class by implementing a child with higher visibility.
If the base class is really meant to be used by public child classes, then you need to make the parent public as well.
The other option is to keep your "parent" internal, make it non-abstract, and use it to compose your child classes, and use an Interface to force classes to implement the functionality:
public interface ISomething
{
void HelloWorld();
}
internal class OldParent : ISomething
{
public void HelloWorld(){ Console.WriteLine("Hello World!"); }
}
public class OldChild : ISomething
{
OldParent _oldParent = new OldParent();
public void HelloWorld() { _oldParent.HelloWorld(); }
}
I think the closest thing you can do is prevent other assemblies creating the abstract class by making its constructor internal, to quote from MSDN:
An internal constructor prevents the abstract class from being used as the base class of types that are not in the same assembly as the abstract class.
You can then try adding an EditorBrowsableAttribute to the class to try and hide it from IntelliSense (though, I've had mixed results using it to be honest) or put the base class in a nested namespace, such as MyLibrary.Internals to seperate it from the rest of your classes.
I think you're mixing concerns here, and C# is to blame, actually (and Java before it).
Inheritance should serve as a categorization mechanism, whereas it's often used for code reuse.
For code reuse it's always been known that composition beats inheritance. The problem with C# is that it gives us such an easy way to inherit:
class MyClass : MyReusedClass { }
But in order to compose, we need to do it by ourselves:
class MyClass {
MyReusedClass _reused;
// need to expose all the methods from MyReusedClass and delegate to _reused
}
What's missing is a construct like a trait (pdf), which will bring composition to the same usability level as inheritance.
There's research about traits in C# (pdf), and it would look something like this:
class MyClass {
uses { MyTrait; }
}
Although I'd like to see another model (that of Perl 6 roles).
UPDATE:
As a side note, the Oxygene language has a feature that lets you delegate all members of an interface to a member property that implements that interface:
type
MyClass = class(IReusable)
private
property Reused : IReusable := new MyReusedClass(); readonly;
implements public IReusable;
end;
Here, all interface members of IReusable will be exposed through MyClass and they'll all delegate to the Reused property. There are some problems with this approach, though.
ANOTHER UPDATE:
I've begun implementing this automatic composition concept in C#: take a look at NRoles.
I think this would violate the Liskov Substitution Principle.
In cases like this, I have used internal classes and prefer composition over inheritance. Is there anything about your design that prohibits containing all such functionality in your internal class, and then have your public classes contain an instance of this internal class?
I am in a situation where i need to use multiple inheritance in C# with WPF.
I am making a control lets say Control-1 that is derived from combobox control. I added some dependency properties as well as methods to the my control Control-1 class. Most of the properties and methods(infact the same implementation of properties and methods) in my control-1 can also be used in another control called Control-2 but that control should not be derived from combobox control (as is the case with Control-1).
I want to seperate the common dependency properties and methods in another class but seperating it in another class require me to derive my control class (control-1) from combobox control and the common class containing properties and methods.
Is there a design that can solve my problem.
Note: The question is about C# using the WPF framework's dependency properties, which require static members and not just on C# in general.
Related
How to reuse code when multiple inheritance is not an option?
Multiple Inheritance in C#
How To Implement Shared Behavior Between Classes (Without Multiple Inheritance Of Course) in C#
What are some good alternatives to multiple-inheritance in .NET?
One solution that may work for you is to create an interface instead, and put your implementation in extension methods.
sounds to me like a good time to use the decorator pattern here are some resources:
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_wrapper302122006080905AM/csharp_wrapper3.aspx
http://andrewtroelsen.blogspot.com/2009/04/decorator-pattern-extension-methods.html
I can't speak directly to the Dependency Property situation, so I'll talk about the general problem, if that's helpful.
You can't do multiple inheritance of implementation in C#. However, you can attach an interface.
So you can define the interface:
interface IWhatever
{
...
}
And then, you can implement the functions of that interface in a class like so:
class M : IWhatever
{
}
And, now, you take the classes that you would like to have this additional functionality on:
class B : MustExtend, IWhatever
{
private M myMImpl = new M();
// implement functions, call to 'myMImpl' for implementation.
}
This is called 'composition'. It can be useful in some circumstances, and is generally underused, I'd think :)
I've used stubs that are called from the derived class and take the class of base type as an argument. This leaves me with several one line functions. Too bad.
The problem with extension methods and interfaces is that dependency properties require the declaration of static members and public properties, for example:
public PermissionEnum Permission
{
get { return (PermissionEnum)GetValue(PermissionProperty); }
set { SetValue(PermissionProperty, value); }
}
public static readonly DependencyProperty PermissionProperty =
DependencyProperty.Register("Permission", typeof(PermissionEnum), typeof(SecurityMenuItem), new FrameworkPropertyMetadata(PermissionEnum.DeliveryView));