I've found myself writing some repetitious code in C++. I'm using some auto-generated, such that if I want to deal with Foo, Bar, & Baz they all have fairly similar method. E.g., get_foo, get_bar, get_baz, etc.
For each "thing" I more or less have to do the same types of thing. Check if it exists, if it does, get the log, look for the most recent entry in the log, check the entry for problems, etc.
That's lead to a fair bit of repeated code, along the lines of:
if (obj->has_foo) {
if(obj->get_foo().has_log()) {
Log *l = obj->get_foo().get_foo_log();
if (!l) {
ERROR("Foo does not have a log")
}
... 30-40 more lines of stuff ...
}
}
if (obj->has_bar) {
if(obj->get_bar().has_log()) {
Log *l = obj->get_bar().get_bar_log();
if (!l) {
ERROR("Bar does not have a log")
}
... 30-40 more lines of stuff ...
}
}
if (obj->has_baz) {
if(obj->get_baz().has_log()) {
Log *l = obj->get_baz().get_baz_log();
if (!l) {
ERROR("Baz does not have a log")
}
... 30-40 more lines of stuff ...
}
}
Is there a way I could build a collection, such that each item in the collection would have the unique aspects of Foo, Bar, Baz and I could use them in a single block of code.
Forgive the Perl-eese, but something like:
foreach my $thingie ("foo", "bar", "baz") {
if (obj->has_$thingie) {
if(obj->get_$thingie().has_log()) {
Log *l = obj->get_$thingie().get_$thingie_log();
if (!l) {
ERROR(sprintf("%s does not have a log", $thingie))
}
... 30-40 more lines of stuff ...
}
}
}
Or, if that's not the right direction, how do I avoid copy/pasting/tweaking that same fundamental block 3 times?