Reputation: 15
If I have a class as follows:
public class Name
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String FullName()
{
return FirstName + " " + LastName;
}
}
FullName() concatenates the first and last names so it makes sense for it to be a method. Suppose I change how the class works so it stores the full name as a string and FirstName and LastName return substrings. It would then make sense for FirstName and LastName to be methods and FullName to be a property. I read these guidelines on where to use properties which states that properties should not be interdependent.
Doesn't using properties and methods break encapsulation as it means you are exposing your internal implementation details to external code?
In cases like this where you don't want to expose which values are stored and which are derived what should you do? Presumably they should all be methods or they should all be properties but which?
Upvotes: 0
Views: 279
Reputation: 43636
If you want to follows these guidelines strictly then I would create full properties for First and Last name and use a get only accessor on FullName to the private fields, since his guidelines only mention Property dependency not field dependencies.
I assume the guidelines are based on the fact logic can be performed inside getters and setters, going the field route will eliminate that risk
Example:
public class Name
{
private string _firstName;
private string _lastName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string FullName
{
get { return _firstName + " " + _lastName; }
}
}
Upvotes: 0
Reputation: 32596
It is arguable if properties should or should not be independent.
I would say that in your case, having property
public String FullName { get { return FirstName + " " + LastName; } } // no set
looks acceptable.
Compare with .NET Rectangle.Bottom property, which returns sum of two other properties
The y-coordinate that is the sum of Y and Height of this Rectangle.
Upvotes: 1