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.
Create-Function
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.
Settings for privacy
This page uses cookies to save the user's privacy-settings. We do not have a stake in how linked pages analyze, process or save data. Since, we only show such content after the agreement of the user.
This applies to sharing-functions of social-media-content like twitter or facebook and embedded videos of youtube.
Einstellungen für Datenschutz
Diese Seite verwendet Cookies, um die Datenschutzeinstellungen des Benutzers zu speichern. Wir haben keinen Einfluss darauf, welche Daten verlinkte Seiten analysieren, verarbeiten oder speichern. Aus diesem Grund werden solche Inhalte nur nach vorheriger Einwilligung des Benutzers angezeigt.
Dies betrifft Funktionen für das Teilen von Inhalten auf sozialen Medien (Twitter und Facebook) sowie eingebundene Videos von youtube.