Bifalgorithm post · Computer science one · Factory Functions

How can factory functions simplify the creation of structure instances?

How can factory functions simplify the creation of structure instances? (Computer science one · Factory Functions) — "Properly creating and initializing struct…

Ideas in this flowchart

  • Factory functions simplify the creation and initialization of structure instances.
  • Creating and initializing structures manually can be complex and tedious.
  • The initialization operation may need to be repeated many times.
  • A utility function can create a structure instance from supplied values.
  • Such utility functions are called factory functions; in object-oriented languages, similar methods are called constructors.
  • The function receives values such as first name, last name, identifier, and GPA.
  • Dynamically allocated elements such as strings require deep copies.
  • Shallow copies share references and may cause changes to one string to affect multiple structures.
  • The createStudent function provides a concrete implementation of this approach.
  • The implementation allocates memory for a Student structure and separately allocates and copies both strings.
  • It initializes the identifier and GPA, then returns a pointer to the new student.
Feed/

How can factory functions simplify the creation of structure instances?

No cover

Channel

Computer science one

1 page

"Properly creating and initializing structure instances can be a complex and tedious task. However, it is likely that we will need to repeat this operation over and over. We can simplify our task if we write a utility function that creates a structure instance for us. We provide the function the values we want initialized to. Such functions are sometimes referred to as factory functions as they can be used to manufacture as many instances as we want (in object-oriented programming languages, such methods are called constructors). We will need to take care that we make deep copies of any dynamically allocated elements such as strings. Shallow copies where references are shared may lead to unexpected behavior as changes to one string may affect multiple structures.\n\n/**\n\n* This function creates a new student structure with the\n\n* given values.\n\n*/\n\nStudent * createStudent(const char *firstName,\n\nconst char *lastName,\n\nint id,\n\ndouble gpa) {\n\nStudent *s = NULL;\n\ns = (Student *) malloc(sizeof(Student) * 1);\n\n//make a deep copy of the strings\n\ns->firstName = (char *)malloc(sizeof(char)*(strlen(firstName)+1));\n\nstrcpy(s->firstName, firstName);\n\ns->lastName = (char *)malloc(sizeof(char)*(strlen(lastName)+1));\n\nstrcpy(s->lastName, lastName);\n\ns->id = id;\n\ns->gpa = gpa;\n\nreturn s;\n\n}"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.