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.
6. Which design pattern suggests multiple classes through which request is passed and multiple but only relevant classes carry out operations on the request? Explanation: Chain of responsibility pattern creates a chain of receiver objects for a particular request.
Explanation: Adapter and observer patterns benefit from the multiple inheritances.
Having two or more methods named the same in the same class is called overloading. It's not overloading if you have the same method name in two different classes.
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.
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:
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With