I have the following:
public class Person{
public string FirstName {get; set;} = "";
public string MiddleName {get; set;} = "";
public string LastName {get; set;} = "";
public string Title {get; set;} = "";
}
public class Program
{
public static void Main()
{
var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
}
}
I am writing a service class that reports back a user's
- Full name (First + Middle + Last names)
- Title + Full name
- First name and last name
Using dependency injection, I have the following:
(1)
public class NameService{
private readonly Person _person;
public NameService(Person person){
_person = person;
}
public string GetFullName(){
var fullName = $"{_person.FirstName} {_person.MiddleName} {_person.LastName}";
return fullName;
}
public string GetFullNameWithTitle(){
var fullNameWithTitle = $"{_person.Title} {_person.FirstName} {_person.MiddleName} {_person.LastName}";
return fullNameWithTitle;
}
public string GetFirstLastName(){
var fullName = $"{_person.FirstName} {_person.LastName}";
return fullName;
}
}
Which I can use like this:
var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
var service = new NameService(person);
var fullName = service.GetFullName();
However, I can also define the service like this:
(2)
public class NameService
{
public NameService(){}
public string GetFullName(Person person)
{
var fullName = $"{person.FirstName} {person.MiddleName} {person.LastName}";
return fullName;
}
public string GetFullNameWithTitle(Person person)
{
var fullNameWithTitle = $"{person.Title} {person.FirstName} {person.MiddleName} {person.LastName}";
return fullNameWithTitle;
}
public string GetFirstLastName(Person person)
{
var fullName = $"{person.FirstName} {person.LastName}";
return fullName;
}
}
And then get a person's full name like so:
var person = new Person {FirstName = "Daniel", MiddleName = "W", LastName = "Craig", Title = "Mr"};
var service = new NameService();
var fullName = service.GetFullName(person);
Which is the better approach? My thoughts:
(1)
Looks like the service is designed on a "per Person" basis. This means calling another person's full name will require instantiating a new service with a new Person argument (and that's okay).
(2)
This is a lightweight constructor that allows different Person object to be supplied into GetFullName(person) to allow different rendition of full name.
What other pros and cons can you think of?