-1

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?

2 Answers 2

2

"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.

1

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.

2
  • Your solution is obvious. However, it is not quite what I meant: I need to provide too many constructor arguments. Now I know what to do: I will use your solution together with dependency injection!
    – porton
    Oct 24, 2019 at 18:00
  • @porton Most programming languages allow you to provide default values for parameters. Another option is using a builder class for your lexer, before finally using it. Oct 24, 2019 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.