1

I have a simple class ExcelStringBuilder. Its used to build a string that can be exported to Excel. Now I need to build a CSV string also.

The only difference that I see for implementing both of these classes is the delimiter that is to be used while building the string. For Excel it would be "\t" tab character and CSV its "," comma.

What I think is to pass the delimiter as a parameter to the ExcelStringBuilder class constructor. Will that be a right decision or should I go for factory pattern?

Sandeep G B
  • 3,957
  • 4
  • 26
  • 43
gordanvij
  • 1,080
  • 8
  • 16

3 Answers3

3

Don't overdesign it. I would just refactor the existing class slightly:

  • rename it to something like ExportStringBuilder
  • pass the delimiter in the constructor, or as an argument of the ToString() function

You are aware that there are some great free libraries available for this, are you? E.g. see this question

Community
  • 1
  • 1
jeroenh
  • 26,362
  • 10
  • 73
  • 104
1

If the only difference is the delimiter, I would just pass that delimiter in. Everything else is overkill.

If there are more differences, I would create a StringBuilderFactory that returns a IStringBuilder. ExcelStringBuilder and CsvStringBuilder would both implement that interface. You would pass a parameter to the factory that tells the factory whether you want a Excel string builder or a CSV string builder and it returns the correct one.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

If you are planning to use a factory, you can use the template pattern along with Factory or independently. As most part of algorithm will remain same except one step and in future you may have additional steps as well (like new delimiters)

Here is one approach using Template pattern. You can use "Getter" instead of GetDelimiter().

class abstract StringBuilder
{
  public virtual string GetDelimiter();
  public string BuildString(string inputString)
  {
     // Your Code goes here...
     GetDelimiter(); // Code to introduce the delimiter
     // Some more of your code
  }
}

class ExcelStringBuilder : StringBuilder
{
 public override string GetDelimiter()
 {
   return "\t";
 }
}

class CsvStringBuilder : StringBuilder
{
 public override string GetDelimiter()
 {
   return ",";
 }
}
Sandeep G B
  • 3,957
  • 4
  • 26
  • 43
  • 1
    But you would still need the factory pattern to create the appropriate class right? – gordanvij May 03 '11 at 09:06
  • @gordanvij, you are right. Thats what I mentioned in the first statement. You can use template pattern along with Factory pattern or independently. Advantage with this is you are avoiding passing parameters. Since you know the requirement well, you should take the call :) – Sandeep G B May 03 '11 at 09:08