samedi 8 décembre 2018

Some of my class fields is required. How can i know it was initialized?

Ok guys. Im writing code and have one problem. Language is C# but it doesnot matter. For example: I have class Point

Class Point
{
 private _x;
 private _y;

 //getter and setters
}

So, if i want to use object of this class i need to totally know that all fields, like _x and _y was initialized. Default values is not solving. My solutions:

  • pass all required paramaters through constructor and initialize
  • Always check if my field is not null (i think this is the bad way)

But if i have 7 required fields.

Class Point
{
 private _x; //required it must not be null
 private _y; //required it must not be null
 private _z; //required it must not be null
 private _b; //required it must not be null
 private _a; //required it must not be null
 private _f; //required it must not be null
 private _h; //required it must not be null

 //getter and setters
}

How i can be sure that all of them was initialized? Passing this count of paramaters in constructor is really hard and ugly. If i will use builder pattern, it actually not make me sure. Sorry for bad english.

Aucun commentaire:

Enregistrer un commentaire