Use `//@ts-check` in Visual Studio Code to Find Undeclared Variables (and save yourself hours of hunting)

Oh. My. God!

I just discovered //@ts-check in Visual Studio Code.

For all the web/JavaScript developers out there, add that comment to the top of your .js file in Visual Studio Code (that’s all you have to do).

Now, any issues in you variables (like using variables you haven’t declared) will show as an error in the IDE.

This is what I call super charging your IDE and your development.

I could have saved myself half a day’s work yesterday if I’d thought to search for “visual studio code undeclared javascript variables” beforehand. ?‍♂️

See: https://code.visualstudio.com/docs/nodejs/working-with-javascript#_type-checking-javascript

JavaScript (ES2015) – Handling Promises in a loop (full working example)

I’ve spent the best part of the last day and half working with a simple Promise problem in JavaScript.

The scenario I have is:

  • I have a tree structure of folders (and sub-folders) with documents in them.
  • The production scenario I’m emulating is to submit each item in the tree (both folders and documents) to an API for saving, and to receive a return object with a new ID.
  • Documents are are associated with folders via IDs (e.g. Document.FolderID = Folder.ID and Folder.ParentID = Folder.ID).
  • Each item is added to an array of data in my JavaScript app.

The heart of this problem is the asynchronous call to the API. Because I need to associate documents with folders, and sub-folders with parent folders, I need to process each folder and wait for the response to get the new ID before processing sub-items.

Old school, this was done with callback (and I still use callback to this day). But in the interest of staying “modern” I took the ES2015 Promise approach.

Another thing to factor in is the loop through folders and items in the tree. I chose the for(let i; ..; ..) approach to pluck items out of the arrays in the tree. However, you can’t just call the api within the for loop because by the time an async finishes executing and you’re ready to process the next item,. the loop could have iterated on, changed the value of the iterator (i in this example) and hence the currently item in the array.

So you need to wrap the call the API in another function to localise the scope of the variables.

At the end of processing the tree I also need to tell the calling function everything is complete. Which means tracking the completion status of all promises in the loop and notifying the caller of overall completion only once all branches are finished (using Promise.all()).

Anyway, I created a fully working Pen at https://codepen.io/jsnelders/pen/LYVJQbG to demonstrate how this works.
I suggest you pop it open in CodePen itself to see the results – open the browser console (not the CodePen Console) to view debug output.

See the Pen
JavaScript (ES2015) – Handling Promises in a loop
by Jason (@jsnelders)
on CodePen.

JavaScript (ES2015) Promise error “Uncaught (in promise) {reject message}”

Debugging asynchronous code is difficult. Even Promises can become complex.

And once again my Golden Rule of Programming rings true: “if you think something should work but it doesn’t, you probably have a spelling mistake!

 

I’m working on a simple script to test JavaScript Promises – specifically, handling Promises in loops, and dealing with functions that both handle and return promises.
I’ll post about that later when I’m done.

For now, I just spent the last hour trying to figure out why I was getting a JavaScript console error Uncaught (in promise) processItems(Folder: 1): Reject caught (the part in italics is just a message returned in a reject(“processItems(” + title + “): Reject caught”)).

 

The console looks like this:

 

And the problem code is:

executeFolder(item, parentFolder) 
{
    let promise = new Promise(function (resolve, reject) {

        _this.asyncFunction(item)
        .then((resultItem) => {
            _this.processItems(item, resultItem).then(() => {
                resolve("executeFolder.then(" + parentFolder.title + ")");
            });
        })
        .catch( (e) => {
            reject("executeFolder.cathch(" + parentFolder.title + ")");
        });
    });

    return promise;
}

 

The problem is the line in bold: _this.asyncFunction(item).

I hadn’t defined the variable _this (I’d extracted this function out of another function which did have the definition).

All I had to do was define _this and the error resolved.

 

Once gain it was a spelling error (in this case not spelling anything at all).

I stopped feeling bad about these sorts of errors long ago. I’ve learnt over the years we (as developers) get a kind of blindness or tunnel vision when working on problems like this. Between having to hold the business problem, processing logic, nested functionality and all the other bits in our head, we can easily blank out what we later think was “staring us in the face”.

That’s where a good IDE comes in that can track unused variables.
I’m using Visual Studio Code which does identify unused variables (in fact, I noticed and removed one in the project no long ago) but for some reason it failed me in this instance.

Coding Challenges and Technical Tests When Applying for Jobs

Today, someone I’ve never met, whose name I don’t know, rated and told me I’m not a good software developer.

It wasn’t someone on Twitter or social media. It wasn’t an industry expert.

No, it was feedback I received from coding challenge I did for a job application.

As a general rule I refuse all technical tests and code challenges (even if it means not being able to apply for a job).
I’m not sure why I took this challenge. I guess I let my better judgement slip.

Coding tests in job applications have their place, but having been on both sides of the table (and I’ve never made some do a test) they’re more for assessing entry level developers than people nearing 2 decades of in-the-trenches experience.

 

In this post I want to share my thoughts on the process I went though by using the actual test, sharing my solution and the exact feedback I gave the recruiter I went through.

I’m not name dropping the particular company that required the test. But, their requirements are in a public GitHub repository.
I don’t know the department, team or people I was applying for (there’s a warning sign for you) so I can’t name drop individuals.
I also didn’t sign a waiver with the company against sharing my experience.

To be clear: This is not an attack on any one person or the organisation. I’ve been through almost exactly this instance multiple other times in the past.
This instance simply provides a perfect example to share.

 

One final thing: this was for just a 4 month contact. I’ve done a lot of contracting over the years and have never been asked to perform a code challenge.

This whole situation says a number of things to me about:

  1. The persona assessing me (I can infer their experience as well as their personal motivations).
  2. What the organisation is potentially looking for,
  3. Laziness in the organisation’s recruitment process. Say what you want about “efficiency” in hiring, but this speaks to laziness.
  4. Recruiters are still not doing their job in terms of understanding their industry; understanding the people they represent; educating their hiring clients.

 

The Code Challenge Requirements

The complete requirements of the code challenge were provided via a link to a public GitHub repository at https://github.com/medibank-digital/coding. I’ve also included it below.

 

# Medibank Coding Challenge

## Overview

A web service has been setup at the following URL: 
-	https://gist.githubusercontent.com/medibank-digital/a1fc81a93200a7b9d5f8b7eae0fac6f8/raw/de10a4fcf717e6c431e88c965072c784808fd6b2/people.json

## Requirements
You need to:
- Write some code to consume the json hosted on the above web service.
- Output a list of all the cats in alphabetical order under a heading of the gender of their owner.
- Output must be presentable on a web browser.
- Submissions will only be accepted via GitHub or Bitbucket.

Please note:
- It can be written in any language you like.
- Use any libraries/frameworks/SDKs you choose.
- Use industry best practices.
- Use the code to showcase your skill and what you value in a software application.

## Example

```
Male

Angel
Molly
Tigger


Female

Gizmo
Jasper
Notes

```

2 things immediately came to mind:

  1. Use industry best practices” is a MASSIVE alarm bell for me.
    For 2 reasons:
    a) there is no such thing as “industry best practice” in software development. Developers like to use that phrase but in reality it doesn’t exist and we all know it.
    b) What it really says is “some person wants you to write the specific style of code and architecture that they think is best, and we’re not going to tell you what it is”.
  2. There’s no guidance in terms of what they are looking for.
    Do I need to create a full app?
    Can I create just a helper?
    Are there code standards they’re looking for (and what are they)?
    Are they interested in UI design?
    What if I’ve written it in a language they don’t use?
    What if I wrote it in a language they couldn’t compile and run (they did say “It can be written in any language you like”)?
    Ultimately: how does this represent what they are looking for in the work the candidate will do on the job?
    And what the fuck is the actual goal of this test anyway?

 

The people.json file contained the following:

[
  {
    "name": "Bob",
    "gender": "Male",
    "age": 23,
    "pets": [{"name": "Garfield", "type": "Cat"}, {"name": "Fido", "type": "Dog"}]
  },
  {"name": "Jennifer", "gender": "Female", "age": 18, "pets": [{"name": "Garfield", "type": "Cat"}]},
  {"name": "Steve", "gender": "Male", "age": 45, "pets": null},
  {
    "name": "Fred",
    "gender": "Male",
    "age": 40,
    "pets": [
      {"name": "Tom", "type": "Cat"},
      {"name": "Max", "type": "Cat"},
      {"name": "Sam", "type": "Dog"},
      {"name": "Jim", "type": "Cat"}
    ]
  },
  {"name": "Samantha", "gender": "Female", "age": 40, "pets": [{"name": "Tabby", "type": "Cat"}]},
  {
    "name": "Alice",
    "gender": "Female",
    "age": 64,
    "pets": [{"name": "Simba", "type": "Cat"}, {"name": "Nemo", "type": "Fish"}]
  }
]

 

My Solution

I completed my solution in using React (it was good to practice for something I’m currently learning) and I published it to a public GitHub repository at https://github.com/jsnelders/medibank-coding-challenge.

All up it took me about 4-ish hours. I actually started it while watching TV the night I received the request and finished it the next morning between other tasks. In all I think it was about 4 hours of my time.

Now, that may seem like a lot of time for a simple task like this, and I’m sure there are better programmers than me that can spit it out in half the time or less, but consider the following:

  1. I had to guess at the “hidden” agenda and requirements they were assessing me against. So, I have to spend a bit of time trying to get inside their heads.
  2. It’s a complete React app. Even with create-react-app it still takes time to build one.
  3. I’m new to React and only just [finally] getting into ES2015, so I spent some time with reference material open.
  4. I’ve never worked with the Jest test framework.
  5. I’m an OG developer trying to keep up with “modern” ways of development. In this case, converting my old school (by which I mean more than 5 years) approach to programming JavaScript and use ES2015 approaches. Which, is no more “correct” or “better” than the old way.

 

The Feedback

The feedback I received via the recruiter is exactly as follows:

Here is some further feedback for you.

Positive

    • Used ES6 filter method for sorting list
    • Used config file for url

Negative

    • Didn’t break up React components (one for entire app)
    • Very long methods instead of breaking logic up into smaller chunks
    • Could have used constants for JSON response types instead of repeating string literals throughout class
    • Many of the ‘let’s could have been ‘const’
    • Had a unit test but when try to execute it had a syntax error, so couldn’t execute
    • Inconsistent and Unconventional naming conventions (didn’t use service, utility, some declared with lower case others, while other upper case)

 

To which I replied:

 

Thanks [name],
This is exactly the sort of feedback I was expecting.
I’m all for constructive feedback, but to be honest this is not constructive. If anything it’s nitpicking and disrespectful of candidates because we have to invest at least half a day of our time and can’t even get a reasonable response.
I’ve included in my own thoughts in red beside the feedback. You don’t need to pass it on – it’s for you do understand how a candidate can see this situation.
I just want to reiterate what I mentioned on the phone from a candidate’s point of view:
* A company can’t throw such “small” tests like this at developers without giving at least some context of what they’re looking for. That’s a hostile action, and leaves a candidate unsure of what to focus on and how far to go. How I would approach in a larger enterprise software project is very different to a small “toy” case like this.
* It’s unreasonable to expect candidates to invest hours of their time (ie. a test like this takes a minimum 2-4 hours) and not discuss the results. The comments provided are “not” feedback – they’re just someone’s opinion without explanation.
So it makes me as a candidate ask: Is this how they operate as a team and treat developers? Is their work style and priority to pick on coding style or solve business problems? Would I go into that team and worry every day that all my code reviews are going to be picked on, without standards given, and how would I feel?
Those are the serious questions that come to mind when I apply for a job and (without an interview) have my ability as an experienced developer scrutinised and “picked on” by someone I’ve never met, based on criteria I haven’t been told.
It is honestly an experience that does not leave me feeling good, especially considering we work in an industry where most us – even the best and most famous – still talk about feeling “imposter syndrome” after 20+ years.
Apologies – I don’t want this to sound like a rant, but I do like to give an honest point of view on the testing process to recruiters whenever I can, especially having sat on both sides of the hiring table.
Cheers,
Jason

 

And my responses to the Positive and Negative Feedback:

 

Positive

    • Used ES6 filter method for sorting list [I only did this because I exepcted that’s what they were looking for. A loop is still a perfectly reasonable option too.]
    • Used config file for url

Negative

    • Didn’t break up React components (one for entire app) [Not required on an application of suck low complexity. This should have been stated as something they were looking for.]
    • Very long methods instead of breaking logic up into smaller chunks [Which method are they referring to. I’ve checked all my code and I just can’t see a function I would think necessitates chunking or shortening.]
    • Could have used constants for JSON response types instead of repeating string literals throughout class [Not even sure exactly which code this referring to? If I was to guess, then I’d say I understand their thinking but don’t think it’s reasonable without pre-defining it as a coding standard they use (what I did was “not” unreasonable and would cause not maintenance problems).]
    • Many of the ‘let’s could have been ‘const’ [I’ll concede this “to a very small degree”, bit this is really low-level nitpicking. Both are perfectly valid, and no dev who’s been working front-end web more than 5 years would even consider this a problem.]
    • Had a unit test but when try to execute it had a syntax error, so couldn’t execute [Fair enough. I must have renamed a function and not re-run the test. And technically, it’s not a “synatx” error.]
    • Inconsistent and Unconventional naming conventions (didn’t use service, utility, some declared with lower case others, while other upper case) [I totally disagree (and just saying this one line is not enough feedback). In fact, I used conventions I’ve just learnt that are taught by one of the industry leading teachers of React! And they didn’t set any expected conventions (there is no single one in our industry).]

 

My Thoughts

I’m an very experienced developer. No boasting – that’s just how it is. Almost 20 years in the industry. Many roles. Over 8 languages and variants. I’ve worked with countless different tools, technologies, platforms, patterns, and code from probably hundreds of other developers.

I’m also still a programming software developer after almost 2 decades on the jobs. The number of people with more than 15 years in the industry who can say that is a dwindling number.
I’ve done everything from code Excel to website interfaces, setup and manage deployments to debug production issues, hire and manage staff to run a business.

What that means is I’ve seen and experienced a lot, in an industry that has no certification and governing bodies, and the only thing I can tell you is: there’s no right or wrong way to do things – just someone’s opinion.

All that said, I’m an “average” programmer.I know that. I get shit done and solve business problems – that’s my job. I’ve been through the school of hard knocks more than once in life. And this not the first time I’ve received feedback like this on a coding challenge (most times I never received feedback).

Even so, it’s still a kick to the stomach to be criticised like this, from someone I’ve never met, without a chance for discussion, which is what you would reasonably expect in an actual workplace.

I’ve had exactly one decent technical test in my career as an interviewee. It was about 10-15 lines of  JavaScript printed on a piece of paper. Handed to me during the interview and I was asked to describe how it worked. Speak it out aloud. No right or wrong answers. And we discussed it as we went. 5 minutes taking across a table. I missed something and we discussed it.

That’s how you test someone.

Vue.js 2.x with global store and reactive component data sync

This is a basic test to show how you can use a global object as your primary data store in Vue.js, and use a watcher to trigger a function that builds secondary data sets filtered from the primary source to update the display in the Vue instance (or component).

In this way you can share data between the Vue instance and components (via the global object) and work with the data specifically need by a component while still responding to changes in the global store (e.g. if the global data is updated via a service class or AJAX call).

If the embed below is not working then view it on CodePen at https://codepen.io/jsnelders/pen/dyoJPrw.

 

See the Pen
Vue.js with global store and component reactive sync test
by Jason (@jsnelders)
on CodePen.

 

 

Cheap and Easy “Pipe Cleaner” USB, Headphone Cord & Electronics Cable Ties

I’m a big fan of Fly With Stella on YouTube and one of the tips she’s shared in travel organising is the Nite Ize Original Gear Tie.

Which look awesome and I want them!

The only problem – I’m located in the ass end of the world (Australia) and no-one here seems to stock anything like it. I can order on Amazon, but with normal delivery it’s going to take some time to arrive.

But today I had an inspired idea – I could use Pipe Cleaners! (otherwise known as Chenille Stems).

I actually had a pack in an old craft box, so I cracked it open, got out the wire side cutters, and cut a few pipes into 4 parts (each pipe is about 1 foot/30cm in length).

This is what I ended up with.

There you have it. One pipe cleaner cable tie.

And for about AUD$2.50 for a pack of 40, I can get up to 160 cable ties and colour code until my heart is content.

Don’t tell my wife but before this inspired idea I went to Howards Storage World and bought a 6-pack of BlueLound CableLip cable thingies for $14.95. They’re good, but I already think my pipe cleaners are better.

SMaRT Code Architecture

I’ve been thinking about code architecture in consumer grade software solutions and what I believe matters most.

As a result I came up with:

SMaRT Code Architecture

Which stands for Simple. Maintainable. Readable. Testable.

 

Simple: It’s easy to find (discover), understand and trace code during debugging and or enhancements. The simplest code is no code. Not always feasible. But reducing layers and reducing decomposition can help.

Maintainable: Developers should be able to (and not scared to) fix bugs and introduce enhancements. An unmaintained system suffers from entropy and can become “toxic” within the larger ecosystem.

Readable: Code is written for people to read, not computers. Everyone should be able to easily read and understand the code you wrote yesterday – from a 1st year novice to a 20 year veteran. Fancy or shorthand code works against the next person. Use white space. Write comments to assist in understanding intent. Old school statements are still valid.

Testable: Developers need to easily test their changes. If they cannot there is a lower likelihood of changes being made, and a higher chance of errors when they are.

 

Notice I haven’t mentioned anything about patterns or practices, APIs or languages features. Those are implementation details – how you implement as opposed to what is important.

What is important is code that makes it easy for people in the future to learn and touch the system.

Example of Being Tracked Online by Advertisers

Here’s an example of being tracked around the Internet that happened to me.

Yesterday I heard a product name on a podcast. I thought I recognised it so I looked it up (it was a sports bag my wife has).

In searching for it I visited the product page of an Australian seller (“The WOD Life”). At that point I remembered I actually bought the bag for my wife from that site a few years ago.

About 2 hours later I checked my emails and waiting for me was a new promotional email from the seller.
I haven’t received correspondence from them since I bought the bag.

My guess is, thanks to tracking cookies (advertisers, Google, etc.) I was tracked onto the site, which was then identified by an marketing company running campaigns for the seller, and they decided it was a good time to email me with a reminder to by more product.

 

A few years ago I came home from work to find my place had been broken into and I’d been robbed.

I felt violated by that experience.

Being tracked and targeted online like this holds the same feeling.

Learning React.js and practising in StackBlitz (online IDE)

How easy is it to learn React and practise at the same time?

  1. Start with this course on Pluralsight (https://app.pluralsight.com/library/courses/react-fundamentals-update/table-of-contents).
    Can’t afford Pluralsight (it is expensive for many developers)? You should be able to find something on freeCodeCamp or YouTube (search for something like “React fundamentals or “Learn React”).
  2. Create a GitHub account (every developer should have one for their work and portfolio).
  3. Create an account on StackBlitz – a Visual Studio Code “in the browser” development environment – and link it to your GitHub account so you can start committing (saving) your work as you go.

See the project I’m building as I learn React at https://stackblitz.com/edit/test-react-playground/ (GitHub repo https://github.com/jsnelders/test-react-playground).

Notesheet: Parcel (JavaScript bundler)

Status: Work in Progress (Updated 04 March 2020)


What is Parcel? It’s basically webpack without all the configuration automatically handled out of the box so you can just install it and all your “modern” front-end development compilation happens automatically. Seriously, zero configuration. Clone my sample repository at https://github.com/jsnelders/sample-parcel-js, follow the instructions in the readme.md file and see for yourself.

(That being said, further reading indicates webpack 4 is also zero configuration, though to date I haven’t found a tutorial that doesn’t touch the webpack.js file.)

I discovered Parcel today (11 Feb 2020) and had a test site up and running in under 5 minutes, including typos. Compared to webpack which took “I don’t know how long” to get setup.

  • Keep in mind I’m focused on front-end web development and basically just need it for transpiling ES2015+ to ES5, SCSS pre-processing, minification, bundling and cache busting. And I want the whole setup to be simple.
  • The official site https://parceljs.org/ has a easy getting started guide.
  • The official guide and some articles say you need to npm install the “sass” package but in my sample site this worked out of the box. I suspect that’s because I’m using a version with included features greater than the documentation suggests.

Update after 3 weeks:

  • For the most part it’s working well.
  • It updates packages.json and installs dependencies based on my code without me needing to think about it.
    • One initial hitch was referencing images in Vue.js. Bit after a bit of research I found you can use a JavaScript import like import rootImages from "./images/*.*";, then in your JavaScript you just use rootImages.{your_image_name_in_that_folder}.{image_extension} to reference an image (the value will point to the image path in the distribution/build folder.
      I actually created a new JavaScript module file that includes the import and exposes the images. That way, if I switch back to webpack or some other system, I’ve encapsulated all image dependencies in the once location. Following the the complete code from my file to show what I’ve done:

      import rootImages from "./images/*.*";          // Import to reference Parcel.js generated images.
      import w3images from "./images/w3images/*.*";   // Import to reference Parcel.js generated images.
      // Search: "parcel js copy images" and "parcel js references images in javascript"
      //      https://github.com/parcel-bundler/parcel/issues/1411
      //      https://github.com/parcel-bundler/parcel/issues/3056
      export const assets = {
          images: {
              root: rootImages,
              w3: w3images,
          }
      };
      

      Now I reference [for example] assets.images.root.{file}.{extension} to get the actual path to a file.

  • I have noticed sometimes I’ll create a syntax error (or some other error) while refactoring and I can’t get rid of errors in the browser console. Even a hard refresh doesn’t work. Stop parcel on the command-line then restart it – that usually fixes the issue, or at least generates a new error on the parcel command-line that points me in a better direction to the error.
  • I’m still using parcel in a private SaaS project I’m building. Sometimes I feel the urge to move over to webpack for better errors and debugging, but I’m familiar enough with it now I don’t switch. By moving parcel dependencies to their own JS modules I can still do it in the future with relative ease.

Resources