A typical introductory example to OOP, classes, and constructors is object Car
, with properties such as float fuel
, bool is_engine_running
, etc etc, and a class and constructor definition might be as follows (I'm using a Java-esque syntax here, but it works in any OOP language):
class Car {
float fuel_remaining;
bool is_engine_running;
// ... other fields
Car(float fuel, bool is_engine_running, ...) {
this.fuel_remaining = fuel;
this.is_engine_running = is_engine_running;
// Other assignments
}
}
Most examples of constructors I've seen (admittedly not many, as I haven't dug through the sources for large Java/C++ projects yet) tend to do simple this.x = x
assignments. I would like to implement a class representing UUIDs (I know there already exists various built-in/third-party libraries dealing with this; this is a custom namespace-based UUID for a client with specific requirements) with the UUID itself internally represented as a 128-bit (or 32-byte) array. I am considering C++'s std::bitset<128>
for this, or any equivalent in other languages.
When I initialise the UUID object, I would think that valid constructors would accept, amongst others, the current time, the variables (typically strings) from the namespace, some hardware address (also possibly a string), or even a UUID string itself; for instance, "9fbaea6e-a929-4833-a802-9d64ac432126"
. Otherwise, I would have to directly provide a bit/byte array for the constructor to do something like this.uuid_bits = uuid_bits
, which I feel is rather pointless, because it removes any abstraction whatsoever and leaks the internal bit-array representation to the caller.
Therefore, my question is this: The above UUID class will require some string-parsing, bit-shifting, etc to properly initialise any object while still abstracting away the internal representation. Is it hence an anti-pattern to do more work than merely trivial assignment in the constructor? If not, how might I separate out this 'extra work'? Would I perhaps write and use private static
functions/methods to further process the arguments to the constructor, and return the appropriate internal representation, so that the constructor itself only does an assignment?