Home > Enterprise >  Design pattern for isolating parsing code?
Design pattern for isolating parsing code?

Time:03-06

I have C class Foo:

class Foo
{
public:
    [constructor, methods]

private:
    [methods, data members]
};

I want to add to class Foo the possibility for it to be constructed by reading data from a text file. The code for reading such data is complicated enough that it requires, in addition to a new constructor, several new private methods and data members:

class Foo
{
public:
    [constructor, methods]

    Foo(const std::string& filePath); // new constructor - constructs a Foo from a text file

private:
    [methods, data members]

    [several methods used for text file parsing] // new methods
    [several data members used for text file parsing] // new data members
};

This works, but I feel it would be better to isolate the new parsing code and data members into their own entity.

What would be an adequate design pattern in order to achieve this goal?

CodePudding user response:

This is purely an opinion piece, so I'm surprised it's not closed yet. That being said... To me, it depends upon the format of your input file.

At my company, we use JSON representation for no end of things. We store JSON files. We pass JSON in our REST calls. This is pretty common. I have a virtual base class called JSON_Serializable with a toJSON and fromJSON method, and all the classes that are going to do this implement those.

I consider this 100% reasonable. There's nothing wrong with a class being able to serialize itself.

Do you control the format of your input file? Is it a format you're going to use a lot? If so, there's nothing wrong with making the class smart enough to serialize from a string.

CodePudding user response:

I wrote a http server which involded parsing the request and response to something the server client recognized. Both fit builder pattern(https://refactoring.guru/design-patterns/builder)

Heres a http example of request builder https://bitbucket.org/ptroen/crossplatformnetwork/src/master/OSI/Session/HTTP/HTTP_Request_Builder.h Their is also a response builder in same folder

Use case is similar your building something from or to txt file stream. But depending on the nesting of data could be more complicated so best to write requirements first

  • Related