Skip to main content

Public property, backing up by a private propertyfield, with caching and null checking inside

Tweeted twitter.com/#!/StackCodeReview/status/128728835293319168
Source Link
Saeed Neamati
  • 843
  • 1
  • 8
  • 14

Public property, backing up by a private property, with caching and null checking inside

I have a private field called individualProfile (camelCase) and I've created a public property called IndividualProfile (PascalCase) on it:

private Profile individualProfile; public Profile IndividualProfile { get { if (individualProfile == null) { individualProfile = ProfileFacade.Instance.GetMainProfileByType ( PortalContext.CurrentUserId, ProfileType.IrnicIndividual ); if (individualProfile == null) { individualProfile = new Profile() { FirstName = string.Empty, Family = string.Empty, Details = new IrnicIndividual() { NationalCode = string.Empty } }; } } return individualProfile; } } 

I have to use this public property in almost 10 places, so I first check the private member to see if it's null and load it only once, so that I load it only once and I cache it and use it 10 times. Also, since GetMainProfileByType can return null value, I check another time to see if the private member is null or not. If it's null, I simply set it to an empty object, so that I won't bother checking null values when I bind this object to my view.

Is this code efficient and maintainable? Is there anything I've overlooked?