Using constructor: It’s the widely used way of creating objects of a class in most of the programming languages. Based on the need you can overload constructors. See a sample code snippet below.
public class Customer
{
private string _firstName;
private string _lastName;
private string _email;
public Customer(string firstName, string lastName, string email)
{
_firstName = firstName;
_lastName = lastName;
_email = email;
}
}
Usage of the above mention code snippet looks like following.
public class SignUpService
{
public Customer SignUp(SignUpRequest signUpRequest)
{
return new Customer(signUpRequest.FirstName,
signUpRequest.LastName,
signUpRequest.Email);
}
}
Using syntax sugar: Programming languages provide many ways of creating an object of a class. Similarly, there is a lot of mapper library available to do this job for us. Most of these options either use reflection or use constructors. AutoMapper(C#) and Object Mapper(Java) are one of the most used libraries for object creation.
A code example of usage of this approach looks like following.
public class SignUpService
{
public Customer SignUp(SignUpRequest signUpRequest)
{
return Activator.CreateInstance<Customer>();
}
}
Using a factory method: In this approach, you can create an object using a factory method and turn off object creation by constructor using a private constructor.
public class Customer
{
private string _firstName;
private string _lastName;
private string _email;
private Customer()
{
}
public static Customer SignUp(string firstName,
string lastName, string email)
{
return new Customer
{
_firstName = firstName,
_lastName = lastName,
_email = email
};
}
}
Usage of the above mention code snippet looks like following.
public class SignUpService
{
public Customer SignUp(SignUpRequest signUpRequest)
{
return Customer.SignUp(signUpRequest.FirstName,
signUpRequest.LastName,
signUpRequest.Email);
}
}
Each of these approaches has its own use cases, pros, and cons. I will publish a comparison between them in an upcoming post soon till then try these in your project and let us your experiences.