(Design question) Formatting objects for file output

A

alacrite

I have a class that represents a record in a database table.

class tableName
{
int col1;
string col2;
int col3;
... other fields and relevant operations
}

I want to output that object's contents into a file. The user has
different options for the formatting used(csv,xml,pipe, ect.).

The design I am using right now is use an base class to define the
interface.

class dbWriter
{
string write(const tableName &);
}

then create subclasses for each format

class dbWriterToXml : public dbWriter
{
//this write will take a tableName obj and return a xml string
representation
string write(const tableName &);
}
class dbWriterToCsv : public dbWriter
{
//this write will take a tableName obj and return a csv string
representation
string write(const tableName &);
}

The reason for the subclasses is so that when these classes are to be
written to a file you could do something lik e this

you could have a set format function in the class that is actually
driving this process
iWantToWriteARecodToAFile.setFormat("CSV");
which sets the string outputFormat variable

then when the class that wants to actually do the writing calls its
function to writeToFile
iWantToWriteARecodToAFile.writeToFile();

the contents of the method writeToFile() would look something like this
dbWriter* db_writer = getWriterClassFromFactory(outputFormat);
//factory returns proper format class
outputMessage = db_writer.write(); //polymorphically call the correct
write function
....//write the outputMessage to the file

Questions is that good OO design?

one alternative I can think of:
class dbWriter
{
writeAsXML();
writeAsCSV();
writeAsPipe();
}

then just use if statements
if(outputFormat == "CSV")
{
db_writer.writeAsXML();
}
else if ...

the difference that I see between these two approaches is that as new
formats are created one requires changes to the factory the other to
the if else statements.

Which approach is better and why? Any alternatives that would be better
than each of these approaches?

thanks
-Jake
 
G

Grizlyk

I have a class that represents a record in a database table.

I want to output that object's contents into a file. The user has
different options for the formatting used(csv,xml,pipe, ect.).

The design I am using right now is use an base class to define the
interface.

Try use design pattern "builder" in which each of "(csv,xml,pipe,
ect.)" will be as "concrete builder",
and parser of your table will be as "director".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top