Reputation: 1116
So I need to understand which way is the correct/best one?
class Customer
{
string firstName;
string lastName;
public Customer(string firstName="non", string lastName="applicable")
{
this.firstName = firstName;
this.lastName = lastName;
}
}
class Customer
{
string firstName;
string lastName;
public Customer()
: this("non","applicable")
{ }
public Customer(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
If I'm creating a method printFullName(), it works in both cases. So which one to chose? The first one seems easier to me.
Upvotes: 11
Views: 27593
Reputation: 3964
In terms of semantics, both ways are correct. Some of the differences between the two are
First way: Invoke the constructor as:
new Customer(firstName="first");
new Customer(lastName="last");
new Customer("first", "last");
new Customer();
Second way: Invoke the constructor as:
new Customer("first", "last");
new Customer();
So the first way will give you more flexibility in how you can invoke the constructor.
Upvotes: 11
Reputation: 29222
The second way is better, because it looks like it's your intent to use "non" and "applicable" as the first and last name if they supply no inputs.
If you have just one constructor with optional arguments, someone could supply a first name and have the last name be "applicable," like "Bob applicable."
It's a minor difference because a) it works either way, and b) a consumer can tell what the default parameters are. But the second option seems more in line with your apparent intent.
To be really particular I'd reconsider those defaults. Should someone be able to create a customer without a name? If so then perhaps the name should be null. Perhaps CustomerName
should be a separate class, and Customer
has a Name
property of of type CustomerName.
The reason I'm splitting hairs over that is because you want to know if you have a name or not. Once you supply a fake name that's harder to determine. You could send out hundreds of letters to customers named "non applicable."
Upvotes: 8