Semantic Versioning

Creating Objects

If you want to create a new object, you need to call a constructor. That's how we learnt programming. But what happens if need to validate the data you pass to the constructor?

First validate then construct

One option is to call a validation-function to decide if the data is correct. Then you create the desired object. But this might result in having the validation outside the class or a public static function inside the class and perhaps a duplication of validating. This can happen, because you need to parse the data for validation an a second time for creating the object. Alternatively you can pass lots of parameters to the constructor that will form the desired attributes.

Keep uninitialized

Another option is to use a variable to determine, if the object has been initialized correctly. In that case you need to test in every function, if it is allowed to call it on the uninitialized data. This option would encapsulate the logic of validation inside the class, but expose a function like isValid() to the caller. Nearly everywhere there needs to be a call to this function. So this option could be error-prone.


If you use a static create-function where you pass the desired data, you can calmly parse and validate the input and pass the data to a private constructor. If something fails, you can return a null-value. The caller of the create-function either receives a fully initialized object or null.