Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Sorry for the confusing title of this question, but I can\'t think of an exact w

ID: 654601 • Letter: S

Question

Sorry for the confusing title of this question, but I can't think of an exact way to word it. I have a very long class with hundreds of similar methods and I am trying to find a way to construct it without so many lines of code and so many DRY violations. Each time I add a new property to my class I have to write two methods and update the copy function. There are already over 80 properties.

Currently this class is written in Java but I was wondering if it were written in C++ if it could be done more efficiently. I think it can be done using preprocessor x-macros like described in wikipedia here but I am not a fan of macros and would prefer to do it using the language itself if possible.

Here is a simplified snippet of my Java class:

class InMemoryPerson implements Person {
    private HashMap<String,Object> values = new HashMap<String,Object>();

    public InMemoryPerson copyFrom(Person p) {
        setName(p.getName());
        // more code to copy all the properties...
    }

    public void setName(String name) {
        values.put("name",name);
    }

    public String getName() {
        return (String)map.get("name");
    }

    // many more methods for all the different properties...
    // each method may have a different type
}

Explanation / Answer

In C++ this is possible to do, using old style C macros.

// method is get/set method suffix
// name is the key in hash table
#define POINTER_PROPERTY(type,method,name)
type get##method(){return (type)_pointer_map[name];}
void set##method(type value){_pointer_map[name]=value;}

class InMemoryPerson : Person {
public:
POINTER_PROPERTY(char *,Name,"name")

private:
std::map<const char *,void *> _pointer_map;
};
Value types would have to be handled by different macro and (easiest way) by different hash for each type. Not sure though this code is more readable and manageable than 80 different get/set functions.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote