Would it be a good practice to implement entity base class like that:
[Serializable]
public abstract class Entity<T> : IComparable<Entity<T>>, IFormattable
{
public abstract Int32 CompareTo(Entity<T> entity);
public abstract String ToString(String format, IFormatProvider provider);
// ...
}
So all derived classes must implement those interfaces.
Is it reasonable to put IComparable<T> interface on entity class?
Thanks!
It's not a good (or bad) practice - it comes down entirely to your needs.
Specifying IComparable at such as general level comes with the risk that it may not make sense to compare some objects further down in the inheritance chain. Even if you can compare two objects, would it always make sense to? You may be requiring lines of code to be written to satify a contract which would never be used - beware of YAGNI circumstances.
However, this would be fine if you need to create an absolute contract so that any objects inheriting from Entity can be compared. This allows you to make positive assumptions in your code.
What would T be? Your domain class? If that's the case why not make the Entity class non-generic and directly inherit from Entity?
In general, I've found it to be a good practice to derive all domain classes that can be handled by a particular Repository from a common interface or base class. This allows the Repository to be generic to that interface, providing compile-time checking that you are attempting to use the Repository to persist something that the Repository has mapped. If you use a base class, though, don't map it unless you need a way to uniquely identify any Entity regardless of its actual subclass type; otherwise you'll get that Entity table (with any common fields) as a table in your DB and it can become difficult to manually trace through your data layer.
However, a common, mapped Entity may be desireable; you may want to uniquely identify Persons and Companies by a common ID column that is unique even through Persons and Companies are saved to different tables.
Here's a sterilized example of the hierarchy I've used in one of my projects:
//identifies a class as persistable, and requires the class to specify
//an identity column for its PK
public interface IDomainObject { long Id {get;} }
//In a repository-per-DB model, just because it's an IDomainObject doesn't mean
//a repo can work with it. So, I derive further to create basically "marker"
//interfaces identifying domain objects as being from a particular DB:
public interface ISecurityDomainObject:IDomainObject { }
public interface IDataDomainObject:IDomainObject { }
public interface IData2DomainObject:IDomainObject { }
//There may be logic in your repo or DB to prevent certain concurrency issues.
//You can specify that a domain object has the necessary fields for version-checking
//either up at the IDomainObject level, a lower level, or independently:
public interface IVersionedDomainObject:IDomainObject
{
long Version {get;}
string LastUpdatedBy {get;}
DateTime LastUpdatedDate {get;}
}
//Now, you can use these interfaces to restrict a Repo to a particular subset of
//the full domain, based on the DB each object is persisted to:
public interface IRepository<TDom> where TDom:IDomainObject
{
//yes, GTPs can be used as GTCs
T GetById<T>(long Id) where T:TDom;
void Save<T>(T obj) where T:TDom;
//not only must the domain class for SaveVersioned() implement TRest,
//it must be versionable
void SaveVersioned<T>(T versionedObj) where T:TDom, IVersionedDomainObject
}
//and now you can close TDom to an interface which restricts the concrete
//classes that can be passed to the generic methods of the repo:
public class ISecurityRepo:IRepository<ISecurityDomainObject> { ... }
If your entities require comparability and formatting than using a base class is a very good practice.
sometimes the identity field is also implemented in the base class.
Related
I work with Dynamics CRM (Which is technically irrelevant to this discussion, but explains some of the back-story to this issue). There are numerous types all derived from the class Entity. I wish to create a Class<T>() : where T: Entity, but with a further restriction, that it only operates on specific classes derived from Entity.
My current method of doing this is to have an enum matching the entity names I want to use, if/else if/else my way through those types, and throw if an invalid type is passed in.
It feels clumsy, and I feel that I would be better off writing something like,
public class ProductConverter<t> where T: Entity (OpportunityProduct, QuoteProduct, AccountProduct)
{ ... }
That way the type-engine can say, "We're working on a base class of Entity, and also we're only working on these derived types of Entity".
I hope this gives enough clarity to understand what I'm doing - my purpose is that I want to create an engine that will handle conversion between Entity Records, that can be extended without having to re-write large chunks of code (Effectively, adding a mapping and type parameters). I'm sure there are better ways to do this, so please point them out if you see them :)
edit
#henk-holterman asked if I could change the classes. This isn't possible as they're generated class files, used as an interface to the Dynamics CRM web service.
edit
As noted by #jamiec, the classes are partial, so I can do this by defining an interface on the specific classes I wish to modify.
Your autogenerated classes are almost certainly partial, which means that you should have a separate file for each implementing a shared interface
public partial class QuoteProduct : IProduct
{ // probably empty }
Then you can restrict your generic type by interface:
public class ProductConverter<T> where T: Entity, IProduct
{ // your implementation }
You need to implement an Interface which is then implemented from every class you want to use. This could look like this for example:
public interface IProduct
{
int ProductId {get;set;}
}
public class ProductConverter<t> where T: Entity, IProduct
{
//Do sth. with your ProductId
}
Because your classes are generated as you described in comment this won't work in your special case. Then you only have the ability to use type checking:
T obj;
if (obj.GetType() == typeof(YourClass))
//OR
if (obj is YourClass)
The problem is if you do sth. like you expect in your question, your variable is useless because you don't know which type it is.
public void ProductConverter<t>(T obj) where T: Entity (OpportunityProduct, QuoteProduct)
{
obj. //What to do here?? It can hold Methods from both OpportunityProduct or QuoteProduct
}
So in fact you have the possibilty to generalize the stuff you need or to typecheck.
If you know what can happen maybe the dynamic keyword can help you. In this case you don't need the generic approach. For example this can look like this:
public void ProductConverter(dynamic entity)
{
//Make sure the method exists. Or you will get an Exception.
//The compiler can't warn you about this
entity.SomeMethod1();
entity.SomeMethod2();
}
Not sure if this can really help you if you want to write a converter.
I'm making a simple web form to gather customer data and enter it into a database. I have 5 sub-classes: Customer, Bank, Employee, Owner, and TradeReference which inherit from the abstract class, DataEntry. DataEntry has a function public void InsertSelfIntoDataBase(int id);. The id parameter is the primary key from the Customers Table (Bank, Employee, Owner and TradeReference have a many-to-one relationship with Customer), so a Customer doesn't need an id to be inserted (CustomerID is auto Incremented in the database).
Currently, my code is set up so that Bank, Employee, Owner, and TradeReference implements the InsertSelfIntoDataBase function in the parent class, while Customer throws a NotImplementedException, so the code for the Customer class code looks a little like this:
public int InsertSelfIntoDataBase()
{
int customerID = InsertCustomerAndReturnScalor();
return customerID;
}
public override void insertSelfIntoDataBase(int id)
{ throw new NotImplementedException("Customer does not use this function"); }
This implementation works, but it bugs me that I have to use a NotImplementedException; Like I can't shake the feeling that my professors form college somehow know and are silently judging me. Is there a better way of doing this?
Regardless of the caveats about the class design as Robert Columbia pointed out, I would like give my thoughts about the NotImplementedException.
In the .NET Framework there is anoter well known Exception, which suits this purpose better - the NotSupportedException. It signals that an operation is not supported by the implementation - rather by design and not by the lack of code implementing a feature.
The NotImplementedException is rather an indidicator, that an implementation will and should be done in the future.
This sort of situation can indicate a less than ideal abstract class model. Perhaps you could implement abstract class DataEntry without the insertSelfIntoDataBase(int) method, and then derive a second abstract class such as SelfInsertingDataEntry : DataEntry that defines the abstract method insertSelfIntoDataBase(int) so that concrete classes can inherit from either one depending on whether or not they implement the method.
With this trick, polymorphism related to other methods would be preserved since any concrete instance (whether or not it implemented insertSelfIntoDataBase) could be cast to type DataEntry.
#Recursive also had a good point in a comment, suggesting moving the insertSelfIntoDataBase method into an interface. You could then keep your DataEntry class hierarchy strictly related to Entry type taxonomy and allow some, none, or all descendants to implement or not implement the interface as they wish without requiring them to switch their parent.
I am new to Repository Pattern and trying to use it in my project. I have following entities in my project:
UserProfile
UserTypeA
UserTypeB
UserTypeC
I have 3 types of users and UserProfile containing the general information about all three of them like Password, UserName etc. There are many other entities also and each type of user have different type of relationship with other entities. Now i have decided to create the following repository pattern for this:
public class UserProfileRepository
{
....
}
public class UserTypeAReository: UserProfileRepository
{
.....
}
public class UserTypeBReository: UserProfileRepository
{
.....
}
public class UserTypeCReository: UserProfileRepository
{
.....
}
So i want to know is this (repository inheritance) comes under good practices OR is there any other better way to do this ??
EDIT
There is a 1 to 0..1 shared primary key relationship b/w UserProfile and (UserTypeA, UserTypeB and UserTypeC).
Depending on what you're trying to achieve, you can also use an Interface or an Abstract Class.
If you want all the classes to have a common contract, but the implementation of each method is different, then you can use an Interface, and this will give more flexibility since you have multiple interface inheritance v's singe class inheritance with C#.
With the Abstract class, you can set up the methods, along with an implementation, but allow the derived class to override the base implementation.
This SO post might also help: Interface vs Base class
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interface vs Base class
Its common to see the repository pattern implemented using Interfaces
public interface IFooRepository
{
Foo GetFoo(int ID);
}
public class SQLFooRepository : IFooRepository
{
// Call DB and get a foo
public Foo GetFoo(int ID) {}
}
public class TestFooRepository : IFooRepository
{
// Get foo from in-memory store for testing
public Foo GetFoo(int ID) {}
}
But you could equally do this using abstract classes.
public abstract class FooRepositoryBase
{
public abstract Foo GetFoo(int ID);
}
public class SQLFooRepository : FooRepositoryBase
{
// Call DB and get a foo
public override Foo GetFoo(int ID); {}
}
public class TestFooRepository : FooRepositoryBase
{
// Get foo from in-memory store for testing
public override Foo GetFoo(int ID); {}
}
What are the specific advantages of using an Interface over an Abstract Class in a repository scenario?
(i.e. don't just tell me that you can implement multiple interfaces, I know this already - why would you do that in a repository implementation)
Edit to clarify - pages like "MSDN - Choosing Between Classes and Interfaces" can be paraphrased as "Choose classes over interfaces unless there is a good reason not to" - what are the good reasons in the specific case of a Repository pattern
The main advantage of using an interface over an abstract class in this instance is that an interface is entirely transparent: This is more of an issue where you don't have access to the source of the class you're inheriting from.
However, this transparency allows you to produce unit tests of a known scope: If you test a class that accepts an interface as a parameter (using the dependency injection method), you know you're testing the class with a known quantity; the testing implementation of the interface will only contain your testing code.
Similarly, when testing your repository, you know you're testing just your code in the repository. This helps to limit the number of possible variables/interactions in the test.
Personally, I tend to have an interface that holds the signature for the methods that are purely "business-related" for example Foo GetFoo(), void DeleteFood(Foo foo), etc. I also have a generic abstract class that holds protected methods like T Get() or void Delete(T obj).
I keep my methods protected in the abstract Repository class so that the outside world is not aware of the plumbery (Repository will look like object) but only of the business model via the interface.
On top of having the plumbery shared another advantage is that I have for example a Delete method (protected) available to any repository but it is not public so I am not forced to implement it on a repository where it has no business meaning to delete something from my data source.
public abstract class Repository<T>
{
private IObjectSet objectSet;
protected void Add(T obj)
{
this.objectSet.AddObject(obj);
}
protected void Delete(T obj)
{
this.objectSet.DeleteObject(obj);
}
protected IEnumerable<T>(Expression<Func<T, bool>> where)
{
return this.objectSet.Where(where);
}
}
public interface IFooRepository
{
void DeleteFoo(Foo foo);
IEnumerable<Foo> GetItalianFoos();
}
public class FooRepository : Repository<Foo>, IFooRepository
{
public void DeleteFoo(Foo foo)
{
this.Delete(foo);
}
public IEnumerable<Foo> GetItalianFoos()
{
return this.Find(foo => foo.Country == "Italy");
}
}
The advantage of using the abstract class over an interface for the plumbery is that my concrete repositories do not have to implement method they don't need (Delete or Add for example) but they are at their disposal if they need it. In the current context, there is no business reason for to some Foos so the method is not available on the interface.
The advantage of using an interface over an abstract class for the business model is that the interface provides the answers to how it make sense to manipulate Foo from a business side (does it make sense to Delete some foos? To create some? etc.). It's also easier to use this interface when Unit testing. The abstract Repository I use cannot be unit tested because it is usually tightly coupled with the database. It can only be tested in integration tested. Using an abstract class for the business purpose of my repositories would prevent me from using them in unit tests.
This is a general question that applies to any class hierarchy, not just repositories. From a pure OO point of view, an interface and a pure abstract class are the same.
If your class is part of a public API, the primary advantage of using an abstract class is that you can add methods in the future with little risk of breaking existing implementations.
Some people also like to define an interface as "something that a class can do" and a base class as "what a class is", and therefore will only use interfaces for peripheral capabilities and always define the primary function (eg. repository) as a class. I'm not sure where I stand on this.
To answer your question, I don't think there is any advantage to using an interface when it defines the primary function of the class.
While others may have more to add, from a purely practical point of view, most IoC frameworks work better with interface -> class mappings. You can have different visibilities on your interfaces & classes, whereas with inheritance, the visibilities must match.
If you're not using an IoC framework, from my point of view there is no difference. Providers are based on abstract base classes.
I guess the key difference would be, that an abstract class can contain private properties & methods, wherein an Interface cannot, as it's only a simple contract.
The result being an interface is always "no shenanigans here - what you see is what you get" whilst an abstract base class may allow side effects.
Take a look at the implementation of Tim McCarthy's Repository Framework.
< http://dddpds.codeplex.com/ >
He uses interfaces like IRepository<T> for defining the contracts, but he also uses abstract classes like RepositoryBase<T> or his SqlCeRepositoryBase < T > that implements IRepository<T>. The abstract base class is code to eliminate a lot dublicate code. A type specific repository just have to inherit frome the abstract base class and needs to add the code for its purpose. Users of the API can just code against the interface by contract.
So you can combine both approaches to use the advantages of them.
Additionally, I think most IoC-Frameworks can handle abstract classes.
Since the pattern originates in Domain Driven Design, here's a DDD answer :
The contract of a Repository is usually defined in the Domain layer. This allows objects in the Domain and Application layers to manipulate abstractions of Repositories without caring about their real implementation and the underlying storage details - in other words, to be persistence-ignorant. Besides, we often want specific behaviors to be included in the contracts of some repositories (in addition to your vanilla Add(), GetById(), etc.) so I prefer the ISomeEntityRepository form than just IRepository<SomeEntity> - we'll see why they need to be interfaces later.
The concrete implementations of Repositories, on the other hand, reside in the Infrastructure layer (or in the Tests module for test repositories). They implement the above repository contract but also have their own range of persistence-specific characteristics. For instance, if you're using NHibernate to persist your entities, having a superclass to all the NHibernate repositories with the NHibernate session and other NHibernate-related generic plumbing in it could come in handy.
Since you can't inherit several classes, one of these 2 things that your final concrete Repository inherits has to be an interface.
It's more logical for the Domain layer contract to be an interface (ISomeEntityRepository) since it's a purely declarative abstraction and mustn't make any assumption about what underlying persistence mechanism will be used - i.e. it mustn't implement anything.
The persistence-specific one can be an abstract class (NHibernateRepository or NHibernateRepository<T> in the Infrastructure layer) which allows you to centralize there some behaviors that are common to the whole range of persistent-store-specific repositories that will exist.
This results in something like :
public class SomeEntityRepository : NHibernateRepository<SomeEntity>, ISomeEntityRepository
{
//...
}
Recently I have come across a curious pattern in some code. We know that there is a time and a place for everything, especially when it comes to the issue of ABCs and interfaces, but this just seems redundant to me.
// This describes a person....
public interface IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int BasePay { get; set; }
public string Address { get; set; }
}
// And so does this, but it also uses the interface....
public abstract class Person : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int BasePay { get; set; }
public string Address { get; set; }
}
// This uses both ?!
public class CoalMiner : Person, IPerson
{
public CoalMiner()
{
BasePay = 10000;
}
}
Can anybody think of what the specific advantage of using both and ABC and an interface that define the same members be?
Personally, I feel that using an interface to describe a "noun", such as a person, it typically a poor design choice.
Interfaces should be used for contracts - all people are always a Person, so an abstract class makes more sense here. Interfaces could be added for behaviors attached to specific types of people, or to allow a Person to be used in a certain way by fulfilling a contract (ie: Person : IComparable<Person>).
Having both the IPerson interface and the Person base class allows you certain freedoms, as long as you are passing around objects under the IPerson interface rather than the Person base class.
Base classes tend to implement common code that should be used by all descendants of that base class. That's fine if that's what you want, but one might run into a case where an entirely different implementation of IPerson is needed, where the base class Person is not used at all. Now you have 2 class hierarchies that have IPerson in common, and things still work. You would not be able to do that with Person only.
Another good reason for the redundancy of always having an interface would be for COM interop.
A situation where both the interface and the ABC makes sense is when using the decorator pattern. The ABC is used to provide common implementation code for the different concrete implementation classes. All implementation classes are probably derived from the ABC.
A decorator, which wraps an existing instance and tweaks the functionality of it would typically only implement the interface and not derive from the ABC. If there are many decorators, there could be another ABC which provides the common composition handling and function call forwarding that the decorators need.
Explicitly mentioning the interface sometimes makes it more readable. The MSDN documentation often do that, e.g. showing that List<> implements both ICollection<> and IList<> although IList<> is derived from ICollection<>.
The only advantage I could think of with a derived class explicitly implementing the same interface as its base class is to prohibit the derived class from hiding a member and as a result breaking the interface.
Interfaces specify a contract for behavior, so this only makes sense if you have sufficient behavior (beyond simple property accessors) that a non-Person might want to implement IPerson. For instance, if IPerson could HoldConversation(Stream input, Stream output), then you might have a TuringTestCandidate that implements IPerson, without actually deriving from Person.
In more practical terms, this pattern is typically used when you want to unit test behaviors of some class that depends on the interface and you don't want the overhead or possible interference from changes in the base class. It wouldn't make sense for this simplified example, but is often useful in practice.
In this case, your interface and abstract class are quite redundant, except that the abstract class is fulfilling the method requirement of the interface. I don't see the need for the interface in this case, especially given that there is an abstract class.
If you were to be implementing methods on objects with two arms and two legs -> IThingWithArmsAndLegs::DoTheHokeyPokey() that could be a good use of an interface. Then this interface could be shared among Person : IThingWithArmsAndLegs, and Alien : IThingWithArmsAndLegs.
I am a fan of both in the right situation, Why?
Even if you need just an Interface for some type of IOC/DI, it provides no common functionality. You can do this to Inject and have the base functionality covered through a common abstract base class. Then only abstract/virtual methods as needed.
It is oop at it's finest IMHO. Especially in a multi target solution.
I will make my Interfaces one time for all devices, then for each device create an Abstract Class that covers all the same common functionality common to that device type.
Just for the sake of argument you could have common functionality in the abstract Person base class that not everything implementing the interface IPerson needs to reduce duplicate code. At the same time you could have some routines that expect an IPerson to perform some common logic.
Having said that, I wouldn't recommend this practice this at all.
To me it looks bad specify Person and IPerson in the declaration of CoalMiner. I would just derive it from Person. The structur interface -> abstract class -> concrete class is fine with me, but overkill in most situations. I use it sometimes if most of the classes implementing the interface share a lot of code. So deriving from the abstract class is the default case for the 95% simple cases, but I would like to keep the option to have completly independent implementation of the interface.
Interfaces tend to be used a lot in Dependency Injection scenarios because they are considered "light weight" dependencies. Using this approach you tend to have interfaces defining a lot of things, and often end up with abstract classes that implement the interface to provide the base implementation of some or all of the interface members.
I tend to think this is a little extreme, particularly in the example you provided where the abstract class does not provide anything beyond the properties. I have to say I've been guilty of this myself at times, generally using the excuse that the interface makes it more "testable", and is friendlier to my IoC container of choice. I've been trying to reduce the interface bloat in my code recently that comes from a general mentality that loose-coupling via interfaces are required for proper Dependency Injection, realizing that there is a point where things just become silly.
While there is no NEED for CoalMiner to have the IPerson interface, I know some people prefer that so it is obvious that the type implements the interface. That being said, I don't this it is very useful like that.
Interfaces to define nouns are very common in enterprise systems where you may need to support multiple data access layers (DAL) because your system deals with multiple other systems. In this case you might have the following abstract classes
public interface ICustomer {}
public abstract class SapEntity {}
public abstract class NHibernateEntity {}
public class SapCustomer : SapEntity, ICustomer {}
public class NHibernateCustomer : NHibernateEntity, ICustomer {}
public class CustomerProcessor
{
public ICustomer GetCustomer(int customerID)
{
// business logic here
}
}
I find I often need to use both with generic base classes. Usually at some point I need to pass a reference to the open class generic base class which unfortunately you can't do in C#, so I create a non-generic interface.
I can see the point of having both the interface and abstract class (the interface defines the contract, and the abstract class can have a partial implementation that derived classes can share).
However, specifying both the parent class and the interface in the derived class is redundant (It's already implied because the abstract class must implement the interface or it won't compile).
This pattern might just be there as a coding standard so that it is obvious to other programmers when looking at the concrete class that its ancestors implement that interface.
None, if you extend the same interface twice, it's only used the first time. You can delete the 2nd IPerson and your code will still run fine.