I have a few classes in my current project where validation of Email/Website addresses is necessary. The methods to do that are all the same.
I wondered what's the best way to implement this, so I don't need to have these methods copy pasted everywhere?
The classes themselves are not necessarily related, they only have those validation methods in common.
How about adding an interface, and using an extension method?
public interface IFoo { }
public class A : IFoo {}
public class B : IFoo {}
public class C : IFoo {}
public static class FooUtils {
public static void Bar(this IFoo foo) { /* impl */ }
}
That way:
no unnecessary inheritance
no duplication
You might want to put all the validation code into a Validator class, then use that class anywhere that validation is needed. Access to validation should be through a single method, Validate(object Something) maybe. I think this is called "Composition" (as far as design patterns go).
Later on, you can have sub-classes of Validator that maybe more specific or do different kinds of validation.
You could also have all classes requiring validation extend a base class or abstract class that has 90% of the validation in it.
Sounds like you just need a static class with a static method
public static class Utilities{
public static bool validEmail(string email)
{
//Your code here
}
}
Yes, duplicating this code would be a bad smell, you can extract these methods to single Helper class in static methods or you can define a "Validator" interface class and using this interface, you can link different validation methods with chain of responsibility pattern.
Create a Utility class and define these methods as extension methods for appropriate class/interfaces.
You really need to take a good look at the aspect oriented programming methodology (AoP). The Enterprise Library 4.1 has an AoP implementation called Unity Interception.
http://msdn.microsoft.com/en-us/library/dd140045.aspx
This framework allows you to code a single handler class for the email validation. So what this entails is that the validation code goes into a handler class, and no longer part of the class(es). Next thing you do is mark the classes for interception.
You can intercept the classes in a variety of ways, including setting an attribute on the desired method that should be intercepted and handled per your requirements. Setting an attribute is probably the easiest way to do an interception.
create validation logic classes and interfaces, and have them being injected in your code... so seperate the logic from validation so that it can be reused...
Create Email as a separate class.
Use Email as properties/parameters/return values in your classes instead of String.
Create EmailValidator to validate strings as email addresses.
Create EmailFactory that returns Email when passed a valid email address and null if not.
(Do same for Website).
I would recommend you create an IValidator interface then create multiple different validators that handle different scenarios. Here's one example:
public interface IValidator {
bool CanValidateType(string type);
bool Validate(string input);
}
The CanValidateType() method could be a bit more complex, but I hope you get the idea. It basically identifies whether the validator can handle the input supplied. Here are a couple implementations:
public class UrlValidator : IValidator {
bool CanValidateType(string type) {
return type.ToLower() == "url";
}
bool Validate(string input) {
/* Validate Url */
}
}
public class EmailValidator : IValidator {
bool CanValidateType(string type) {
return type.ToLower() == "email";
}
bool Validate(string input) {
/* Validate Email */
}
}
Now you will use constructor injection to inject the dependency into your class:
public class SomeSimpleClass {
private IValidator validator;
public SomeComplexClass(IValidator validator) {
this.validator = validator;
}
public void DoSomething(string url) {
if (validator.CanValidateType("url") &&
validator.Validate(url))
/* Do something */
}
}
The CanValidateType comes in handy when you have a class that can use multiple validators. In this scenario you pass in a list or an array of validators to the constructor.
public class SomeComplexClass {
private List<IValidator> validators;
public SomeComplexClass (List<IValidator> validators) {
this.validators = validators;
}
public bool ValidateUrl(string url) {
foreach (IValidator validator in this.validators)
if (validator.CanValidateType("url"))
return validator.Validate(url);
return false;
}
public bool ValidateEmail(string email) {
foreach (IValidator validator in this.validators)
if (validator.CanValidateType("email"))
return validator.Validate(email);
return false;
}
}
You would then have to pass in the required instance of the validator(s) to your classes somehow. This is often done with an IoC container (like Castle Windsor) or do it yourself.
IValidator emailValidator = new EmailValidator();
IValidator urlValidator = new UrlValidator();
SomeSimpleClass simple = new SomeSimpleClass(urlValidator);
SomeComplexClass complex = new SomeComplexClass(new List<IValidator> { emailValidator, urlValidator });
The above code gets tedious to do on your own, this is why IoC containers are so handy. With an IoC container you can do something like the following:
SomeSimpleClass simple = container.Resolve<SomeSimpleClass>();
SomeComplexClass complex = container.Resolve<SomeComplexClass();
All the mapping of interfaces is done in your app.config or web.config.
Here's an awesome tutorial on Dependency Injection and The Castle Windsor IoC container.
Related
Let's say I have multiple classes that all have the same actions (in my case I'm creating a plugin framework that all: Load, Run, Dispose), and I want to use an interface so I can create a PluginFactory to handle the initialization. The problem is they all need wildly different data so the methods would be the same but the parameters would be different. Is there a best practice or design pattern where I can use interfaces and polymorhism while passing in different data to the methods?
Generics wouldn't necessarily solve my problem because the number and types of parameters is different for each plugin. I'm thinking of creating a container inside the methods when I implement them that retrieves the parameters from a global source and therefore I can inject different dependencies into that global source when I test but I'm not sure if that breaks any abstraction rules.
Edit:
Here's a code example:
public interface IPlugin
{
void Load();
}
public Hubbub : IPlugin
{
public void Load(int individualId, IApiDataSource apiDataSource)
{
//code
}
}
public class SysEx : IPlugin
{
Load(OAuthToken token, string connString, User user)
{
//code
}
}
public class FriendPlat: IPlugin
{
Load(string username, string password)
{
//code
}
}
You can create an interface eg ILoadArgument
Create a class per IPlugin implementation eg FriendlyPlatArgument, SysExArgument etc. These dto classes can implement ILoadArgument interface that you created. May be they all need a common property eg CreatedAt that can also goto the interface.
Now your IPlugin interface can define Load method as
Void Load(ILoadArgument arg) ;
Also you can then make it generic as:
Void Load(T arg) where T:ILoadArgument{°°°}
I have two interfaces implemented by one main class. How can i refactor my code in a way that on implementing each contract, the methods of each contract has a different value for a parameter such as DatabaseName.
Example :
Class1 Implements Interface1,Interface2
Interface1.GetData() has DatabaseName set to Database 1
Interface2.GetData() has DatabaseName set to Database 2
I can configure those value in the methods GetData() but i want a cleaner way of doing it.
Any pattern recommendation be that DI ,Domain driven ,even basic inheritance example which accomplishes the above is what i am looking for.
It sounds like all you need is explicit interface implementation:
public class Class1 : Interface1, Interface2
{
// Note the lack of access modifier here. That's important!
Data Interface1.GetData()
{
// Implementation for Interface1
}
Data Interface2.GetData()
{
// Implementation for Interface2
}
}
Obviously the two methods can call a common method with a parameter to specify the database name or similar.
Refactoring is usually motivated by noticing a code smell and the very fact that you ended up in a situation where you have to implement 2 abstraction which expose similar functionality is the code smell.
Without having more understanding of the problem I might not be able to provide you a conclusive answer but with limited understanding this is what I would propose. Have 2 different concrete implementation each implementing one interface and have a factory which would be injected to client and make the client make the deliberate decision which one of these implementation is needed. In case these concrete classes share common functionality you can always abstract that into a common parent class.
public interface ISQLReader
{
string GetData();
}
public interface IOracleReader
{
string GetData();
}
public abstract class Reader
{
protected void CommonFunctionaility()
{
}
}
public class MSSQLReader : Reader, ISQLReader
{
public string GetData()
{
return "MSSQL";
}
}
public class OracleReader : Reader, IOracleReader
{
public string GetData()
{
return "Oracle";
}
}
public interface IReaderFactory
{
OracleReader CreateOracleReader();
MSSQLReader CreateMSSQLReader();
}
public class ReaderFactory : IReaderFactory
{
public MSSQLReader CreateMSSQLReader() => new MSSQLReader();
public OracleReader CreateOracleReader() => new OracleReader();
}
public class ReaderClient
{
private IReaderFactory _factory;
public ReaderClient(IReaderFactory factory)
{
this._factory = factory;
}
}
Explicit interface implementation is technique that should restrict usage of the functionality until the client has made and explicit cast there by making a deliberate decision.
I have a factory object ChallengeManager to generate instances of a Challenge object for a game I'm building. There are many challenges. The constructors for each Challenge class derivation are different, however there is a common interface among them, defined in the base class.
When I call manager.CreateChallenge(), it returns an instance of Challenge, which is one of the derived types.
Ideally, I would like to keep the code for the object construction inside the derived class itself, so all the code related to that object is co-located. Example:
class Challenge {}
class ChallengeA : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeA();
}
}
class ChallengeB : Challenge {
public static Challenge MakeChallenge() {
return new ChallengeB();
}
}
Now, my ChallengeManager.CreateChallenge() call only needs to decide the class to call MakeChallenge() on. The implementation of the construction is contained by the class itself.
Using this paradigm, every derived class must define a static MakeChallenge() method. However, since the method is a static one, I am not able to make use of an Interface here, requiring it.
It's not a big deal, since I can easily remember to add the correct method signature to each derived class. However, I am wondering if there is a more elegant design I should consider.
I really like the pattern you are describing and use it often. The way I like to do it is:
abstract class Challenge
{
private Challenge() {}
private class ChallengeA : Challenge
{
public ChallengeA() { ... }
}
private class ChallengeB : Challenge
{
public ChallengeB() { ... }
}
public static Challenge MakeA()
{
return new ChallengeA();
}
public static Challenge MakeB()
{
return new ChallengeB();
}
}
This pattern has many nice properties. No one can make a new Challenge because it is abstract. No one can make a derived class because Challenge's default ctor is private. No one can get at ChallengeA or ChallengeB because they are private. You define the interface to Challenge and that is the only interface that the client needs to understand.
When the client wants an A, they ask Challenge for one, and they get it. They don't need to worry about the fact that behind the scenes, A is implemented by ChallengeA. They just get a Challenge that they can use.
You're "decentralizing" the factory, such that each subclass is responsible for creating itself.
More commonly you would have a central factory that would know about the possible subtypes and how to construct them (often enough, simply by creating a new instance and returning that instance typed as a common interface or common base class). That approach avoids the issue you currently have. I also see no benefit to your current approach. You are currently gaining no encapsulation or code reuse over the more typical implementation of a factory.
For additional reference, have a look at
http://www.oodesign.com/factory-pattern.html
Not necessarily the answer you are looking for but...
You can use following implementation, if you can move away from static method per class.
using System;
public class Test
{
public static void Main()
{
var c1 = ChallengeManager.CreateChallenge();
var c2 = ChallengeManager.CreateChallenge();
//var c = ChallengeManager.CreateChallenge<Challenage>(); // This statement won't compile
}
}
public class ChallengeManager
{
public static Challenage CreateChallenge()
{
// identify which challenge to instantiate. e.g. Challenage1
var c = CreateChallenge<Challenage1>();
return c;
}
private static Challenage CreateChallenge<T>() where T: Challenage, new()
{
return new T();
}
}
public abstract class Challenage{}
public class Challenage1: Challenage{}
public class Challenage2: Challenage{}
Since we can't define a public static method in the interface, can such an interface be implemented in a class with public static?
public interface IValidator
{
bool IsValid(bool data);
}
public class MyValidator : IValidator
{
public static bool IsValid(string data)
{
//code which returns bool
}
}
No, C# does not allow for static interfaces.
Interfaces are designed to act as contracts between classes, that contract defines that each instance of these classes will have a set of method.
Jon Skeet has given a very good explanation in this question, I'd recommend reading it.
When you have an object instance, it makes sense to cast and use that as an interface. But when you work with static stuff, this isn't the case. You can only access static members through the name of the containing class, you can't pass them around like instances, etc.
It is possible to implement an interface and make sure it's not instantiated multiple times, it's called the singleton pattern. A singleton class is similar to a static class, but it has an instance that can be passed around and it can implement interfaces as well.
No, but you could get something close to it by having a static member return an instance of the interface.
Somthing like:
public class MyValidator : IValidator
{
public bool IsValid(string data)
{
//code which returns bool
}
public static readonly IValidator Instance = new MyValidator();
}
Then you could use it in a static sort of way:
bool isValid = MyValidator.Instance.IsValid("data");
You cannot define static members via the interface, so if static members are required by design they can only be added to concrete types.
This ultimately produces a lot of confusion. Any other implementation would not have that same member. Mocked instances will not have access to that member. And so on.
Solution is to avoid declaring static members. In your particular case, I would object to the very design of the interface. I would prefer to see classes implement some interface like IValidatable:
public interface IValidatable
{
bool IsValid();
}
...
public class SomeBoolClass: IValidatable
{
private bool Data;
public bool IsValid()
{
return this.Data; // i.e. return Data == true
}
}
...
public class SomeStringClass: IValidatable
{
private string Data;
public bool IsValid()
{
return !string.IsNullOrEmpty(this.Data);
}
}
In this way you obtain fully polymorphic validation across all current and future types.
If you insist on having a validator which receives low-level data (such as Boolean or string) to validate, then you are half-way doomed. Suppose that there are two classes which wrap string data. These two classes would normally have to be validated in different ways. But validator would not be able to distinguish which validation algorithm to apply based on input data. Even worse, validator would have to contain all validation logic for all types, existing and those yet to be coded. This means that validator would act as one giant (and inherently incomplete) switch statement.
I am basically trying to implement a Strategy pattern, but I want to pass different parameters to the "interfaces" implementation (that inherit from the same object) and don't know if this is possible. Maybe I'm choosing the wrong pattern, I get an error similar to
'StrategyA' does not implement inherited abstract member 'void DoSomething(BaseObject)'
with the code below:
abstract class Strategy
{
public abstract void DoSomething(BaseObject object);
}
class StrategyA : Strategy
{
public override void DoSomething(ObjectA objectA)
{
// . . .
}
}
class StrategyB : Strategy
{
public override void DoSomething(ObjectB objectB)
{
// . . .
}
}
abstract class BaseObject
{
}
class ObjectA : BaseObject
{
// add to BaseObject
}
class ObjectB : BaseObject
{
// add to BaseObject
}
class Context
{
private Strategy _strategy;
// Constructor
public Context(Strategy strategy)
{
this._strategy = strategy;
}
// i may lose addtions to BaseObject doing this "downcasting" anyways?
public void ContextInterface(BaseObject obj)
{
_strategy.DoSomething(obj);
}
}
It sounds like you're actually trying to reinvent the Visitor pattern, instead of just using the Strategy pattern the way it was intended.
Also, since you're using C#, I'd recommend reading Judith Bishop's paper titled On the Efficiency of Design Patterns Implemented in C# 3.0. This covers multiple approaches to the visitor pattern in detail, and has some interesting, related useful ideas.
In C# method signature includes its name, type parameter list and formal parameter list. In the code above "overrides" have different signatures than virtual method and thus it is not allowed.
The core idea behind Strategy Pattern is to define set of interchangeable algorithms with details hidden inside. But if your strategies differ (by type) in what they can accept as input they are no longer interchangeable. So it seems this a wrong pattern to use in this situation.
You might want to consider this article:
http://hillside.net/plop/2010/papers/sobajic.pdf
The pattern is called "parameterized strategy pattern" and should match what you need. Basically, it builds up on the strategy pattern and allows for strategies (different algorithms) to have different parameters. Parameters are encapsulated in special classes, i.e. parameter classes. Each strategy (i.e. algorithm) needs to implement GetParameters() method which sends back the list of parmaters instances for specific algorithm.
The strategy pattern is meant to provide different behaviour on input objects of the same type.
What you're actually trying to do is context-dependent, and I'm not sure it can be seen from the code that was posted.
You could create a Parameters class like so:
public class Parameters
{
public ObjectA {get; set;}
public ObjectB {get; set;}
}
The alter your methods to accept Parameters such as:
class StrategyA : Strategy
{
public override void DoSomething(Parameters parameters)
{
// Now use ObjectA
if(parameters.ObjectA.SomeProperty == true)
{ ... }
}
}
This way you can additional parameters should your requirements change in the future. Another alternative is to use Dictionary<string, object> where you can do:
class StrategyA : Strategy
{
public override void DoSomething(Dictionary<string, object>parameters)
{
// Now use ObjectA
var someProperty = (bool)parameters["SomeProperty"];
if() ...
}
}