mercredi 10 février 2021

Design pattern for generating diagnostic messages

in software engineering, there is a frequent need for reporting helpful warnings and error messages back to the user. There are usually two types of messages: the generic ones and the diagnostic ones. For instance, when implementing a compiler, a generic message could be something like: "encountered an error while parsing file at xxxxx:line:column", while a diagnostic message would say something like, "did you forget an ; at xxxxx:line:column?".

I am not actually writing a compiler, but a software that has a similar challenge as a compiler, that is to generate diagnostic warning messages during the runtime, depending on user input. A lot of times I found myself writing code like this;

if (only event 1 happens) {
   remember event 1 has happened
   output warning A
}

if (only event 2 happens) {
   remember event 2 has happened
   output warning B
}

if (only event 3 happens) {
   remember event 3 has happened
   output warning C
}

if (during event 1, event 2 happens) {
   output a more specific warning
}

// because the order of events matter
if (during event 2, event 1 happens) {
   output a different specific warning
}

if (event 2 and event 3 happen) {
   output a more specific warning
}

many if's...

As you can tell, I ended up checking many combinations of events and the code is not maintainable. Every time a new feature is added, there is a new event that needs to be taken into account, combining with the old events. therefore, the number of if's grows expotentially.

I'd like to know if there is some sort of OOP design pattern I could apply to my code, so that instead of writing if's on a case-by-case basis, I could make use of the virtual inheritance of OOP languages to better maintain this code.

Aucun commentaire:

Enregistrer un commentaire