C# – Refactor class (extract methods) in a main / helper classes

crefactoring

Simply spoken, one of my c# classes got too big and I'm currently splitting this class in several subclasses by clustering semantically related methods (actually actions, which do side effects).

So, to give you an example:

class ViewModel
{
  // a lot of properties bound to view (MVVM pattern)
  public Property 1 //bound to view
  public Property 2 //bound to view

  // a lot of actions, containing the controller logic of the view
  //Function 1 changes Property 1 -> shall be moved to class MyViewModelHelper
  Function1() {}

That is, when I create a helper class for the viewModel, it needs to to receive the instance reference of the main view model in its constructor, so that it has access to the public properties.

I do not want that the view has to have the knowledge about the helper classes, that is the main view model shall provide all the properties… but the functions shall delegate the work to the helper classes to keep the viewModel class maintainable.

Best Answer

Sounds like a case for using extension methods. Simply move Function1() to MyViewModelHelper, make it static, and change the first/only paramater to be like this:

public static class MyViewModelHelper
{
    public static void Function1(this ViewModel vm)
    {
        // whatever
    }
}

As a benefit: afterward, the semantics of the callers often don't need to change.

Related Topic