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
or
42 + parseInt(fortyTwo); // also returns 84
or
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; }

    [Required]
    public string request_type_id { get; set; }

    [Required]
    public string screen_id { get; set; }

    [Required]
    public string request_subject { get; set; }

    [Required]
    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!

What’s in a name?

Working on a team can be tough.

It’s necessary for rapid, effective development- a team can work much faster and has a much larger knowledge base than a solo developer.  It’s also necessary for security and building a robust application- a team of eyes will spot issues and possible improvements that a solo developer might miss.  So I understand the many benefits.

But it also has pitfalls.  We are working on a .net API for our Angular application.  As part of this API, an admin can change the email address in a user’s account (which also serves as their username).  During testing, we found that edits to the email weren’t “taking”.  We could update anything else, but when trying to update the email, the dreaded “500 Server Error” message kept popping up.

So I started digging.  The error in the stack trace shouted at me: “Object not set to instance of an object” – which, though past frustrating experience, I learned is a null pointer exception.  Somewhere in the API’s Put method, we were referencing a property or method on an object that had never initialized.

But I just could not see it.  I started working as a developer solo- which can be difficult in it’s own way, but one advantage is that I (usually) know where I put things.  Where I initialize variables, where I add logic, etc.  Not always- sometimes lazy present me really screws over frustrated future me- but generally it’s pretty quick to find the path of my previous thinking.  I couldn’t see the error in this codebase by looking, so I started logging to the console (see previous post!).  Eventually, I got to the null object- a duplicate call to a method we use to get a user info object.

We work with another team remotely.  They do great work and having worked solo, I appreciate that they each have a head full of tips and tricks and knowledge that I may never have.  But sometimes they might not examine anything too deeply before starting on the coding.  They receive a job and a prototype or existing file and build it/update it with new functionality- they don’t necessarily analyze what’s already there for conflicts.

In this case, they had been tasked with adding a feature to the .net code to allow an admin to edit the access level of an account (employee vs admin).  When they added this to the update method, they ignored the code above that covered updating the rest of the account.  The method variables were up there- including the one that instantiates the object representing the user being updated.  This is done with a reference to their unique user id (which is never changed).  In the new code, an attempt was made to create a user object by referencing their email address.

And there’s the bug.  You can’t get a user by email if they’ve just changed that email (or if you get really unlucky, and that email already exists in the system, you’ve got an even trickier bug).  The fix to this bug was ridiculously simple- remove this 2nd user object and update the calls below it to reference the original user object.  Works like a charm now.  Finding the bug was trickier- it was hidden in the middle of a method and the reference to the user was not named something obvious (it was called “roles”).  When I scanned the code, “roles” didn’t really register as being involved in an email account update, but it was the culprit.

A team can put processes in place to mitigate the issues of distributed development- but it requires some extra work.

  • A style guide and naming conventions is a great step.  Make sure all your devs are on the same page by putting the requirements on an actual page (or a virtual one).
  • Take it a step further and create a set of linting rules to enforce the guide- maybe make an update pass all the checks before you can push to git or svn.
  • Do code review sessions- instead of moving forward with new code every day, take the time to review what was written yesterday.  Just because something compiles and outputs what you want doesn’t mean it should be in the final product.

This can be tough to sell to a supervisor- there’s no real immediate benefit as far as project progress or new tasks checked off a list- but it can really save time down the road.  Sometimes, it takes one developer to push for such a shift- a shift that will make your and your co-worker’s lives easier.

Multiple Method Madness

Arguments are generally important.

Different languages have different ways of dealing with them- but a couple have really interested me lately.  I work mostly in Javascript- which generally doesn’t care at all about your arguments.  Sure, you might have a function that accepts “error” and “callback”, but JS doesn’t actually care if you pass them or not.

That can be kind of useful- though sometimes a bit confusing.  Sometimes, I’ll have a function that has a couple different possible outcomes.  Simple example: In our Angular application, there are multiple methods that get info from the database (using observables).  Sometimes, we will need a final callback to fire after the data is retrieved.  You can pass 3 ‘blocks’ to a subscription: the success, error, and finally blocks.  That finally block is a great place to perform a task like hiding a ‘loading’ animation.

But in one case, the method calling the .subscribe function was on a shared service, and the function that needed to be called in the ‘finally’ block had to remain on the component itself (it created a d3.js chart and needed access to the DOM).  So, we added an argument to the method on the service for callback.  Something like:

getData(cb) {
    backendService.get(url).subscribe(response => {
        //set local variables and manipulate data response here
        this.myData = response.map(d => d);
    }, error => {
        //handle errors here
        console.log(error);
    }, () => {
        //clean up and call callback
        if(this.myData && callback) {
            cb(this.myData.length);
        }
        hideLoader();
    });

The ‘finally’ block doesn’t take any arguments- you just perform tasks. In this case, I check to make sure a callback has been provided (see below for details), and to make sure the data came in (check the length because I think a simple boolean check on an empty array still returns true- but 0 will return false).  If it did, I fire the callback (sending the data to the chart and drawing it to the screen.

To call the method, we have a couple options.  Pass a callback function or don’t.  Like I said- JS don’t care.  If I don’t have a graph to draw but need to get data, I just don’t pass a callback.  The check in the ‘finally’ block to make sure ‘callback’ exists before it’s called prevents any errors.  If a callback is provided, it gets called when the data is available.  Pretty cool!

In a statically typed language like C#, things are a bit different.  C# definitely cares about arguments.  If you try to pass nothing to a function that has arguments, you get an error.  If you try to pass an argument to a function that takes none, you get an error.  If you pass a string argument to a function that takes an int argument, you get an error.

You get the idea.

Strict, but no less useful than the JS method- it just requires a different mindset.  You sacrifice flexibility for security.  You know what that function takes and it will not run with anything else.  Probably leads to less bugs down the road.

And you have different options for flexibility.  In C#, you can have two functions with the same name- as long as they take different arguments:

public int addStuff()
{
    return 2 + 2;
}

public int addStuff(int y)
{
    return 2 + y;
}

Stupid, simple example- I know.  But still a pretty cool concept.  You get the same flexibility at the call site as you would with JS.  The addStuff function doesn’t care if I pass an int or no int (as long as I have both methods accounted for above).  It will still give me what I want.  The above example wouldn’t be very useful, but we did use it for a method in our live application.  I’m a bit new to the .net world, but it’s still cool to see the parallels with something familiar (and the differences).

A Static Sort of Typing

The more I use c#, the more I grow to enjoy having a type system.

I started with PHP- which I believe is dynamically typed, and Javascript, which is pretty much just the Wild West where anything goes.  I never really had to worry about providing info to my program about what this variable would be, or what might be returned from a function.  I remember my confusion in seeing the ‘void’ term for the first time on a function declaration.

And dynamic typing can be great.  It can be really quick and easy to set something up.  Example: to declare a variable in Python, you just type your var name then the value: i = 1.  There you go- i is ready to use and the language will infer (hopefully correctly) what you meant i to truly be.

But as a program becomes more complex, having static typing, or at least a static type checking system, becomes very useful. When I declare variable i in c#, it’s slightly longer: int i = 1, but that ‘int’ lets any program or action using it know that it is an integer.  With modern editors, you’ll be notified right away if you do something wrong with it.  At worst, you’re notified at compile time, not run time, so you can fix it before anyone notices that you tried to add the string ‘dozen eggs’ to the number 1 before calling .ToString().

And now in Javascript land, a small group of brave lawmen have come to town.  Typescript is keeping watch over our little project, and as someone who started out in dynamic/no type land, it seems like the best of both worlds.

Part of that is flexibility.  In most cases, using Typescript is optional.  Set it up in your JS project and don’t make any changes (except renaming .js to .ts so the transpiler finds what to work on).  Most times, your files will just work.  There are some exceptions, but it seems like most are due to really bad code (see personal example below).

I can still just declare a simple variable: const i = 1.  Or, I can provide more info: const i: number = 0.  In the latter case, the transpiler (and my editor) will complain if I try to add i to a string- they’re different types.  This flexibility allows for a smooth transition into Typescript- we can use type checking on just a few important functions or variables and leave some others as plain JS for now.  This is a very simple example: adding a string to a number in JS generally causes no problems, but things like this can be the source of very hard to find bugs (JS is well meaning in its type inference, but can’t always get it right).

One ‘gotcha’ I did run into was with a sorting function.  We needed to sort a grid by some options, but each column might have a different kind of data.  For example- the grid might have a column for date (a Date object), name (string), and id (number).  I tried running a simple array.sort method on all my info with a conditional on the type of what was passed:

return group.sort((a, b) => {
    if(typeof a[param] === 'number') {
        return b[param] - a[param];
    } else if(typeof a[param] === 'string') {
        return b[param] > a[param];
    } ...

a and b are objects and the param variable is passed into the wrapping function (which allows for sorting an array of objects by a specific parameter).

That’s a simplified version of the real first draft- the real one has checking for empty strings, conversions to lowercase to ensure we’re comparing the correct number code, etc.  However, there’s already a problem, according to Typescript (and any statically typed language).  There are two possible return types: number (branch one) and boolean (branch two).  This is fine (well, it’s allowed) in JS, but not in a statically typed language.  The Typescript transpiler throws an error and won’t cooperate.

And there is a quick and dirty solution.  Typescript has an ‘any’ type.  Add that as the return type for the sort function and it will transpile:

group.sort((a, b): any => {

But our sort function is still an ugly mess.  And that’s another thing static type checking seems to provide.  Initially, I was frustrated with the whole system- finding the ‘any’ type was very exciting.  But as I learn more c# (where you have to provide proper typing), I realize that the type system helps you write better code.  My old sort function was poorly written and hard to follow.  Having a function with multiple possible return types is not a great idea (I’m sure someone will tell me how wrong I am, but just go with it for now).  And in the sort function, this notion is absolutely correct.  With Javascript’s array.sort method, it seems generally best to return either 1 or -1 from each comparison.  You can just return the difference or true/false, but it can lead to bugs.  So, instead of the quick and dirty solution (putting the ‘any’ decorator on my function), I really needed to refactor the structure:

return group.sort((a, b) => {
    if(typeof a[param] === 'number') {
        return b[param] - a[param] > 0 ? 1 : -1;
    } else if(typeof a[param] === 'string') {
        return b[param] > a[param] ? 1 : -1;
    } ...

Please excuse any typos- this isn’t production code, just an example.  Each return checks for a boolean result, then returns either 1 or -1.  Now we have a function that uses the array.sort in a more efficient manner, and has a unified return type.  Typescript’s ‘any’ type is useful in some situations, but I now really check myself before using it.  Generally it’s a smell that means I’ve done something wrong or overly complex that can be refactored.

So, that was part of my journey to loving static typing.  It’s about delayed gratification.  More work up front for less headaches down the road.  By the way- a major side benefit of Typescript is that the transpiler will take car of any ES6 -> ES5, so you can use all the cool new JS features in addition to (optional) static typing.

Hold My Beer

The rallying cry of a redneck about to do something really stupid.  I think we should have a version in the programming world where it means: “I just spent half the day writing this code and not compiling/running it once- here goes!”  You’re likely about to hurt yourself in a spectacular manner.

But this time, for the first time ever, it actually worked (results not typical).  I was adding a really simple module to allow an admin to add new activity types (for audit logging).  Usually, I will recompile the .net code at multiple steps, but with Visual Studio, that has become less important- it will yell at me with those red squiggly lines if I really mess something up.  It’s my complete newbieness with C# that usually causes the issues- generally trying to use JS syntax and finding that it just doesn’t work that way.  Imagine my surprise when I finally ran the app and it not only compiled without error, but also did what it was supposed to do!

But no one would recommend this as a best practice.  And really, most modern development tools have checks against this built in.  There are Visual Studio’s aforementioned red squigglies that burrow though your eyes and into your brain, relentlessly mocking you and your stupid mistakes.  Also, on the front end, when working with a transpiled language like Typescript (which we are and it’s awesome), you usually have a “Typescript compile watch” constantly running.  Whenever you make a save to a file that’s being watched (usually all .ts and .html files within your app folder), that watcher will automatically attempt to re-transpile the entire thing.  If you’ve done something really dumb, the command prompt will yell at you (no red squigglies, but oh well – also, the word ‘squigglies’ also results in a red squiggly line!).

Of course, an app can compile or transpile and still be completely broken, so it’s definitely good to test frequently after small changes.  Even when your dev tools don’t force you to.

There’s a great line in the Mel Gibson (I know) ode to violence and America “The Patriot”.  He’s giving his young sons quick tips on how to kill British soldiers in the most effective manner possible.  He says “Aim small, miss small”.  It’s cheesy and I have no idea if it actually makes you a better shot, but it is solid advice to co-opt for writing code.  Add or modify something small and check your results.  You might miss- but it will take a much smaller correction than if you spent hours editing multiple files across your entire project, only to find you’ve broken the whole thing.  Or missed that evil Redcoat!

The metaphor might have broken down a bit at the end there, but I think you get the point.