where to put the GetItems static method? + inheritance question - c#

I have Item class:
public class Item {
public long Id {get; protected set;}
public string Name {get; protected set;}
}
and now I want to add a function that retrieve items from the db according to filters. This should be static method that returns Item[]:
public static Item[] GetItems(long? itemId, string itemName) {
//Do Search in the db for items with Id=itemId (in case itemId is not null) and
//with Name=itemName (in case itemName is not null)
return itemsList.ToArray();
}
The question is where to put this method?
1. should I create a new class for this? How will I call this class?
2. should I put this method in Item class?
Another question:
In case I want to inherit from Item class. How can I force the child classes implement such GetItems method?

I would recommend a simple repository pattern implementation. You could create a class called ItemRepository that knows about your Item object and your DAL implementation. The repository would simply call into the DAL to get any data it needs and then return business objects back to the consumer.
This is very simple to implement, and if you create an interface to go along with it (ex: IItemRepository), unit testing becomes very easy because you'll be able to mock the repository and pass it along to any object that consumes it. If you make everything static, then testing is much harder, so I wouldn't recommend it.
As for inheritance: if you want to define general method signatures and properties that should be available on every Repository object, then use an interface to specify exactly what each repository should have in common. If you want to provide a base repository skeleton, then an abstract may be more fitting.

GetItems (plural) does not, to me, sound like something that should be a member of Item (singular). Especially since Item is so simple. I would create a static utility class (the factory pattern) called ItemUtility that has GetItems.
To answer your second question: if a class inherits from Item it will also inherit any concrete implementations of its member. So if there was a LoadItem method on Item, and I made SpecialItem : Item, then SpecialItem.LoadItem() would actually just be the Item.LoadItem() code. If you want to make Item.LoadItem() overridable then you can use the "virtual" modifier on the method (which would give SpecialItem the option of doing its own thing with that method).
Item could also be an abstract class if you only intend it to be used as a boilerplate base class for other more complex classes like SpecialItem.
Another option would be to create an IItem interface, and make LoadItem (and any other required member) part of the interface definition.

The data access should go in a separate class. Data access should be stored in a separate layer than the object definition, following the Separation of Concerns concept.
If you want to force all inherited objects to implement a method, you can make it abstract.

Is there any specific reason you want to make the method static? If you want to inherit the GetItems method in your child classes, you cannot make it static. To answer your questions in order:
1) Yes. Create a new class called something like ItemManager that makes the actual call to the DB layer to get the Items. That way you are separating your Data Access code from business logic
2) You should create a method in Item Class that calls the method in ItemManager to get the actual data.
3) Mark the method you created in step 2 as virtual if you want child classes to override the method to provide their own implementation. If you want to force them to override and need no implementation in the base class itself, then mark the base class as abstract so child class must override it

Related

Interface & Base Abstract Class c#

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.

Object oriented design: when to make an abstract class

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.

C# Abstract Method Inheritance and Hiding Methods Unintentionally

I've got a question about accidentally hiding abstract methods.
I'm creating a basic Entity class as an interface from which to create all other entities in the game I'm working on.
From this Entity class, I have created several derived classes. There are things like MovingEntity, Trigger, Door, etc... Many of these children classes also have children derived from them. For example, MovingEntity has classes like Projectile and EnemyUnit as children.
In my base Entity class, I have methods like Update() and Render() that are abstract, because I want every entity to implement these methods.
Once I get down to the second level, however, -that's- where I hit my question/problem. I'll use the Trigger class, for example. Trigger derives from the base Entity class, but Trigger still has its own children (like TriggerRespawning and TriggerLimitedLifetime). I don't want to instantiate a Trigger object, so I can keep that class abstract - I will only create objects from Trigger's children classes. But what do I do with the abstract methods that Trigger is supposed to implement from Entity?
I thought I could just basically use the same code in Trigger as I did in Entity. Declare the same method, same name, same parameters, and just call it abstract. Then, Trigger's children would be forced to implement the actual functions.
This didn't work, however, because in the Trigger class, my build errors say that I am hiding the abstract methods from the base Entity class.
How can I pass down the idea of forcing the eventual children to implement these abstract methods without making all of the parents in-between implement them? Do I need to use virtual on the first round of children classes?
I haven't been able to find a good answer on this so far, so I decided to break down and ask. Thanks in advance, guys.
Just don't redeclare the methods at all - the eventual concrete classes will have to implement all the abstract methods still unimplemented all the way up the tree:
public abstract class Foo
{
public abstract int M();
}
public abstract class Bar : Foo
{
// Concrete methods can call M() in here
}
public class Baz : Bar
{
public override int M() { return 0; }
}

Force a class to implement a method without restricting the parameters in C#

I have an interface that contain the method void DoCommand();. now I'll force all the child classes to inherit the base class method DoCommand(). but I need each class to define a different parameter for this method to serve the page with the proper parameters.
How can I do that ?
Is it even possible !
N.B: I'm building an ASP.NET web application and the page that will implement the method already inherits from the page base class, so I think Interface is my only option. as only one base class is allowed in inheritance of classes.
Edit
I hope illustrating what I need this for could let you help me to come up with a better design and stick to the rich concepts like OOP.
I have 19 pages, each page will need a method to collect data from the input controls in this page and put it in an object (19 pages .. 19 types of objects)
so I need Collect(); to be forced, then each page will take as a parameter the proper type of object .. does it make more sense ?
btw if you think that my design is totally wrong, a whole new design patterns are welcome (Y)
It's not possible. The closest you can come is to have your method be generic and take a single generic argument:
protected abstract void DoCommand<T>(T parameter);
Short of that you'll have to use a property bag of some sort (like NameValueCollection).
The best I can think of is:
interface IBlaBla
{
void DoCommand(params object[] parameters);
}
and then each class receives the parameters as a sequence of objects.
Otherwise, you'll just have to define a brand new method for each class.
The interface will need to have all the functions (with different parameter). There is no reason to have an interface otherwise
Edit: You might want something like this (using generics)
public interface ICollect<T>
{
void Collect(T obj);
}
public class Car : ICollect<Car>
{
public void Collect(Car obj)
{
//Do stuff
}
}
It does not make sense. This violates the whole idea of polymorphism: the base class(or interface) has a method and child classes provide their own implementation. If you didn't mean to use a generic parameter, then the methods of your child classes are different from the base class, they just appear to have the same name. So you can't force your child classes to implement 'some routine with a given name but arbitrary parameters'.
No, that's impossible. However, you can try this:
void DoCommand(params object[] args);

C# Interface for multiple classes

I have a data provider project to access the database. this is composed by various classes (PersonDataProvider, JobDataProvider ...)
I want to create an Interface.
Do I have to create an Interface for each class?
I was tempted to create one interface and than inherit on all the classes. This involves making all the projects classes partial and change the classes name.......But i think is not the best solution.
Any suggestion?
You don't inherit an Interface you implement it. There's no need to make a class partial to add an interface to it.
An interface is a contract that the class subscribes to saying that it will honour the methods described in the interface and will implement them appropriately. For your scenario you'd create a single interface and implement it in your classes, you can then pass the instances of the various accessor classes as instances of the interface.
For example:
public interface IDataProvider
{
void LoadData();
}
The data providers would then look as follows:
public class MyDataProvder1 : IDataProvider
{
// Some methods
// Must implement LoadData
public void LoadData()
{
// Do something
}
}
public class MyDataProvder2 : IDataProvider
{
// Some methods
// Must implement LoadData
public void LoadData()
{
// Do something
}
}
You can then pass the objects as IDataProvider as follows:
IDataProvider DataProviderA = new MyDataProvider1();
IDataProvider DataProviderB = new MyDataProvider2();
// Call function that expects an IDataProvider
DoSomething(DataProviderA);
DoSomething(DataProviderB);
...
public void DoSomething(IDataProvider DataProvider)
{
DataProvider.LoadData();
}
Hopefully that clears it up for you.
I think you are approaching this incorrectly.
When you make an interface, you're making a contract for those classes. Think of it as "my class will act as a IMyInterface".
If all of your classes have a common usage scenario, then a single, common interface may be appropriate (IDataProvider, given the class names..?).
Using interface depends how you want to arrange the classes. Interface allows some sort of plug and play behaviour. So, if you need a single interface, this will mean that you shall have a single set of interfaces accross all the classes implementing the interface. In such a case, your classes PersonDataProvider, JobDataProvider etc. will have the same set of methods. If you feel, they need to be different and still be available through a single provider facade, you can think of using a facade pattern.
The facade will have interfaces for individual provider and the provider classes will implement them.
First off, I'm assuming there are standard method calls across all your xDataProvider classes. For example, instead of a SelectPerson method, you have a Select method on the PersonDataProvider class. If not, you have some work to do to make this a valid exercise.
Within Visual Studio, there is an Extract Interface refactoring option. Right-click in a xDataProvider class and choose Refactor - Extract Interface. Now name it (IDataProvider, for example) and choose the methods / properties you want in your interface, click OK and your done with this class.
Then just implement this IDataProvider interface in your other xDataProvider classes. Assuming you've already implemented similar methods in all you DataProvider classes, you won't have to write any more code (beyond the : IDataProvider).

Categories