Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it worth abstracting out Object creation for single classes?

I'm playing around with design patterns, and things are coming along nicely. One thing I'm unsure of is it worth abstracting out Object creation when there is currently only one object?

For example a project I'm working on contains two different user types which are not related in any way. They are IStudent and IStaff. For the application in question, there will never be any other types of user (staff Roles handle all none-student interactions with the system).

In my controllers I could simply:

IStudent student = new Student();

Or I something like this:

public static class UserFactory
{
    public static T Create<T>() where T : class
    {
        if(typeof(T) == typeof(IStudent))
            return new Student() as T;

        if (typeof(T) == typeof(IStaff))
            return new Staff() as T;

         throw new Exception("The requested user type is not valid.");
    }
}

And then:

IStudent student = UserFactory.Create<IStudent>();

Is this overkill? I'm trying to work out best practice in these situations.

like image 419
Chris W Avatar asked Aug 31 '11 20:08

Chris W


1 Answers

Personally, I use TDD for most development. One thing I like about that is that it provides an answer for your question: "not unless it's required to make a failing unit test pass".

In other words, if you don't need it, then don't do it.

like image 59
John Saunders Avatar answered Oct 27 '22 06:10

John Saunders