Instantly share code, notes, and snippets.

Embed
What would you like to do?
New Refactoring Presenter with static factory method
public class ExtractMethodPresenter
: RefactoringPresenter<ExtractMethodModel, ExtractMethodDialog, ExtractMethodViewModel>
{
public ExtractMethodPresenter(ExtractMethodModel model, ExtractMethodDialog view, ExtractMethodViewModel viewModel)
: base(model, view, viewModel) { }
}
public class RefactoringPresenter<TModel, TView, TViewModel> : IDisposable
where TModel : class
where TView : Form, IRefactoringDialog<TViewModel>, new()
where TViewModel : class, new()
{
protected readonly TModel model;
protected readonly TView view;
protected DialogResult dialogResult;
public static RefactoringPresenter<TModel, TView, TViewModel> Create(TModel model)
{
return new RefactoringPresenter<TModel, TView, TViewModel>(model, new TView(), new TViewModel());
}
public RefactoringPresenter(TModel model, TView view, TViewModel viewModel)
{
this.model = model;
this.view = view;
}
public TModel Model => model;
public TView View => view;
public TViewModel ViewModel => view.ViewModel;
public virtual DialogResult DialogResult => dialogResult;
public virtual TModel Show()
{
dialogResult = view.ShowDialog();
if (dialogResult == DialogResult.OK || dialogResult == DialogResult.Yes)
{
return model;
}
return null;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
view.Dispose();
}
}
}
var model = new ExtractMethodModel(_state, selection.Value);
var presenter = ExtractMethodPresenter.Create(model);
if (presenter == null)
{
return;
}
model = presenter.Show();
if (model == null)
{
return;
}
@retailcoder

This comment has been minimized.

Copy link

retailcoder commented Nov 24, 2017

I love the use of generics here, but if M V VM are passed through the base ctor then I see little use for them being virtual. Show method can reasonably be overridden in a derived presenter class, so that's good.

IDisposable implementation involving inheritance and virtual methods should use the "dispose pattern" to ensure disposable base class fields get disposed when a derived class overrides the dispose method.

The presenter null check in the calling code can be done on the model assignment: model = presenter?.Show() that way only the model needs a fully-spelled null check =)

@bclothier

This comment has been minimized.

Copy link
Owner Author

bclothier commented Nov 24, 2017

Updated to use the dispose pattern correctly (oops!) and made View & Model non-virtual.

@bclothier

This comment has been minimized.

Copy link
Owner Author

bclothier commented Nov 24, 2017

Updated to reflect the fact that ViewModel is a property of the WinForms dialog via IRefactoringDialog interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment