/**
* A JavaScript value representing a signed integer.
*/
class V8_EXPORT Integer : public Number {
public:
static Local<Integer> New(Isolate* isolate, int32_t value);
static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
int64_t Value() const;
V8_INLINE static Integer* Cast(v8::Value* obj);
private:
Integer();
static void CheckCast(v8::Value* obj);
};
The above code is from Google's V8 engine. Example initialization of this is:
Handle<Value> x = Integer::New(42);
From what I can see in the source code, they marked the constructor as private and want you to use the New function to create instances of this class. Isn't this against the standard C++ design patterns? Why didn't they just overload the constructor instead of making static functions for creation? This usually the kind of thing you see when people try to port a library from one language to another (the only one I can think of off the top of my head right now is Xamarin's iOS kit).
I've tried to Google around for a name for this type of convention but was unable to find anything on it really.
This is a pattern called "Static Factory Method", which is recommended by Joshua Bloch as Item 1 in "Effective Java". (I am almost sure that Scott Myers has an equivalent Item in "Effective C++", but right now I do not have a copy of the book to check.)
The advantages of creating objects through such a method, instead of the normal constructor, are described by Bloch as:
- such methods may have a descriptive name
- unlike constructors, such methods are not required to create an entirely new object, i.e. they can return a previously cached copy of the object.
- unlike constructors, such methods may also return an object of any subtype of their return type
- such methods reduce verbosity of parameterized object construction
There are also downsides to this design pattern, it is only a recommendation in certain situations.
Probably, in the case of V8, the second point in the list is most important, in order to speed up construction. I am no V8 expert, but it seems that "event-driven, single-threaded" is its philosophy. When many "event callbacks" want to have one and the same number, all of them get a copy of the same instance of that number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With