Question

I am rewriting a lexer class that has several "parameters" like whitespaceSplit.

So it goes this way:

lexer = new Lexer();
lexer.whitespaceSplit = true;
lexer.otherParameter = ...;
lexer.parse(file);

The trouble is that a user of my library could change the parameters such as whitespaceSplit in the middle of the parsing process and allowing this looks like a code smell for me.

What to do?

Was it helpful?

Solution

"several parameters" means you will likely forget which position is which if you set these with a constructor. There are ways around this problem but they depend on your language.

If you use a language with named arguments like C# you can fix that problem:

new Lexer(
    whitespaceSplit:true,
    otherParameter:"other"
);

If you use a language without them like Java you can simulate them with the Joshua Block Builder Pattern.

new Lexer.Builder
    .whitespaceSplit(true)
    .otherParameter("other")
    .build()
;

Either way you get an immutable object and the parameters are clearly labeled.

OTHER TIPS

What about letting those parameters which change the parsers behavior only to be passed with the construction of the instance?

class Lexer {
public:
    constructor Lexer(whitespaceSplit : boolean; otherParameter : ...) 
       : whitespaceSplit_(whitespaceSplit ), otherParameter_(otherParameter) {
    }

    property whitespaceSplit : boolean read whitespaceSplit_;
    property otherParameter : ... read otherParameter_;
private:
    whitespaceSplit_ : boolean;
    otherParameter_ : ...;
};

lexer = new Lexer(true,whatever);

The access to these attributes can be made read only for further access.

The trouble is that a user of my library could change the parameters such as whitespaceSplit in the middle of the parsing process and allowing this looks like a code smell for me.

Thus this can't happen at all.

Licensed under: CC-BY-SA with attribution
scroll top