I, Object

I might have mentioned this before, but I started programming with the more loosely typed languages.  Think PHP, Python, or the loosest of the loose, Javascript.

With PHP, you don’t really need to declare what type a variable will be- you can just declare:
$fortyTwo = “42”;

Python is similar, even simpler to declare:
fortyTwo = “42”

Now, if you need to change the type of a declared variable, you might have to re-cast it, but you still don’t have to provide a type annotation beforehand:
PHP: intval($fortyTwo); // $fortyTwo is now 42 – integer type
Python: int(fortyTwo) // fortyTwo is now 42 – integer type

Javascript muddies the waters a bit, as you can add a string directly to a number, but you’re probably not going to like the results:
const fortyTwo = “42”;
fortyTwo + 42; // returns “4242”

It’s safer to explicitly coerce the “type” yourself:
42 + Number(fortyTwo); // returns 84
42 + parseInt(fortyTwo); // also returns 84
42 + +fortyTwo; // a bit more confusing to read, but also returns 84

All basic stuff- but the point is that until I started working with C# earlier this year, I didn’t realize how complicated the very basic task of declaring a variable can be, and how deep into your program those complications can extend.

In a current project, we have a bit of code we use to send out an email notification.  A user submits a form on the frontend to an api endpoint, where a method on that endpoint processes the info and sends the email.  .NET has a base class for this: IEmailSender- you can extend it as needed (and the process of extending classes is a good topic for another time).

The email processing can be used to send a few different kinds of messages (password reset, sales contact form, support request form, etc).  We have different templates for each, with different variables you can replace with custom info (the user’s name, their support ticket id, a password reset token, etc).  So that template info is just passed into our SendEmailAsync function as an object.  First, we initialize the object:

support_email customer_vars = new support_email {
    first_name = loggedInUser.first_name,
    support_id = objModel.support_id,
    request_type_id = objModel.request_type_id,
    screen_id = objModel.screen_id,
    request_subject = objModel.request_subject,
    request_notes = objModel.request_notes

The loggedInUser object is the current user (retrieved via the Json Web Token provided on each request) and the objModel object is the info from the form they submitted.  Now we can pass the customer_vars object into our SendEmailAsync function so they can be used in the template.

But making SendEmailAsync reusable was tricky.  If a variable is going to be passed into a function in C#, you have to give it a type.  Giving it a generic ‘Object’ type won’t work- so usually you just create a simple class or interface, name your fields, and use that as the type.  You can also do useful tasks at this point, like declare required fields or even restrict what can be entered for a field:

public class support_email
    public string first_name { get; set; }
    public string support_id { get; set; }

    public string request_type_id { get; set; }

    public string screen_id { get; set; }

    public string request_subject { get; set; }

    public string request_notes { get; set; }

This works great, until you want to pass a different type of object to the SendEmailAsync method. For example, we want to use the SendEmailAsync method to also send mail regarding a password reset. That’s not going to have a “screen_id” field, but you can’t just pass the wrong object type- C# won’t allow it.

This was an eye opener after a few years in Javascript-land.  There I can just pass anything as an argument and be off and running.  Our current answer is to create a super basic base class:

public class general_email_template {}

Then, each subset of email template simply inherits from that class:

public class reset_email : general_email_template
    //properties specific to reset email here

public class support_email : general_email_template
    //properties specific to support email here

And so on. In the SendEmailAsync method, we use the type “general_email_template” for our template variables object argument type and it works great. Any type that extends the type the method takes is acceptable.

Another possible option that we might explore is having multiple methods with the same name (SendEmailAsync) but different parameters. That way, we could just declare the specific type on each different SendEmailAsync version and let the language decide which one to use based on what it was passed (see previous post about how C# handles methods with the same name but different argument parameters). One approach might be better than the other, but this one works for now!

As an aside, another major difference between a statically typed language like C# and Javascript when performing a basic task is looping over an object. Coming from Javascript, it seems much more complicated in C#:

foreach(var v in variables.GetType().GetProperties())
    string prop_name = v.Name.ToString();
    string prop_value = v.GetValue(variables, null).ToString();

Than in JS:

for(let i in variables) {
    let propName = i;
    let propValue = variables[i];

The type system means you can be much more confident about what you’re getting as each variable, but it can definitely be an adjustment coming from a more relaxed language!

Template for Two – or Twenty

I didn’t realize it, but some recent posts to this blog have had a bit of a theme.  As I work on a couple different projects and we really get into the final stages, I’ve started to realize that sharing is very important.

When you have a medium-large sized web application, there will be a good deal of code written.  It becomes more and more vital to reuse or share as much of that code as possible between different areas or components.  Any intro to development guide will give very good reasons why: unifying the look/function of your app, making it easier to fix bugs, as well as easier to add functionality.  If a feature uses a base class or service for a good chunk of it’s behavior, and that behavior is shared by other features, editing one base class or service is much easier than trying to find/replace across multiple files.

It’s even more important with a team.  Generally, medium-large sized web applications are not written by one developer.  When more programmers get involved, having shared services becomes even more vital to avoid confusion and duplication of work.

So we have some (15-20) views on our Angular 2 application that will all show some kind of single item grid.  These will be two columns in a database (key and name) and when displayed on the app, will just show the name and a column for ‘action’ (edit/delete).  There will be a search text box at the top, a row at the bottom for adding a new entry, and will include the pagination component.

We already covered creating that pagination component in past posts, so all we had to do for that is drop the component’s selector into the template and import the related service.  We did this on a shared ‘single-column-grid’ class- all our actual components that will use this view will extend from that class.

But in this case, we found we could go one step further.  Each screen will be so similar, and only the data will change, that we created a shared ‘single-column-grid’ html template.  By using generic variable names in the template and component class, each component can ‘hook into’ the template and use it as needed.

This dropped the number of html templates needed from about 20 to 1 for this aspect- reducing a whole lot of copy/paste and the typos/wasted debugging time that come along with it.  Also, if the design team wanted to make a change to the layout, they just needed to edit one file, not 20.

One of my favorite tricks from the couple shared base classes we’ve created for this project relates to Angular’s lifecycle hooks.  These are very cool callback functions that fire at certain points in a component’s life- the most recognizable are ngOnInit and ngOnDestroy.  OnInit is very useful for loading data from a database into the component and calling any other initialization type methods you need for this section of your app to function.  However, these only exist on a full ‘@Component’ in Angular- they are not available on a simple ‘@Injectable’ class.  The problem is, we need to do certain tasks when our component initializes, and some of those involve updating the base Injectable class.

At first, I thought we could put the necessary logic in the base class constructor, but that only gets called on class construction (duh).  Because we had multiple child classes sharing that parent, those children would all have to be able to update the parent.  The answer turned out to be: create our own, super simple, onInit!  In the base class, we created a method: serviceInit.  In this method, we have some calls to other methods on the base class that need to fire each time a new component that inherits from it starts up (setup text search, pagination, get initial data from db).  Then, in the child class, in the onInit method, we simply call this.serviceInit() after initializing any class variables.  For example: there is the backend api url- different for each component that needs to get data from the database.  So, in the child class, we just set that variable (and a few others), then call the init method:

this.apiUrl = CONFIG.componentApiUrl;

And the base class serviceInit method takes care of the rest.  We end up having to do very little on the child component- setting up any form that might be specific to that screen only, unsubscribing from any Observables in onDestroy, etc- but most of the logic is in the parent.  If any member of the team needs to create a new component, it becomes very simple to do so.  And if they need to add or fix some functionality of the shared service, they just edit that one file and the fix propagates to any component that inherits from the base.

You Stay Classy, San Diego

So, there are classes in Javascript.  I know- not really, but practically, by using new es6 features, you can create a class that looks and works similarly to any other classical language.  I know- it doesn’t work the same ‘under the hood’- it’s really still just using JS’s existing prototype chain and assignment mechanic (right?).  But it does make it easier for those of us familiar with classical inheritance to quickly create some useful components.

We work in Typescript on one project.  It’s great because it provides a transpiler- allowing us to use the latest and greatest es6 features, then dumbing them down for the real world (i.e.: some older browsers).  When I found myself copying a method among multiple components in an Angular 2 application, my first instinct was to create a service those components could share access to, then move the method there.  But as I thought about it, I realized creating a base class might be just as easy, and a fun alternative to explore.

And so was born the Utilities class.  As a super simple example, I had a ‘cancel’ method on most components.  A user clicks the ‘cancel’ button and the app jumps back to the previous view and shows a notification.  We had a notification component already, and using the ‘Location’ class provided by Angular would make the navigation aspect easy.

The class has a bit of Angular magic- the Injectable decorator (though I’m not sure if it’s absolutely necessary here- it seems like the common practice is to put it on any class that’s not explicitly a component).  Ignore that for now:

export class Utilities {
    public location: Location,
    public notificationService: NotificationService
  ) {}

Looks just like any other JS class so far- except the parameter passed to the constructor.  There’s some Typescript leaking in, but really we’re just instantiating the Location class (provided by Angular) and our NotificationService class (custom- shows a little notification modal).

Then, later in the component, comes the actual method:

cancel(msg?: string, type?: string): void {
    timer: 2000,
    message: msg || 'Update Canceled',
    type: type || 'warning'

More TS sprinkled in there- it’s pretty cool stuff!  A question mark after a parameter means it is optional.  The identifier after the colon is the type (‘string’ in this case- but you can really get wild with this aspect).  Parameters in JS are generally pretty flexible- but this enforces a bit of structure and most editors will have some kind of intellesense going when you use the method that will show you exactly what you can pass to the function.  You can also use TS to define what the function will return (‘void’ in this case).  Note that none of this is necessary to the code working- it’s just useful to a developer and their team- and generally leads to more structured, easy to reason about, code.

Those familiar with es6 are probably laughing at me right now.  There’s at least one more cool refactoring I could make.  Now we can pass default arguments to function parameters.  So, instead of

cancel(msg?: string, type?: string)

We could do

cancel(msg = 'Update Canceled', type = 'warning')

Eliminating the need for the ‘or’ (||) operator in the object passed to the showNotification method.  When the cancel method is called, if there is a parameter passed in the first position, it will be set to ‘msg’- if not, it will pass the default ‘Update Canceled’ string (same with type).  Very cool!

We went down a bit of a rabbit hole there, but to finish off the inheritance aspect- now we just need to make sure the class/component that’s going to use this as a base ‘extends’ it and call the ‘super’ method:

export class UserEditComponent extends Utilities {
    public location: Location,
    public notificationService, NotificationService
  ) {
    super(location, notificationService);

The first part is simple.  The ‘extends’ keyword lets your new class have access to the parent class methods (I’m betting it just assigns your new object to the same prototype ‘under the hood’, though I’m currently too busy/lazy to dig in).  But there is still a bit of work.  In the constructor, you have to make a ‘super’ call and pass along any necessary parameters (those you included in your parent class constructor).  Super calls the parent’s constructor function- necessary to provide this access.

But that’s it!  In my UserEditComponent class I now have access to the ‘cancel’ method.  I’ve been using VS Code lately (great editor!)- the code completion will even pick up that method.  So when I start typing and I get to the ‘dot’ in my call, any method on UserEditComponent or Utilities will show as an option.  The call to the parent class method is as easy as:

this.cancel(//optional msg and type parameters);

Pretty cool stuff.  And again- I think most of this is possible just using traditional JS prototypal inheritance syntax, but having another option is definitely useful.  One caution would be to simply remember that this is not actual classical inheritance.  I think there are some ‘gotchas’ that can happen if you do anything too complex without remembering that it’s all prototypes ‘under the hood’.