I am working on a transliteration tool. I have two modules lexer and translator. Lexer generates tokens out of the input text. Depending on the current language chosen, I have to call appropriate translation routine.
I have came up with couple of ideas to do this. First one is to create a base class something called base_translator
and provide virtual method (translate()
) which every translators has to override. Now create a factory translator_factory
and call create()
with the language name. This factory will return appropriate instance.
But this seems to be over engineering. So I came up with another approach where I have a struct like the following.
struct translator
{
const char* name;
void (*fp)();
};
Which just keeps a language name and a function pointer who can process it. Usage will be,
static translator translators[] = {
{"first", first},
{"second", second}
};
const char* language = /* */;
for(int i = 0; i < 2; i++) {
translator *t = translators + i;
if(strcmp(t->name, language) == 0) {
t->fp();
break;
}
}
This approach is very simple and easy to maintain. But I wonder, is this the best approach to the problem? Do you have any suggestions to make this better?
Any help would be great.
So a function either can take some arguments, or nothing is taken. Similarly, a function can return something, otherwise does not return anything. So we can categorize them into four types. Function with No argument and No return type. Function with No argument and Return something. A function that takes argument but returns nothing.
Function call by value is the default way of calling a function in C programming. Before we discuss function call by value, lets understand the terminologies that we will use while explaining this: Actual parameters: The parameters that appear in function calls.
C function argument and return values. A function in C can be called either with arguments or without arguments. These function may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values.
C - Functions Defining a Function. A function definition in C programming consists of a function header and a function body. ... Example. Given below is the source code for a function called max (). ... Function Declarations. A function declaration tells the compiler about a function name and how ...
This is typically a blessed use-case for abstract classes and virtual functions. I don't get why you think of it as "over-engineering".... o_O
The point is to define a contract so that your code is extensible easily, and the "main code" doesn't have to worry about the actual implementation details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With