Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple classes with same methods - best pattern

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.

like image 705
Tony The Lion Avatar asked Apr 05 '10 13:04

Tony The Lion


People also ask

Which design pattern suggest multiple classes through which?

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.

What are the patterns of multiple inheritance design?

Explanation: Adapter and observer patterns benefit from the multiple inheritances.

Can we have same method in different class?

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.


3 Answers

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.

like image 75
FrustratedWithFormsDesigner Avatar answered Oct 24 '22 14:10

FrustratedWithFormsDesigner


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
like image 24
Marc Gravell Avatar answered Oct 24 '22 15:10

Marc Gravell


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
    }
}
like image 31
juharr Avatar answered Oct 24 '22 14:10

juharr