tags:

views:

95

answers:

3

Sorry for the bad title I just didn't know how to word it right.

Say I have a class called Table and these three methods:

//Creates a new table in underlying provider and returns new Table object.
CreateNew(string Name); 
//Opens the table in provider and returns new Table object.
OpenTable(string Path);
//Same action as above just on a collection, and returns a IList<Table>
OpenTables(IList<string> path);

At the current time I am using something like this, where all the methods are static on the type:

Table tab = Table.OpenTable("SomePath");
Table tab = Table.CreateNew("DummyTableName");

You get the idea.

However I was wondering if these really should be in a factory. Something like this:

 TableFactory factory = new TableFactory();
 Table tab = factory.CreateNew("DummyTableName");
 Table tab = factory.OpenTable("SomePath");

The factory wouldn't be static as that would make other code that uses a factory hard to test

What do you think?

+1  A: 

It depends on what you are trying to achieve. You get better inversion of control if you use a factory, so you could for example, create a Test implementation for Table which you use during testing, which allows for finer grained control on your unit tests.

Provided your factory usage is ubiquitous you could in test mode replace it with a TestTable factory.

Sam Saffron
+1  A: 

The main reason to use a factory is to decouple the creation of an object from its usage. Since you are just creating a Table object with different parameters, I think it makes more sense to have the static creation methods off of the Table class itself.

Andy
A: 

Have you considered:

var tab = new Table("tableName");

and

var tablePath = new TablePath("SomeTablePath");
var tab = new Table(tablePath);

OTOH, if you want a factory and all the decoupling that can give you, I'd extract a table interface, and have the factory return the interface.

Robert
Opening a table requires an underlying provider to get called so I would be breaking the "no work in constructor rule" if I just used a constructor.
Nathan W