loading...
Cover image for Refactoring:  Dependency Injection for Reusable Functions

Refactoring: Dependency Injection for Reusable Functions

jwp profile image John Peters Updated on ・1 min read
// In this reusable View component,
// the context of its table
// is injectable with 
// context from elsewhere. 
// This means as a child
// View, others can inject
// the context.

 setTableData(context: any) {
  this.showTable = true;
  this.cdf.detectChanges();
  // Use the reusable function here
  funcSetTableData(
   context, // outside data
   this.paginator, // view 
   this.pageSize,  // number
   this filter,    // string
   this.sort,      // view
  );
  // Back to the view component here
}

Enter fullscreen mode Exit fullscreen mode

Notice that the reusable function is taking in four "this." values. Two of them are Views contained in this View and the other two are string and numeric values respectively. We are "injecting" the reusable function with local values.

From the perspective of this View Component, this is close-coupling; however, the function itself doesn't care where the parameters come from.

Functions just require the proper parameters to work. This means that functions themselves are not close-coupled.

If we create another material table View which re-uses this function it will inject its own required proper dependencies.

We created the function, funcSetTableData when we spotted a possible refactor while thinking about reusability. The number of 'this.' parameters was a clue too.

Had we not moved it into a function library it would have only been known to this View. This is the mal effect of "close-coupling" and not thinking of reusability.

Discussion

pic
Editor guide