Generic base class to handle CRUD operations - c#

I have a business requirement to consolidate CRUD operations into a single base class, regardless of the type of object. I am not able to modify the calling code, which could be anything ... so if there are a bunch of callers that look like this:
var state = new State("New York");
state.Save();
var city = new City("New York", state);
city.Save();
var stadium = new Stadium("Yankee Stadium", city);
stadium.Save();
All of these Save methods would need to be handle in one, single common base class.
The path I've lead myself down is to create a single generic abstract base class which these classes implement, such as the following ...
public abstract class PersistableObject<T> where T : class {
public string Id { get; set; }
public static T Find(string id) {}
public void Save() { }
public void Delete() { }
}
I then have the above objects inherit from this class:
public class City: PersistableObject<City> { }
I stripped out the CRUD methods tied to the concrete implementations and after having these various objects inherit from the abstract base class, the solution compiles without error.
And now I'm stuck. The backing store is a local XML document (decision out of my hands). I am guessing I can serialize these to XML using the normal XML serializers in .Net, but is there a better way to do this? Should I be using some sort of a repository pattern?
Thanks.

Related

How can I make my code extendable for future use

I am trying to structure my code so that I can easily extend it in the future, however I think I am overthinking things and struggling to accomplish this.
My scenario is:
Based upon some data being passed to me I need to generate a class.
The class that I need to generate is not similar in nature to any of the other classes.
For example I have several classes that can be created:
public class File1{
public string Name {get;set;}
// etc...
}
public class File2{
public int ID {get;set;}
// etc...
}
public class File3{
public string MyType {get;set;}
// etc...
}
In my main class I have:
switch (myExtension)
{
case ".abc":
ProcessABC(myContents);
break;
case ".def":
ProcessDEF(myContents);
break;
case ".ghi":
ProcessGHIL(myContents);
break;
//etc...
}
I have tried creating an interface with a common method:
public ProccessStuff(data);
but I don't think that will work since I don't have a common return type.
Then I thought about an abstract class, but then it seems I'll be pushing a lot of work into that abstract class.
public abstract class MyAbstractClass
{
public void ProcessStuff(string data)
{
// Parse the data into an object
// Update some DB fields
// Log some data
}
}
Am I on the right path with just creating an abstract class to handle all of my logic?
You're saying the classes don't have any similarities. But that's not actually true - they all take a string to do some processing, and it's exactly this that you want shared between the classes.
Make an interface, IDataProcessor (or something). There, have a single method - void Process(string). The file classes will implement the method in a way they require.
This changes your main classes switch to a simple
IDataProcessor actualDataProcessor = ...;
actualDataProcessor.Process(myContents);
Of course, you still need some way to create the proper IDataProcessor based on e.g. the extension. Depending on your exact needs, a simple Dictionary<string, Func<IDataProcessor>> might be quite enough. Otherwise, there's plenty of other ways to bind classes more dynamically if you so desire, or use an explicit factory class.
Have you tried using generics?
Here is an example :
public void Process<T>(string contents)
where T : IProcessStuff, new ()
{
// Common work to do here
// ...
// Specific processing stuff
T t = new T();
t.ProcessStuf(contents);
}
public interface IProcessStuff
{
void ProcessStuf(string contents);
}

Accepting multiple similar entities in a Method - Elegant solution

I have two data entities, which are almost similar, design is something like:
public Class Entity1 : Base
{
public int layerId;
public List<int> Groups;
}
Difference is Entity1 has an extra collection of integer Groups
public Class Entity2 : Base
{
public int layerId;
}
These entities are filled as an input from UI using Json, I need to pass them to a processing method, which gives the same Output entity. Method has a logic to handle if List<int> Groups is null, I need to create a method which is capable of handling each of the input in an elegant manner. I cannot just use only Entity1, since they are two different functional inputs for different business process, so using Entity1 as direct replacement would be a mis-representation
Instead of creating overload of the function, I can think of following options:
Use object type as input and typecast in the function internally
I think we can similarly use dynamic types, but solution will be similar as above, it will not be a clean solution in either case, along with the switch-case mess.
What I am currently doing is processing method is like this:
public OuputEntity ProcessMethod(Entity 1)
{
// Data Processing
}
I have created a constructor of Entity1, that takes Entity2 as Input.
Any suggestion to create an elegant solution, which can have multiple such entities. May be using generic, where we use a Func delegate to create a common type out of two or more entities, which is almost similar to what I have currently done. Something like:
Func<T,Entity1>
Thus use Entity1 output for further processing in the logic.
I need to create a method which is capable of handling each of the input in an elegant manner
Create an Interface, or a contract so to speak, where each entity adheres to the particular design. That way common functionality can be processed in a similar manner. Subsequently each difference is expressed in other interfaces and testing for that interface sis done and the differences handled as such.
May be using generic,
Generic types can be tested against interfaces and a clean method of operations hence follows suit.
For example say we have two entities that both have Name properties as string, but one has an Order property. So we define the common interface
public interface IName
{
string Name { get; set; }
string FullName { get; }
}
public interface IOrder
{
decimal Amount { get; set; }
}
So once we have our two entities of EntityName and EntityOrder we can add the interfaces to them, usually using the Partial class definition such as when EF creates them on the fly:
public partial class EntityName : IName
{
// Nothing to do EntityName already defines public string Name { get; set; }
public string FullName { get { return "Person: " + Name; }}
}
public partial class EntityOrder : IName, IOrder
{
// Nothing to do Entity Order already defines public string Name { get; set; }
// and Amount.
public string FullName { get { return "Order: " + Name; } }
}
Then we can process each of them together in the same method
public void Process(IName entity)
{
LogOperation( entity.FullName );
// If we have an order process it uniquely
var order = entity as IOrder;
if (order != null)
{
LogOperation( "Order: " + order.Amount.ToString() );
}
}
Generic methods can enforce an interface(s) such as:
public void Process<T>(T entity) where T : IName
{
// Same as before but we are ensured that only elements of IName
// are used as enforced by the compiler.
}
Just create generic method that will do this work for you:
List<OuputEntity> MyMethod<T>(T value) where T : Base
// adding this constraint ensures that T is of type that is derived from Base type
{
List<OutputEntity> result = new List<OutputEntity>();
// some processing logic here like ...
return result;
}
var resultForEntity1 = MyMethod<Entity1>();
var resultForEntity2 = MyMethod<Entity2>();
P.S. check my answer for this question as you may find it useful too:
map string to entity for using with generic method
You probably want to implement an interface or an abstract class.
From MSDN
If you anticipate creating multiple versions of your component, create
an abstract class. Abstract classes provide a simple and easy way to
version your components. By updating the base class, all inheriting
classes are automatically updated with the change. Interfaces, on the
other hand, cannot be changed once created. If a new version of an
interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of
disparate objects, use an interface. Abstract classes should be used
primarily for objects that are closely related, whereas interfaces are
best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use
interfaces. If you are designing large functional units, use an
abstract class.
If you want to provide common, implemented
functionality among all implementations of your component, use an
abstract class. Abstract classes allow you to partially implement your
class, whereas interfaces contain no implementation for any members.
Abstract Class Example
Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion. (You might make this method virtual so that you can override it for certain animals, like Fish, which does not breath the same as most animals).
Interface Example
All animals can be fed, so you'll create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable - You'll not implement this on the base class, since this does not apply to Cat.

How do I write an interface or abstract class that specifies creation logic?

I have a generic class that deals with widgets that can be deserialized from strings. Instances of the generic class will take the type of one of these widgets as a template parameter, and then create these widgets from strings. I wish to use the covariance properties of C#'s generics to write code like WidgetUser<IWidget> to deal with objects that may be WidgetUser<RedWidget> or WidgetUser<BlueWidget>. The problem is that to create a widget from a string inside of WidgetUser<T>, I'm forced to add new() as a guard. This makes WidgetUser<IWidget> an invalid type. Currently, I have code like this:
interface IWidget
{
// Makes this widget into a copy of the serializedWidget
void Deserialize(string serializedWidget);
}
class WidgetUser<T> where T : IWidget, new()
{
public void MakeAndUse(string serializedWidget)
{
var widget = new T();
widget.Deserialize(serializedWidget);
Use(widget);
}
}
With this code, I can make WidgetUser<BlueWidget> just fine, because BigWidget satisfies new(). I cannot write WidgetUser<IWidget> because instances of IWidget (or an equivalent abstract class) are not guaranteed to work with new(). A workaround could be this:
abstract class WidgetUser
{
public abstract void MakeAndUse();
}
class WidgetUser<T> : WidgetUser
where T : IWidget, new()
{
/* same as before but with an 'override' on MakeAndUse */
}
With this code, I can create a WidgetUser<BlueWidget> then write code that deals with just WidgetUser. I could have similar code with an abstract class BaseWidget instead of IWidget that accomplishes almost the same thing. This is functional, but I suspect there is a more direct approach that doesn't force me to define a dummy class. How can I convey my intent to the type system without creating dummy classes or extra factories. I just want an interface that says "you can make one of these from a string".
TL;DR:
Is there some way to write an interface or abstract class that lets me create an instance from a string but doesn't require me to have new() as a guard on WidgetUser<T>?
The problem here is that your Deserialize() method should be a static method. Therefore it should not be a member of IWidget itself - it should be a member of a factory interface, or it should be a static member of a concrete Widget class which is called from a concrete factory method. I show the latter approach below.
(Alternatively, you could use a Func<IWidget> delegate to specify it, but it's more usual to provide a full factory interface.)
So I suggest you create the factory interface:
interface IWidgetFactory
{
IWidget Create(string serialisedWidget);
}
Then remove the Deserialize() from IWidget:
interface IWidget
{
// .. Whatever
}
Then add a static Deserialize() method to each concrete implementation of IWidget:
class MyWidget: IWidget
{
public static MyWidget Deserialize(string serializedWidget)
{
// .. Whatever you need to deserialise into myDeserializedObject
return myDeserializedObject;
}
// ... Any needed IWidget-implementing methods and properties.
}
Then implement the factory for your concrete widget class using the static Deserialize() method from the concrete widget class:
sealed class MyWidgetFactory : IWidgetFactory
{
public IWidget Create(string serialisedWidget)
{
return MyWidget.Deserialize(serialisedWidget);
}
}
Then add a constructor to your WidgetUser class which accepts an IWidgetFactory and use it in MakeAndUse():
class WidgetUser
{
public WidgetUser(IWidgetFactory widgetFactory)
{
this.widgetFactory = widgetFactory;
}
public void MakeAndUse(string serializedWidget)
{
var widget = widgetFactory.Create(serializedWidget);
Use(widget);
}
private readonly IWidgetFactory widgetFactory;
}
Note that in this scenario, you no longer need the type argument for WidgetUser, so I have removed it.
Then when you create the WidgetUser you must supply a factory:
var widgetUser = new WidgetUser(new MyWidgetFactory());
...
widgetUser.MakeAndUse("MySerializedWidget1");
widgetUser.MakeAndUse("MySerializedWidget2");
Passing in a factory allows a lot more flexibility.
For example, imagine that your serialization scheme included a way of telling from the serialized string which kind of widget it is. For the purposes of simplicity, assume that it starts with "[MyWidget]" if it's a MyWidget and starts with ["MyOtherWidget"] if it's a MyOtherWidget.
Then you could implement a factory that works as a "virtual constructor" that can create any kind of Widget given a serialization string as follows:
sealed class GeneralWidgetFactory: IWidgetFactory
{
public IWidget Create(string serialisedWidget)
{
if (serialisedWidget.StartsWith("[MyWidget]"))
return myWidgetFactory.Create(serialisedWidget);
else if (serialisedWidget.StartsWith("[MyOtherWidget]"))
return myOtherWidgetFactory.Create(serialisedWidget);
else
throw new InvalidOperationException("Don't know how to deserialize a widget from: " + serialisedWidget);
}
readonly MyWidgetFactory myWidgetFactory = new MyWidgetFactory();
readonly MyOtherWidgetFactory myOtherWidgetFactory = new MyOtherWidgetFactory();
}
Note that this is generally not the best way to do things - you are better using a Dependency Container such as Autofac to manage this kind of thing.
I would implement WidgetFactory and call WidgetFactory.Create<T>(serializedWidget) to avoid the usage of new T()

Make a interface method return an object of type of the class which implemented it

I have searched for an answer to accomplish this, but I haven't found anything: I want an interface's method to return an object of the type of the class which implemented it. For example:
interface InterfaceA {
public static returnValue getObjectFromDatabase(); //What do i need to put as returnValue?
}
Then, if I have two classes (for example, ClassA and ClassB) that implement it, I would like to have:
ClassA obj1 = ClassA.getObjectFromDatabase(); //return object of class ClassA
ClassB obj2 = ClassB.getObjectFromDatabase(); //return object of class ClassB
Thank you, in advance.
What you want to do here won't work for two reasons:
Interfaces can't have static members
Interfaces need to specify the return types of their methods. An interface shouldn't know the types of all the members implementing it, that defeats the point and in many cases would be unachievable.
Moreover, if you did manage to do this, it still wouldn't be good design, because it violates the single responsibility principle. You can find plenty of information on this by googling it or looking around this site, but the idea- as indicated by the name- is that a class should only have a single purpose which it is responsible for.
So imagine that your class was, for example, an Employee class. That class has a pretty clear responsibility, it should be responsible for holding information and functionality related to an Employee in a company. It might have members like FirstName, GivePromotion(), etc. So it'd be strange to now make this class also take responsibility for its own database access.
So how this is achieved would be with another class which is responsible for retrieving objects from the database. One common design pattern for this is the repository pattern. You'll also probably want to take advantage of generics. So you repository interface might look like:
public interface IRepository<T>
{
T GetFromDatabase()
}
Which you can then implement with a generic repository:
public class Repository<T> : IRepository<T>
{
T GetFromDatabase()
{
//Your actual code for database retrieval goes here
}
}
Or, if the database retrieval code is very different for some or all classes, you can implement with a specific repository:
public class EmployeeRepository : IRepository<Employee>
{
Employee GetFromDatabase()
{
//Your actual code for database retrieval goes here
}
}
One approach is to use generics:
class Program
{
interface MyInterface<SomeType>
{
SomeType getObjectFromDatabase ();
}
class A : MyInterface<A> { public A getObjectFromDatabase () { return new A (); } }
class B : MyInterface<B> { public B getObjectFromDatabase () { return new B (); } }
class Program2
{
static void Main ()
{
A a1, a2;
a1 = new A ();
a2 = a1.getObjectFromDatabase ();
B b1, b2;
b1 = new B ();
b2 = b1.getObjectFromDatabase ();
}
}
}
I want an interface's method to return an object of the type of the class which > implemented it
You seem to miss the point of interfaces: an Interface shouldn't have any knowledge about its implementers. Interface exposes contracts and that's it.
Also, from your example, I can see that you are trying to create a static method but interfaces and static are far away from each other. Interfaces are tied with instances, not the type.

Generic DAL / BLL Classes

I'm currently building the Data Access Layer and Business Logic Layer classes for our new application, and I have a question (obviously). First, here are some details that may help:
Using Entity Framework 5 for Model classes and data access
Each "layer" is separated in different class libraries and namespaces (i.e App.Model, App.DAL, App.BLL)
Starting with the DAL - I decided to write a base class for all DAL classes to inherit.
public abstract class DALBase<T> : IDisposable
{
protected AppEntities context;
protected DbSet set;
public DALBase()
{
context = new OECCORPEntities();
set = context.Set(typeof(T));
}
protected virtual void Save()
{
context.SaveChanges();
}
public virtual void Add(T model)
{
set.Add(model);
Save();
}
public virtual T Get(int id)
{
return (T)set.Find(id);
}
public virtual List<T> GetAll()
{
return set.OfType<T>().ToList();
}
public virtual void Delete(int id)
{
T obj = Get(id);
set.Remove(obj);
Save();
}
public virtual void Update()
{
Save();
}
public void Dispose()
{
context.Dispose();
}
}
As you will see, the base class implements a generic type which should be the type of the model the DAL class is responsible for working with. Using the generic type, in the constructor it creates a DbSet using the type of the generic argument - which is used in the predefined CRUD-like virtual functions below (add, get, etc).
And then I got the idea - wait a minute... since it's generic, I really don't have to implement DAL classes for every single model. I can just write something like this:
public class GenericDAL<T> : DALBase<T>
{
public GenericDAL() : base() {}
}
... that I can use for any of the models. OK, so on to the Business Logic Layer. I created a base class for BLL as well:
public abstract class BLLBase<T>
{
protected GenericDAL<T> dal;
public BLLBase()
{
dal = new GenericDAL<T>();
}
public virtual void Add(T model)
{
dal.Add(model);
}
public virtual T Get(int id)
{
return dal.Get(id);
}
public virtual List<T> GetAll()
{
return dal.GetAll();
}
public virtual void Delete(int id)
{
dal.Delete(id);
}
public virtual void Update()
{
dal.Update();
}
}
... which uses the GenericDAL to do its work. So in a simular fashion, I just wrote a GenericBLL class that looks like this:
public class GenericBLL<T> : BLLBase<T>
{
public GenericBLL() : base() { }
}
And to test it, a simple console application:
class Program
{
static void Main(string[] args)
{
GenericBLL<ADMIN> bll = new GenericBLL<ADMIN>();
List<ADMIN> admins = bll.GetAll();
}
}
... where "ADMIN" is the model type. Works like a charm.
The idea behind this was to avoid having to write DAL / BLL classes for every single model, unless it needed extra functionality. Can someone tell me why I WOULDN'T want to do it this way? I think the generic DAL / BLL classes would get the job done and also save development time.
Thank you for your time.
Well, one drawback is that if you decide to add some business rules later on you would have to switch the type from GenericBLL[Whatever] to WhateverBLL.
An obvious solution to this is to create a class that inherits from GenericBLL[Whatever]. Like:
public class WhateverBLL : GenericBLL<Whatever>
and use this class instead.
Right now, your BLL isn't particularly adding value. Every call is simply a pass-through to another layer. Maybe it's the simplicity of your application (and thank your lucky stars that you are so lucky), or maybe you have what I would classify as the actual business logic living elsewhere.
Business logic to me is everything that is done up to the point of persisting data, everything that is done after retrieving data, and things like that. The decisions, the forks in the road, the actions that are taken. Actually saving and retrieving data is typical extremely trivial by comparison.
So as I look at your generic DAL base class, I think it's a fine start. I would probably extract an interface from it so I could replace it when testing. For now, your class that inherits the base isn't adding any value. Do not create layers and classes simply for the sake of it, be sure it adds value and makes your life easier in some way.
As I look at your generic BLL class, I think you probably have your real business logic tucked away in the codebehind on some form, or inside a class file in a console app. While it's certainly possible that there could be generically applicable functionality that only varies on the type, I don't think one class is where you want to be. My suggestion here is to reconsider what you think is your actual business logic. A simple pass-through layer to the DAL probably isn't it.

Categories

Resources