Reputation: 17186
Here is a synopsis of my code which is a moderately complex WinForms GUI.
The context of the dependencies is the model view presenter pattern.
public class StatSyncherFormView : Form, IView
{ ... }
public class Presenter
{
// Here is the member I made public
public readonly IView view;
public Presenter(IView view)
{
this.view = view;
}
}
static void Main()
{
IView view = new View();
Presenter presenter = new Presenter(view);
// Here is where I'm accessing the public member
Application.Run((Form)p.view);
}
1) I like the fact that view is only set by the constructor and won't be modified after. It makes me feel better in the context of multi threaded GUI development.
2) With public View {get; private set;}
then I lose (immutability?).
3) With private readonly IView view
I also need public View {get {return view;}}
which feels (to me at least maybe someone can tell me otherwise) redundant.
My Question: I feel like (3) is the only way to avoid using a public member, but in this case I do not understand the benefit.
I realize this is minutiae, so Thanks in advance for anyone who takes the time to give me advice about this.
Upvotes: 3
Views: 122
Reputation: 9698
If you use public field, you cannot change it to property later without recompiling your assembly. So I think it is better to do it right at the first place by using property.
Upvotes: 0
Reputation: 124706
This is really just a variant on the publicly-visible fields vs properties debate.
Following the standard guidelines (your option 3) is what most people will recommend, despite what you call "redundancy". BTW I'm not sure which of the following you mean by redundancy
a few extra characters to type, or
an extra getter method at runtime (which will probably be optimized away by the JITter).
In neither case is the "redundancy" significant.
Having said that, in your specific case Hans Passant's answer, which is to avoid the need for the property/field altogether, is probably the best.
Upvotes: 1
Reputation: 158309
The benefits of your third approach (which I like most) include:
IView
. This conversion can happen in the getter.Upvotes: 1