I grew up on "Algol" style languages like Java, C++, and ActionScript 3 where one of the first things you learn about is the concept of a class, a blueprint for an object. I guess I'm too young to remember a lisp world without Clojure so at first I was amazed that you could even have a programming language that didn't based its foundational architectural patterns around classes or object use classes! I just today was working on a project and found it refreshingly simple to just write some functions in a namespace so I could require and call them from another file. In this post we'll take a look at how to we import functions in a ClojureScript project using the build tool leiningen without classes or objects.
Let's suppose I have this basically blank project for an AWS lambda function written in ClojureScript using the cljs-lambda leiningen template (and chopping off some of the "work-magic" code).
In the above code we are declaring a namespace for this file, "basic-cljs-lambda.core", requiring a bunch of libraries, and then defining the lambda function with the name "cool-lambda-function". This function just returns a JSON object with some hardcoded values.
Create A Function Somewhere Else
Suppose you now want to create a helper function, something that does side effects, something that does some calculations on the object that was passed into the lambda function, some function that does whatever! To stay organized I'll create a folder and name it cute-little-utils, and inside of that I'll put a file called string-utils.cljs in which I'll add a function called derpify. This function will be super useful because it will take a string and add the string "DERP" to either side of it, with spaces in between.
Then you can simply load the namespace "as" an alias name and call the function in the code.
The problem with classes and object instantiation is that it encourages you as a developer to use mutable variables and local state freely which can quickly lead to a huge web of interconnected pieces that all modify each other's stuff to point where no one even know's what the heck changed what. In Clojure you can have your cake and eat it too- you are heavily encouraged to use the efficient built-in immutable collections yet you can use set! on mutable atoms if you really want to have mutable variables, but notice that we still don't need any class-based blueprints to do that. Playing the game of building a cute little army of classes that you spring to life mutate on the fly can be a fun way to personify programming, but when you want to get stuff done and end up with concise, maintainable code you should reach for Clojure.
The posts on this site are written and maintained by Jim Lynch. About Jim...
Want FREE access to
my daily stock tips
Sign up here:
- Triple Gainers
- Rippers N' Dippers
- Growingest Growers