Simpler code in handlers using pattern matching

Published
Monday, December 30, 2019
Category
xmpp
Author
alex

The pattern matching feature which came with c# 7 can be very useful when writing XMPP stanza handlers with MatriX.

The handlers are using predicates to filter and match stanzas. Sometimes the predicates can get very complex and would require a lot of type casts without pattern matching. So pattern matching makes you code much more readable, but also faster at runtime because we can save some casts of objects.

Here is a small code snippet of a stanza handler which is responsible for XMPP roster pushes.

Code without pattern matching

public class RosterHandler : XmppStanzaHandler
{
    public RosterHandler()
    {
        // handle roster pushed
        Handle(
            el =>
                el.OfType<Iq>()
                && el.Cast<Iq>().Query.OfType<Roster>()
                && (el.Cast<Iq>().Type == IqType.Result || el.Cast<Iq>().Type == IqType.Set),

            async (context, xmppXElement) =>
            {
                // do something with the stanza
            });
    }
}

Code with pattern matching

The sample below used also the IsAnyOf extension method which was added to MatriX recently

// With pattern matching
public class RosterHandler : XmppStanzaHandler
{
    public RosterHandler()
    {
        // handle roster pushes
        Handle(
            el =>
                el is Iq iq                
                && iq.Query is Roster
                && iq.Type.IsAnyOf(IqType.Result, IqType.Set),
            async (context, xmppXElement) =>
            {
                // do something with the stanza
            });
    }
}

of course you can use XPath or other technologies fore more complex stanza filtering in MatriX. I personally just prefer predicates becuase they are strongly typed and also fast.