I have the following interface:
public interface IValidator
{
// Checks whether the selected roles are Valid based on Buisness rules for the
// specific EntityValidator
bool HasCompleteValidSelection(
ICollection<Role> availableRoles, ICollection<Role> selectedRoles);
//Checks whether the available roles are Valid for the specific entity
bool HasValidRoles(ICollection<Role> availableRolesList);
//Computes the Remaining Roles that needs to be selected to make it a Valid selection
ICollection<Role> GetRemainingRoles(
ICollection<Role> availableRoles, ICollection<Role> selectedRoles);
}
Now, I have bunch of EntityTypes,mentioned in the enum:
public enum EntityType
{
Shop= 1,
SmallBuisness= 2,
Corporation = 3,
Firm = 4,
Partnership = 5,
Unknown = 0
}
All the above Entity Types have their corresponding validator classes which implements the IValidator.
public class ShopValidator : IValidator
{
public bool HasCompleteValidSelection(
ICollection<Role> availableRoles, ICollection<Role> selectedRoles)
{ /*implementation */ }
public bool HasValidRoles(ICollection<Role> availableRolesList)
{ /*implementation */ }
public ICollection<Role> GetRemainingRoles(
ICollection<Role> availableRoles, ICollection<Role> selectedRoles)
{ /*implementation */ }
}
But the concern is some of the validator classes are having exact same logic/code.
What I have thought of is:
Instead of Interface, created abstract class and kept the common
code there
Validator classes, which has different implementation,are
overriding the abstract class.
Now, my questions are:
Although the above is working fine, is there any better
approach/design pattern more suitable for the above scenario?
I am using Autofac like below, its working fine, but is there any
issue that you can foresee?
builder.RegisterType().As().Keyed(EntityType.Shop);
// other validators similarly.
Personally, I like your initial proposal. Some will probably disagree, but I like the symmetry of creating a class for each entity type, even if some of those classes have no code.
That is, if there is some common code, I would use your suggestion of converting the interface to a base class and put your common code there. (Much like CException.)
Of course, if the common code is more complex, then you might have more specialized base classes that your final class can derive from, but in that case it isn't near as elegant.
Related
This question centers on dependency injection and generic interfaces.
One of my business entities is an ID card. There can be multiple types of ID cards, all inheriting from ICard:
interface ICard
{
string CardId { get; }
}
class CardA : ICard
{
string CardId { get; set; }
string SomethingCardASpecific { get; set; }
}
class CardB : ICard
{
string CardId { get; set; }
bool SomethingCardBSpecific { get; set; }
}
I have a CardFactory that takes a card ID and returns the correct card type (as ICard):
class CardFactory : ICardFactory // Trivial interface definition left out
{
ICard FromCardId(string cardId)
{
if (MatchesPatternA(cardId))
{
return new CardA { CardId = cardId /* ... */ }
}
else
{
return new CardB { CardId = cardId /* ... */ }
}
}
}
Furthermore, I have another dependency that checks if the card is authorized to perform some action. The logic depends on the card type, hence the generic interface:
interface ICardAuthorization<TCard> where TCard : ICard
{
bool IsOperationXPermitted(TCard card);
bool IsOperationYPermitted(TCard card);
}
I have an API controller that depends on ICardFactory and ICardAuthorization. An action receives a cardId, creates a card, and checks whether it's authorized for action X. The controller is not concerned with the fact that authorization is handled differently for the two card types, so it should depend on operations on the "base" card type (interface), i.e., ICardAuthorization<ICard>.
The actual question:
Naturally, I need at least two different implementations of ICardAuthorization, namely
class CardAAuthorization : ICardAuthorization<CardA> { /* ... */ }
class CardBAuthorization : ICardAuthorization<CardB> { /* ... */ }
However, using the design described above, the API needs to depend on the interface typed to ICard:
class DelegatingCardAuthorization : ICardAuthorization<ICard> { /* ... */ }
This, in turn, depends on the two "real" workhorses, ICardAuthorization<CardA> and ICardAuthorization<CardB>, and calls the correct one based on the type of the ICard its methods receive.
And of course, in my app, ICardAuthorization<TCard> is just one of several interfaces that needs different implementations for different card types.
This seems to me a fairly robust way to structure things, but I don't like the fact that I need delegating implementations that check types and forward calls to other implementations. I can live with it, no problem, but is there any way to make this more elegant by removing the need for the delegating implementation? (I'm using SimpleInjector if that matters.)
I guess you can't just remove the need the delegating implementation entirely because the logic to select an action based on card type should reside somewhere.
What I propose, however, is to go along with factories.
Create CardAuthorizationFactory which will return appropriate ICardAuthorization implemetor based on the type of the ICard object, passed to it. Create any number of other factories for other card actions. Put all those as singletons into IoC.
Now, when some method needs to do something with a card using authorization, it should query AuthorizationFactory for the CardAuthorization object appropriate for the card object it currently has. Factory should be injected into it by IoC. Will it suite your needs?
I am developing a application for sports clubs administraion. And my problem is that I have one primary class Member which contains all the "default" information (name, surname, gender...) and two other classes Coach and Practitioner which inherit from Member. A coach has some specific properties (salary, trainings held in current month...) wheres a practitioner has some others (isCompetitor, category ...)
The problem is that a Practitoner can also be a Trainer as well as the other way around. How can I model this into something that is better then having two entries for the same person?
Edit: this is how it looks now
Class Member {}
Class Coach:Member {}
Class Practitioner:Member {}
You can create one class 'member' that contains a list of roles. Each role (coach and/or practitioner) inherit from a base class 'role' which contains all properties you now have in your member class. Coach and practitioner than have their own specific properties. So:
public class Member {
public IList<Role> Roles { get; private set; }
public Member(){
Roles = new List<Role>();
}
}
public class Role {
public string SomeGlobalProperty { get; set; }
}
public class Coach : Role {
public string SomeSpecificProperty { get; set; }
}
public class Practitioner : Role {
public string SomeSpecificProperty { get; set; }
}
If you're only looking at them in one way at a time - so as one of a group of practitioners, or as one of a group of trainers - then you can create them as the specific type of member they are being viewed as at a time. If required, you can add a boolean property "IsTrainer" to practitioner and "IsPractitioner" to trainer, to indicate that there is more info about that person elsewhere.
This presumes you're only looking at them in one way at a time, and not getting a page with all info about the person.
SImeple: Realize that you basiaclly need to read an intro book into OOP.
A Member is a Member (and even that is disputable - acutally it is a Party, regardless of what it does).
It has different roles which are basically a collection of roles, all with start and end date.
Party
CoachInformation
PractitionerInformation
etc.
I suggest reading "The Data Model Resource Book", volume 1 - they go into great detail about this standard problem and how most people get it wrong.
In [this post], I'm struggling to implement a State Pattern as #jonp suggests. I don't quite get how to use what's he's posted but it leads to the thought that maybe I'm trying to fit a square peg into a round hole. So my question:
If I have a visitor to my site that can play multiple roles i.e. a User could be a Vendor, an Employer, an Advertiser, OR all of the above, should I be using inheritance? I've declared:
class Vendor : User {}
class Advertiser : User {}
et cetera, but when a user is both a vendor and an employer then instances of different classes really point to the same underlying object... I'm not sure this can work. How do I model it?
* update *
thanks everyone (you all get a point (it's all I can give)). I've been pulling my hair out over deep-copies with EF, downcasting and the state pattern for the last several days. The role approach makes much more sense.
This sounds like a situation to which the attribute pattern (or so I call it) would be very appropriate. It's a much more loosely-coupled approach than simple inheritance that can be used to specify multiple "behaviours" or in your case kinds of User. It's really nothing more complicated than an object having tags of another kind of object.
The easiest way to implement it would be to have a concrete User class, with a read-only property IList<UserRole> (internally this can be a List<T> field perhaps). Your UserRole class would then be abstract, and VendorRole/AdvertiserRole/etc. would derive from it, allowing you to tag on an arbitrary number of different roles (even ones of the same type) onto a given user. These roles can in addition define their own custom behaviours, utility methods, etc.
In addition, you could define a GetRole<TRole> method on your User class to facilitate access to roles of a specific type (assuming each User only has a single Role of a specific subtype).
Side note: you may also consider the decorator patern, which is closely related to the above mentioned pattern -- though personally I feel it is overkill here, and really adds nothing in terms of flexibility or power. It often just obscures what you're trying to do; though feel free to investigate anyway.
You should favor Composition over Inheritance if the different roles have to contain different logic that would be implemented using polymorphism and abstract methods, for example:
public class User
{
public Role Role { get; set; }
}
public abstract class Role
{
abstract void DoRoleSpecificStuff();
}
public class Vendor : Role
{
public void DoRoleSpecificStuff()
{
/* ... */
}
}
public class Employer : Role
{
public void DoRoleSpecificStuff()
{
/* ... */
}
}
public class Advertiser : Role
{
public void DoRoleSpecificStuff()
{
/* ... */
}
}
If a User can have multiple Roles, consider using a Roles collection property:
public IEnumerable<Role> Roles { get; set; }
Otherwise, an enumeration using the [Flags] attribute could be fine, too, depending on whether you need to be able to assign multiple Roles:
public class User
{
public Roles Roles { get; set; }
}
[Flags]
public enum Roles
{
Advertiser = 0x0,
Employer = 0x1,
Vendor = 0x2
}
You would assign a combination of different roles as follows:
User user = new User
{
Roles = Roles.Advertiser | Roles.Vendor;
};
That would make the User both an Advertiser and a Vendor, but not an Employer.
“I'm a * but I'm also a **” is known as Multiple Inheritance. C# does not support this, so you shouldn't be considering it.
It's indeed composition over inheritance here, but it's more like this if a single user can have multiple roles.
If there are relatively few roles, a 'parking lot' analogous to an outer join result may work. In this pattern, no Role base class is required.
class User
{
// all of these may be null if not applicable
VendorRole VendorRole { get; set; }
EmployeeRole EmployeeRole { get; set; }
AdvertiserRole AdvertiserRole { get; set; }
}
If a user may have multiple instances of a single role, a collection pops up:
class User
{
// all of these may be null if not applicable
VendorRole VendorRole { get; set; }
EmployeeRole EmployeeRole { get; set; }
ICollection<AdvertiserRole> AdvertiserRoles { get; }
}
Alternatively, if there may be a messy pile of roles, if roles get added dynamically, or what have you, you'll need a collection and a base type. If Entity Framework is involved, though, dynamically added roles seem unlikely to me.
class User
{
ICollection<Role> Roles;
}
Can someone explain the exact use of interfaces in C#?
Has msdn not been helpful on this?
http://msdn.microsoft.com/en-us/library/87d83y5b.aspx
This has been discussed so many times here in the past that it is hard to pick any one duplicate for this question.
To save the time of repeating what has been said before, try this search, and start going through the results.
Imagine the the situation of having a factory that creates cars. You know that every vehicle has an engine and can be started, so you have the following:
interface IVehicle
{
Engine vehicleEngine { get; set; }
bool StartEngine();
}
Now, the factory makes an array of other vehicles, so for instance a truck and a normal car:
public Car : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Cars needs to do xyz to start
}
public int MaxNumberOfPassenger { get; set; } // Specific to Car
}
and then:
public Truck : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Trucks needs to do abc to start
}
public int MaximumLoad { get; set; } // Specific to Truck
}
This therefore forces all vehicles to implement specific members to fall under the category of a vehicle, but then can also be specialized with their own distinct members.
In the most simple terms, an Interface expresses what one, or more classes can do, although the implimentation may vary across the various classes.
Polymorphism
You can use 2 classes that implement the same interface without having to know exactly which concrete class it is. It aids in keeping code loosely coupled.
An interface defines the minimum requirements that a class that can be instantiated must implement. It expresses this through methods.
For instance, an interface could define a function called Foo which takes an integer and returns a boolean:
public interface ICanFoo
{
bool Foo(int number);
}
Any class which implements this interface must also implement this method:
public class Fooable : ICanFoo
{
public bool Foo(int number)
{
// do something
}
}
The implementation within the method is up to the specific classes which are implementing the interface.
By using interfaces you no longer care about implementation are compile time, but rather specification. You can call it like this:
ICanFoo myFooable = ...
bool success = fooable.Foo(4);
The actual type of fooable can be any class that implements ICanFoo since you know that ICanFoo will always define a method implementation for the Foo method.
Assuming the following domain entity :
public enum Role
{
User = 0,
Moderator = 1,
Administrator = 2
}
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Role Role { get; set; }
}
I need to know if the user can perform "Edit" action. So i've 2 solutions :
Create a CanEdit method inside the User entity
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Role Role { get; set; }
public bool CanEdit()
{
return Role == Role.Moderator || Role == Role.Administrator;
}
}
Create a CanEdit Extension Method for User type :
public static class UserExtensions
{
public static bool CanEdit(this User user)
{
return user.Role == Role.Moderator || user.Role == Role.Administrator;
}
}
Both solution works, but the question is WHEN use standard methods vs using Extensions methods ?
Extension methods are simply syntactic sugar for plain, ordinary static methods.
If you control the class structure, you should implement all the necessary functionality within the class. Where extension methods are really useful/necessary is if you don't own the class that you are trying to "extend."
For this example, I think you should put the logic inside the User class. It is a logical function of the user itself; consumers should be able to use the CanEdit() method without having to use or even know about the UserExtensions class.
I mostly agree with Aaronaught's answer, but consider this:
Maybe your CanEdit() method or other similar methods (business rules) might change more or less often or depend on some external factors. Or over time, you will have more and more such rules (for different concerns). In that case you might want to keep them in a different place, separated from the domain model to ensure that the domain model doesn't have too many different responsibilities and doesn't need to change very often.
Then, one way can be to implement them as extension methods, because this allows you to keep these business rules separate from your domain model (e.g. User class), but the method is still easily discoverable by users of the User class.
Another way to implement such business rules would be the specification pattern, where you implement each rule as a separate (specification-) class, e.g. demonstrated in this blog post.
There is very little point in using Extension methods for the sake of using them. If the method belongs to the class, use it there. Extension methods are for extending things, use them when you have no control over the class, or for giving functionality to an interface where the functionality should apply to all classes derived from that interface.
if you do not have direct access to the source code for the class you should use Extensions methods if you do have access to the source code i see no reason to not use a standard methods...
I agree with Aaronaught here: Implement your own logic the old-fashioned way. Static method might cause issues (missing using statement and the method seems to be "missing") lateron.
Something inherent to your model should be part of your classes.