Using properties instead of fields in class methods of the same unit is bad practice?

I have declared a private field and a public property for this class.

From other units, I can access the field through a public property that gives it access.

But inside the same unit where this class is declared, I have a choice to access the field directly or through a property.

What is the suggested best practice: direct read / write in the field or through a property that provides read and write access?

+5
source share
3 answers

Unlike David taste , I always use a private / protected field, but only inside the same class (when closing) or inside a derivative (when it is protected). Oddly enough, the reason for me is also readable:

  • Now FCount reads as Count,
  • Using a private field makes it clear that I'm working on internal components,
  • And in a sporadic situation, when I use a property, then it is obvious that I need to call the setter or getter after it.

The key point here is agreed. Choose one and stick to it. There is no right and wrong.

Update due to Jerry's comment:

My point about being consistent is a general recommendation for all of my own benefits. Accustom yourself to one syntax by default, and your code will be crystal clear (for you I mean) for the rest of your life.

Of course, when you choose to use private fields, there will be random situations in which you must use the property. But this is the opposite: if you decide to use a property, then situations will arise when you must use a personal field. I just say that when you stick to the system, exceptions will more clearly look like exceptions.

+6
source

Well, this is probably a matter mainly for personal taste.

I would always choose a property, even when the encoding internally refers to the class declaring the property. For example, a graph rather than FCount reads better, in my opinion.

Another prospect would be that if you provided the public with some property, and this is good enough for public consumption, then it should be good for private consumption.

Another solution will be that if you decide to use the most public interface where possible, it will be more obvious if you use something personal. So, if you find that you need to write FCount because there is no graph, then you have a gentle reminder that this is the personal name that you are using.

So, as I said, there is no final answer, only my personal opinions and preferences.

+5
source

If you do not use getter and setter, it is just a matter of taste. Using a property or field will generate exact code.

If you use getter and setter, you can use a private field if you do not want to use getter / setter code (for example, in constructor ).

If your getter and setter virtual , even if the default implementation is just an assignment, you need to check the SOLID principles and make sure you follow at least the Liskov and Open / Close principles.

+2
source

All Articles