Skip to content
loading...

re: Are properties harmful? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Serialization with lazy loading is one use case. A property's "getter" may check to see if its underlying field is populated, and if not, then popu...
 

I see the idea, but is it so bad to just call a method from the outside? I would approach this by having a ReadName method that would do the same as the property getter. (And maybe turn the setter into a method too.) It might be a couple more lines, but I feel like it would be clearer.

 

Here's a bigger serialization example. If you didn't have properties, then you'd have to remember to manually set the DisplayName value, the DateOfBirth_Formatted value, and the CanDrive value, every time you wanted to serialize the object. These three are "get" properties (the arrow syntax is shorthand for a "get" property with no "set") which are basically the same as methods, but because they're properties, they're executed when the data is serialized, and included in the output, with no extra work.

The FirstName, LastName, State, and DateOfBirth properties could be raw data from the database table.

I use this type of thing when I want to pass data from the web server to the client, when I don't want to have to deal with formatting the data in javascript.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string State { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string DisplayName => $"{FirstName} {LastName}";
    public string DateOfBirth_Formatted => DateOfBirth.ToString(@"MM\/dd\/yyyy");
    public bool CanDrive => DriveService.CanHaveDriverLicense(DateOfBirth, State);
}

But in the end, you definitely have a point. Whatever is clearer to you and the people you work with, is very possibly the best way to go. You'll be the ones maintaining the code in the future. But just keep in mind that field-backed properties aren't going away, so it may be worth the time to get used to them because you will see them whenever you maintain someone else's code.

Ah, I see. Serialization is a good point.

code of conduct - report abuse