Cpp typesafe generic setters

in #cpp7 years ago

Some time ago I had a long discussion with one of my colleagues regarding the POD data types and how to deal with the setters - geters (if of course you like to use them).

My opinion of setters is that they are bad and that they break the basic principles of OOP - encapsulation. But this is subjective anyway.

So lets assume you want to use them.

Lets assume you have a class Customer and your customer has an Id a firstname and a lastname.

class Customer{
int id;
std::string firstname;
std::string lastname;

Customer& setFirstname(const std::string& fname){
firstname = fname;
return *this;
}

Customer& setLastname(const std::string& lname){
lastname = lname;
return *this;
}

Customer& setId(int customerId){
id = customerId;
return *this;
}
};

Looks to be a lot of code. Especially in case if you have a lot of member variables in your class you have to write a lot of setters :( ..

I put some thought about that and came to an interesting solution. What if we make types for every entity we have in our system. When types are in place we could use a template function to set the appropriate member variable :)

struct CustomerId{
int value;
};

struct Firstname{
std::string value;
};

struct Lastname{
std::string value;
};

struct Customer{
std::tuple<CustomerId, Firstname, Lastname> data;
template typename T
Customer set(const T& value){
Customer result = *this;
utils::get T (result.data) = value;
return result;
}
};

int main(int argc, char* argv[]){
Customer customer;
customer = customer.set(Lastname{"Trump"}).set(Firstname{"Donald"});
return 0;
}

You can find utils::Tuple here: https://github.com/alekstheod/tnnlib/blob/master/src/Utilities/MPL/Tuple.h
Imagine that now you can even iterate over your members.
It might be useful for a serialization - deserialization code.

Sort:  

Btw if somebody know how to annotate c++ code please let me know.. Or tell me where to ask....