Strategies when to use properties and when to use internal variables on inner classes?

In almost all my classes, I have a mixture of class properties and internal variables . I always chose one or the other according to the rule " if you need it from the outside, a class variable, if not ." But there are many other problems that make me rethink this often, for example:

  • At some point, I want to use an internal variable from outside the class, so I have to refactor insert the property into the property, which makes me wonder why I don’t just do all my property of the internal variables in case I have to access them from outside, since most classes are inner classes anyway , they don’t appear in the API, so it doesn’t matter if the internal variables are accessible from outside the class or not

  • but then, since C # does not allow you to instantiate, for example. List<string> in the definition, then these properties should be initialized in every possible constructor , so I would prefer these variables to have internal variables in order to preserve purity in the sense that they are all initialized in one place

  • C # code is read more cleanly if the constructor / method parameters are a camel case, and you assign them to pascal properties rather than the ambiguity of viewing templateIdCode and should look around to see if it is a local variable, a method parameter or an internal class variable, for example, easier when you see TemplateIdCode = templateIdCode that this is a parameter assigned to a class property. This will be an argument for always , using only properties for inner classes .

eg:.

 public class TextFile { private string templateIdCode; private string absoluteTemplatePathAndFileName; private string absoluteOutputDirectory; private List<string> listItems = new List<string>(); public string Content { get; set; } public List<string> ReportItems { get; set; } public TextFile(string templateIdCode) { this.templateIdCode = templateIdCode; ReportItems = new List<string>(); Initialize(); } ... 

When creating internal (non-API) classes, what are your strategies when deciding whether to create an internal class variable or property?

+4
source share
1 answer

If I have a private variable that I find, I need public access at a later point, I just create a property that uses it as a private member, ex:

 private List<string> listItems = new List<string>(); Public List<string> ListItems { get{return listItems;} set{listItems = value;} } 

This allows you to create public access to data without the need to refactor any code. It also allows you to initialize data in a private member and does not need to do this in the constructor.
Another advantage is that any data changes that you want to make to those who have access to public property can be made in getter. Although VS2008 introduced automatic properties as a function, I still prefer the VS2005 property style.

+1
source

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


All Articles