Using a method versus a property to retrieve data from a class using LINQ

I am creating a content-driven site with a built-in API created by several developers I work with. The API is just a good LINQ-like layer, similar to ORM, between Sitecore CMS (our CMS in this case) and our C # code for binding data items to controls. I found in several places that I had the opportunity to decide between creating methods and properties to get "sub-items" to receive data.

To explain Sitecore terms, suppose the word "template" means a custom class representing some type of Sitecore.

// retrieve all children of the Sitecore template "Content Folder" below the PageData section
// assume PageData is an object that represents that section in the Sitecore content tree
public List<ContentFolder> GetContentFolders() {
  return PageData.CurrentItem.ChildrenByTemplate("Content Folder").As(i => new ContentFolder(i));
}

The above code will do some LINQ in the PageData section to get a list of sub-items like "Content Folder". Note : .As()- this is just an extension method that makes it easy to create a list of this type. In this example, this is obviously a method. However, should this be public property? For instance.

public List<ContentFolder> ContentFolders {
  get {
    return PageData.CurrentItem.ChildrenByTemplate("Content Folder").As(i => new ContentFolder(i));
  }
}

Which is more suitable? Are they equal? I definitely found a clear example of when a method would make more sense: anyway, when I need to pass its parameters or where I can overload the parameters. For instance.

public List<SupportProductItem> GetSupportProductItems() {
  return GetSupportProductItems(true);
}

public List<SupportProductItem> GetSupportProductItems(bool excludeUnsetProducts) {
  var productItems = CurrentItem.ChildrenByTemplate("Support Product Item").As(i => new SupportProductItem(i));

  if(excludeUnsetProducts)
    productItems = productItems.Where(i => i.ProductSelector.IsSet).ToList();

  return productItems;
}

The case when I selected a property over a method (in my opinion) is when I just check something simple, and do not collect lists of data, for example.

public bool IsSet {
  get {
    return (CurrentItem != null);
  }
}

Instead:

public bool IsSet() {
  return (CurrentItem != null);
}

So, in the code that will look like this:

...
if(ContentFolder.CurrentItem.IsSet) {
  // code
}
...

- , , vs ? - "", ?

+3
2

.

+4

, , :

a) )

, , . .

+2

Source: https://habr.com/ru/post/1748174/


All Articles