Back to previous page

Typescript Design Patterns for SharePoint Framework Part 1 – Factory Method

I wanted to write this for so long but studying this subject, practising and achieving the desired results its not an easy task. If you come from the server development background like I do (C#/.NET Development for Farm solutions) or WCF services, REST API, or event ASP.NET WebForms or MVC, and if you worked in large projects then there is a big chance that you used some programming design patterns, at least the singleton pattern you had to use at some point in time. As a Solutions Architect I was responsible to design and deliver large projects where code maintenance is one of the hardest things to achieve in huge projects, we had to create code that everyone can read, interpret and where changes can be applied easily. Design Patterns allow you to create clean and understandable code that everyone can understand (with some experience) and introduce changes after delivery to production.

So my idea is to start writing during the next months about Typescript design patterns applied to SharePoint Framework webparts, we know SPFx is 100% client side, but that doesn’t mean that we have to just create UI logic and put everything into just a .TS file without any kind of structure, this is what I will try to achieve here.

Design Patterns:

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Creational Design Patterns Series:

  1. Factory method (this post)
  2. Abstract Factory
  3. Builder
  4. Prototype
  5. Singleton

There are other categories as well: Behaviour, structural, SOLID principles, which I will cover when I end with this first series.

Factory method:

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

Another definition which I liked more and fits perfectly my sample today is the following, taken from: https://www.javatpoint.com/factory-method-design-pattern

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the sub-classes decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.

Advantage of Factory Design Pattern

Factory Method Pattern allows the sub-classes to choose the type of objects to create. It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class.

When to use Factory Method Design Pattern

  1. When a class doesn’t know what sub-classes will be required to create
  2. When a class wants that its sub-classes specify the objects to be created.
  3. When the parent classes choose the creation of objects to its sub-classes.

So lets start this journey explaining how I saw this factory method pattern could be applied.

In a SharePoint Site we can have multiple lists and all those lists could have different columns or fields, why not create a generic way to build the list item objects depending on the selected list? well in plain English, a webpart where you can select the list, and based on the selected list it will render all the columns, sure you can do this in many ways and probably with lots of switches/if statements, etc, but I wanted a more elegant solution and I believe this sample will do just that.

Starting now, all the Design Patterns will be on my github repo at: https://github.com/levalencia

Diagram

Diagram

So instead of classes we have interfaces for the generic list item (IListItem), and then other interfaces that extends the base one to add more fields depending on the list, news, announcements and directory.

On the right side of the diagram we have an IFactory interface that declares the signature of the method getItems and what it should return (any), remember at the end all items will be of type IListItem because they extend that interface but in order to make it work we will have to use an array of any[].

And finally on the FactoryMethod react component we use the ListItem Factory to get the items, from the caller point of view, we don’t care what it will return, its the factory method responsibility to actually create the logic inside to know which instance types it should return.

Project structure

Dataproviders

Models

The models just define the type of objects we want to return from our factory method, better for strong typing our return objects.

Factory classes

So the Factory interface is quite simple, we just have a method to implement in the extended classes.

Its in this method below where we actually have a switch statement to get a different list with a different URL (Select columns), and then on the return we get different concrete types by mapping the json result to a different instance of the needed type.

Props and states

Properties we pass from the main webpart to the component are defined in the props interface, things like SPHttpclient are important here, state is where we actually store our returned information from the server, because listitems could be of different types, I created a wrapper Interface and depending on the type of list, then the state would be read from a different state property DetailsListItemState, DetailsNewsListItemState, etc.

We will see later in the series how could achieve this with shorter code, but for this pattern its what I need so far.

The component

The component has a lot of UI logic, but the real Factory method magic is only in the readItemsAndSetStatus method, where we use the Factory class to get the items and then set the corresponding state, this is pretty nice as we avoid lots of code with the setstateLine and the getitems method here.

Some code I think its really self explanatory so I don’t explain it, if needed put a comment below with a question to further explain something.

If you are new to React then I really recommend to read this from the official documentation, which explains the component life-cycle, after reading this, it will clarify concepts for you: https://reactjs.org/docs/react-component.html

The WebPart

And finally the webpart code is below, with self explanatory comments for the reader to understand the events life-cycle.

I hope with this post the design pattern is clear and you can apply it in your own way to your upcoming projects.

About the Author: 

Luis Valencia, CTO at Software Estrategico, Medellin, Colombia, independent blogger and still a coder, after 17 years of experience in the field and regardless of my position, and mostly with SharePoint/Office Products, I still love to code, open Visual Studio and bring solutions to users and to the community its what makes me wake up every morning.

Feel free to contact me via twitter direct messages, @levalencia

Reference: 

Valencia, L (2018). Typescript design patterns for SharePoint Framework Part 1 – Factory method. Available at: http://www.luisevalencia.com/2018/01/12/typescript-design-patterns-for-sharepoint-framework-part-1-factory-method/ [Accessed: 7 November 2018]

Share this on...

Leave a Reply

Back to previous page