Creating reusable components using function wrappers (with Javascript)

Creating reusable code is hard. I know, you have crappy deadlines coming up and you just need that feature today. But, before you go ahead and just dial in that feature, consider the future implications of it. Your code doesn’t die tomorrow, it doesn’t die next week, your code lives as long as the product does. Keeping that code base small and understandable is what ensures that working on the project remains as maintainable as possible. That’s the real reason why reusability is so important. However, that’s a discussion for another day. Today I’m covering one part of the puzzle, which is integrating wrapper functions.

If you want to look at the full body of this code, all of it can be found on my github here.

What is a wrapper function

Put simply, a wrapper function is a function which wraps another function. The underlying concept to this is that you write a function that makes functions. You folks are smart, so let’s get straight to our example. Let’s make a function that only returns true if a user has a particular role.

exports.onlyAllow = function(roles)
{
  return function(user) {return roles.includes(user.role);}
} 

What does this do?

So just now, we’ve created a function that expects a number of roles that returns a function, that expects a user which, if the user has one of the prescribed roles, it returns true, otherwise, it returns false. So an example use of it would be

const {onlyAllow} = require('good.js');
let onlyAdmins = onlyAllow(['admin']);//Creates our function
console.log(onlyAdmins({role:'admin'})//Resolves to true

Where are you going with this?

I’m trying to show off the idea of modeling specific behavior instead of specific cases. So in a theoretical app, a specific behavior may be “only allow these things”, which you saw above, another example behavior that I don’t think is as useful or safe for that matter (Meaning admittedly this is kind of stupid) would be something that doesn’t allow certain roles.

exports.dontAllow = function(roles)
{
  return function(user) {return !roles.includes(user.role);}
} 

This particular tidbit may be useful in some middlewares for some apps, but that’s not the point. What you should grasp here is the idea that we’re modeling this particular behavior not a specific case.

What do you mean by a specific case?

When I say that, I’m referring to some yahoo thinking that it’s ‘self documenting’ to do something like this.

exports.isAdmin = function(user)
{     
  return user.role == 'admin'
} 
exports.isWizard = function(user)
{     
  return user.role == 'wizard'
} 
exports.isLizard = function(user)
{     
  return user.role == 'lizard'
} 

Now, what we’ve effectively done here is hardcode every single last role in our made up app. The issue with this is that each of these things don’t reflect a specific behavior we want to capture, they reflect a specific instance of a behavior. The next logical step here would be to also code isNotAWizard, isNotALizard, and isNotAnAdmin, which I’ll spare you for the sake of brevity. I know that reading this you’re going to tell yourself “I’d never code that” I’ve said the same thing and sometimes crunch time rolls around and it just happens. We all do it, it’s a normal part of day to day programming or even happens unknowingly. We’re not wizards (But some edge cases allow us to be lizards) and are unable to see into the future. Broken windows are a part of life, but we should always be vigilant of them. Just look at these mocha unit tests as an example. This is a bit of a long code block, so feel free to only give it a cursory look

const expect = require("chai").expect;

describe("Check Authorization Level",function()
{
  describe("bad wrapper example", function()//6ix9ine
  {
    
    let admin = {name:'brad',role:'admin'};
    let wizard = {name:'brad',role:'wizard'};
    let lizard = {name:'brad',role:'lizard'};
    it('tests for isAdmin',function()
    {
      expect(role.isAdmin(admin)).to.equal(true);
      expect(role.isAdmin(wizard)).to.equal(false);
    })
    it('tests for isWizard',function()
    {
      expect(role.isWizard(wizard)).to.equal(true);
      expect(role.isWizard(lizard)).to.equal(false);
    })
    it('tests for isLizard',function()
    {
      expect(role.isLizard(lizard)).to.equal(true);
      expect(role.isLizard(wizard)).to.equal(false);
    }
  })
  
  describe("good wrapper example", function()//The real slim shady
  {
    let admin = {name:'brad',role:'admin'};
    let wizard = {name:'brad',role:'wizard'};
    let lizard = {name:'brad',role:'lizard'};
    let onlyAdmins = onlyAllow(['admin']);
    let noLizards = dontAllow(['lizard']);

    it('only allow tests',function()
    {
      expect(onlyAdmins(admin)).to.equal(true);
      expect(onlyAdmins(lizard)).to.equal(false);
    })

    it('Dont allow tests',function()
    {
      expect(noLizards(wizard)).to.equal(true);
      expect(noLizards(lizard)).to.equal(false);

    })
  })
})

Our bad testing overhead is a bit larger than our good example. Take the long view here and consider what these two tests will look like with four cases; five cases;ten cases! We don’t need to update our good test cases because all they test are our two behaviors: “Allow this” and “Don’t allow this”. In our bad example, we have to edit our codebase directly to add in this behavior (already kind of icky), which grows it by a few lines, after that we have to add our tests with also grows it by 3 lines (5 if you want to include “isNotWizard” and the like). That’s a lot of growth of nothing vs 10+ lines per case, all because someone didn’t recognize a good place to use a wrapper function.

To Wrap Up (ha)

Use wrapper functions. They’re great at automating specific cases into code behaviors. I know a place that I use them extensively are ExpressJS middlewares, but try to think back to some earlier projects where you accidentally hardcoded each case and consider if you could have employed wrapper functions to alleviate that issue.

Another thing to keep in mind this doesn’t just apply to javascript. Many other languages support similar features, such as decorator functions in Python. If you want to employ something like this in your language of preference, look it up. There’s a wealth of options in many languages to cover this topic.

Organizing your next NodeJS+MongoDB App – Part 1

When dealing with a project of any real substance, one needs to plan (what a thought!). Often this takes place at the diagram level and perhaps even at a technology selection level. In this multi-part post, I wanted to share my method of organizing my app’s backend. In this portion, I’ll be discussing the general layout of our app and explain what each subfolder will hold. Once we’ve established that, in the next post I’ll be going into the nitty-gritty of how some of these bits fit together

Why Read This Post?

You Want Easier To Maintain Files

You don’t want your projects to become 2,000 line monster files. A good developer doesn’t just sit down and start 💩ing out code. Organizing your work into multiple, easier to understand files will slow you down in the short run, but over the life of a 3-6 month project it will pay off in spades.

Your Code Needs To Be Maintained By Someone Other Than You

It’s not just a possibility; it’s an inevitability. Having your project organized into a small set of recognizable folders/files makes wrapping someone’s head around a project much easier than having them read several unrelated files and hoping they fit them together or worse, traversing a disorganized mess of files/folders.

What You Need To Know

Actually not much for this portion! A lot of what you pick up from this post applies to programming in general.

The General Layout

Most of my mongodb+express projects involve the following files/folders

  • Server Folder
    • Schemas
      • SomeSchema.js
      • AnotherSchema.js
      • Schemas.js
    • Routes
      • SomeSchemaRoutes.js
      • AnotherSchemaRoutes.js
      • Routes.js
    • Helpers
      • WhateverYouNeed.js
      • othergoodies.js
  • Files
    • server.js
    • cluster.js

Schemas

The Schema’s folder will hold all of our MongoDB schemas. Each file in this folder will describe a different schema in our database. In most cases, this suffices however in some situations where an object has many methods, I may even have a “SomeSchema” folder with a separate “SomeSchema.js” and a “SomeSchemaMethods.js” file, but more on that in the second post.

This allows us to have all of our schemas in one nice place. To tie them all together we will import each and every one of them into the “Schemas.js” file. This acts as our single access point for our schemas for the rest of our app. Ideally, this will only Routes.js, but in some rare cases, we may need to import a schema else where.

Routes

Routes will handle all of the routes of our app(big surprise huh?) So if we want to create, read, update or delete something, we do it here. Some nice benefits of this are that we can separate database logic and app logic. So if we wanted to implement an extra method from the server that doesn’t interact with the database, we can do it in a single location that is separated from the database logic. For instance, if you had a courtesy route from the app to check if a login token is still valid, you could implement that here.

Helpers

This is our “doesn’t fit neatly into either category” where I usually store my JWT encrypter/validator, validator functions and the like. This is also a good place to store our various middlewares. The important part is that we put all of these miscellaneous functions in one neat area instead of rewriting them all over the place.

Server.js/Cluster.js

This is where we tie it all together. In this set of files, we import all of our routes and various middlewares. After structuring everything in the way we did we can describe our server in one neat, clean line of code. This means the next guy who comes around will understand exactly what is going on as soon as they see it. There should be no need for them to look into any of the aforementioned folders unless they wanted to understand the specific implementation of the methods.

In the next post, I’ll be going into detail in how all of these ideas fit together in the code and what I’ve described looks like.