Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

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

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

From other units I can access the field through the public property that provides access to it.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Contrary to David's taste, I always use the private/protected field, but only within the same class (when private) or within a derivative (when protected). Strangly enough, the reason is readability for me too:

  • By now, FCount reads as Count,
  • Using the private field makes it clear I am working on internals,
  • And in the sporadic situation where I use the property, then it is obvious that I need to trigger the setter or getter behind it.

The key point here is being consistent. Choose one, and stick to it. There is no right nor wrong.

Update due to Jerry's comment:

My point about being consistent is a general advise for everyone's own benefit. Accustom yourself with one default syntax, and your code will be crystal clear (to you I mean) for the rest of your life.

Of course, when you choose using private fields, there will be incidental situations you must use the property instead. But this applies vice versa: if you choose to use the property, then there will be situations you have to use the private field. I am only saying that when you stick to a system, the exceptions will more clearly look like exceptions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...