开发者

Is anything good/bad/unnecessary about this use of a public member?

开发者 https://www.devze.com 2023-01-18 11:35 出处:网络
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.

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 Pr开发者_如何学运维esenter 
{
   // 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.


Just give the Presenter a Run() method.


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.


The benefits of your third approach (which I like most) include:

  • You may add logic to the getter later without the need of recompiling calling code
  • Encapsulation: you have exactly one place in your code that gets the value from the actual field, allowing you to add logging or use any other debugging mechanism to troubleshoot unexpected behavior.
  • The encapsulation also means that you could actually change the field to hold some other type, as long as it can be converted to IView. This conversion can happen in the getter.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消