Last active
April 25, 2017 19:31
-
-
Save 4e1e0603/bfa41ec3e9c8a4e1d23cacf590f0005d to your computer and use it in GitHub Desktop.
Simple value object example in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Ukázka jak implementovat jednoduchý *value object*. | |
*/ | |
#include <string> | |
#include <stdexcept> | |
#include <iostream> | |
template<typename T> | |
class SingleValueObject | |
{ | |
public: | |
/*! | |
\brief The value constructor. | |
*/ | |
constexpr SingleValueObject(T const &value) : _value(value) { } | |
/*! | |
\brief Gets the stored value. | |
*/ | |
inline T value() const noexcept { return _value; } | |
protected: | |
virtual ~SingleValueObject() { } | |
private: | |
T const _value; | |
}; | |
struct Email final : SingleValueObject<std::string> | |
{ | |
/*! | |
\brief The value constructor. | |
*/ | |
Email(std::string const &value) : SingleValueObject(validated(value)) { } | |
/*! | |
\brief Validates the input value. | |
*/ | |
static std::string validated(const std::string &value) | |
{ | |
if (!value.size()) { | |
throw std::invalid_argument("Value cannot be empty!"); | |
} | |
return value; | |
} | |
}; | |
int main() | |
{ | |
const Email e1("[email protected]"); | |
const Email e2("[email protected]"); | |
std::cout << e1.value() << std::endl; | |
std::cout << e2.value() << std::endl; | |
try { | |
const Email e3(""); | |
} | |
catch (std::exception const &e) { | |
std::cout << e.what(); | |
} | |
try { | |
const Email e4(nullptr); | |
} | |
catch (std::exception const &e) { | |
std::cout << e.what(); | |
} | |
// Rovnost je v C++ ve výchozím stavu strukturální. | |
std::cout << (e1.value() == e2.value()) << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment