Writing

Gentle Introduction to Functional Programming

Originally published here on behalf of LaunchCode a non-profit dedicated to helping people land their first job in tech through training and apprenticeships.  I wrote this article in collaboration with my colleagues Dave Morse and Haley Shoaf. Credit also to Tianna Berry-Jones for her help with content and editing.

In your coding journey, you may have heard rumblings about Functional Languages. St. Louis hosts the annual Strange Loop conference, a prestigious tech conference focused specifically on functional languages. While functional programming is not particularly marketable, and shouldn’t be your first language, it’s still pretty interesting. Understanding the concepts behind functional programming languages can help your overall programmatic understanding. This is meant to be a very basic 
introduction to some of the ideas behind functional programming and why you may find them beneficial.

Functional vs Object-Oriented


The best way to describe functional programming is to contrast it with more traditional object-oriented programming. Often thought of as a more esoteric programming paradigm, functional programming languages such as Haskell and Clojure are distinct from more traditional object-oriented languages such as Ruby, Python, C++ and Java. While there are some “functional-only” languages, most modern object-oriented languages support both functional and object-oriented styles.

In declarative (functional) programming, functions can be treated as first class objects. This means that functions can be passed around as values, functions can pass into other functions as parameters, and one function can return another function. Functions are composed of other functions so that you can transform values without describing the internal steps involved in transforming the values. Contrast this with imperative (object-oriented) programming, where you describe the step-by-step processes needed to modify variables and get your answer.

Below is a simple example of using JavaScript in an object-oriented imperative style and then in a functional declarative style.

//Problem -- I want to take a list of "User Objects"
  and turn it into a simple list of first names
//Sample data
var people =
[{ firstName: "Charles",
   lastName: "Xavier",
   superheroName: "Professor X"
 },
 { firstName: "Ororo",
   lastName: "Monroe",
   superheroName: "Storm"
 }];

In the above object-oriented example, we have to tell the computer to loop over an array, index into the array, get the first name, add that name on to another array, and repeat until there are no more people left. Finally, we can return the name array that has been mutated to have the values we want.

In contrast, here is a solution in the functional style:

//The Functional Approach
function getFirstNames(people) {
  //return a transformation of the people list
  return people.map(getFirstName)
}

function getFirstName(person) {
  //another function that takes a person and returns their name
  return person.firstName;
}

Here in the functional solution, we are saying return the same list of people, but only after transforming it with the function “getFirstName.” The “getFirstName” function just takes a person and returns their firstName. This example is using what is known as a map, a staple of functional programming. The map function takes another function as an argument and applies that function to each element in a list. It then returns the same list of elements, however each element has been transformed by the function we passed to map. Here, we just transformed a list of people into a list of those peoples’ firstNames. While this may seem a little weird and confusing at first, many people find this method much more expressive and clear than an object-oriented approach. However, it is important to note that both approaches return the same answer. One is not necessarily better than the other, they are simply two different ways to approach the problem.

Strengths


One of the main strengths of functional programming is that it makes code easier to reason about. One way this happens is that functional programming languages either encourage or enforce ”pure functions”. This just means that a function will not have any side effects and will not modify an outside object or change state. With pure functions, given the same input you will get the same output every time. This is not always true for object-oriented style functions where your object might be holding on to some state that could change the output of a function. Once you get the hang of working with pure functions, it can become much simpler and easier to reason. Your programs can become more straightforward, understandable, easier to test, and easier to maintain.

One great example of how functional concepts can be used beneficially is seen in the React framework for front-end JavaScript development. Making complex front-end JavaScript applications is difficult. These applications often have a tendency to turn into giant balls of spaghetti code over time. This looks exactly like it sounds — a tangled mess of inter-dependant code. If each function can mutate the global state being used by other functions, it is hard to reason about what each function does. To understand any specific piece of code, you would need to know what every other piece of the code does. If this sounds difficult, it’s because it is!

In an attempt to fix this, React.js applied a functional paradigm to this problem, specifically the idea of one-way data flow and pure functions. As opposed to normal two-way data flow between JavaScript and all of its inter-dependencies, React makes you manage the state of your application in once place. Then, you can define render functions that transform the state into HTML. When a user interacts with your application, those events move in a well defined loop that modifies the one global state. At that point the render function will rerun and output new HTML, leading to very predictable applications. React is known for being fast, mostly due to optimizations made possible by this predictability. This functional-style framework helped developers clean up their JavaScript and reduce many of its inefficiencies. It is also a great example of how functional programming ideas can help us write better programs in any language.

Weaknesses


Functional programming is not a programming cure-all. Working with functional languages can sometimes be more complicated, especially when programmers are used to object-oriented or procedural programming. It can be difficult to understand a complicated functional program that uses many higher order functions if you aren’t very familiar with those concepts. Functional languages do not work well for certain types of projects, such as writing device drivers or complex video games. A video game, for example, needs to track the state of an entire game world as a player progresses. Because there is so much state (player health, obstacles, character progression, etc.), it is easier to model this using objects, which hold state, instead of pure functions which can not hold information.

Finally, there is just not as much work for functional programmers. There are few to no entry-level functional programming jobs, and object-oriented programming skills are still required in almost any job you find. There can be a lot of inertia in programming, and the cultural resistance to buzzwords in the coding community has made many programmers wary of switching away from the object-oriented programming paradigm. In the past, functional programmers have garnered a reputation for being aloof — often referring to underlying mathematical concepts that are less accessible to the average developer. This attitude has been changing recently and there have been efforts within the functional programming community to gain more widespread adoption. For now, though, object-oriented is the dominant paradigm in the industry.

Takeaway

Functional programming should be learned in the same spirit as reading the Iliad — not because it is an immediately marketable skill, but because it is a useful way to think about the world. It will make you a more efficient programmer and give you a greater toolbox from which to draw on when solving problems. Understanding functional concepts does not mean you need to totally eschew object-oriented ones. The best developers know when it is appropriate to apply functional concepts and when to stick to good old OO programming. A good understanding of functional programming will give you deeper knowledge of coding concepts overall.

If you want to learn more, this medium article goes into a lot more depth about many functional programming concepts that we just touched on above. If you are interested in learning a functional language, first make sure you want to dedicate significant time to learning an entirely new language. If you are sure, Elm is a good language to start with. It is a newish language that targets front-end development and is designed to be easy to learn for people unfamiliar with functional programming.

By Eliot Piering, Haley Shoaf & Dave Morse
of the LaunchCode Tech Team
Read More...

How to Have a Successful Project

Originally published here on behalf of LaunchCode a non-profit dedicated to helping people land their first job in tech through training and apprenticeships. This article was written specifically for new developers working on their first solo project, one of the requirements for getting a LaunchCode apprenticeship. Credit to Tianna Berry-Jones for her help with content and editing.

Tips For Completing Your First Project 


To land a technical job, you should first complete a decent sized programming project to serve as tangible proof that you have the required skills. Unfortunately, this can be difficult and where great candidates often get stuck. Even after studying alone online or in a classroom environment, building your first programming project start to finish on your own can be daunting. It can feel like going from swimming in the shallow end with arm floaties to suddenly being dropped straight into the deep end with nothing but your swimsuit. It’s easy to find yourself drowning in a pool of programming tools, frameworks, databases, servers and options. This post will not offer any specific technical advice, but rather give you a framework for approaching the project along with some guidance and tips to keep you going until you’re swimming like a pro.

The Big Idea


The first step to any project is figuring out what you want to build. Pick something that interests you. You are going to be spending a LOT of time working on your project, so make it something you find engaging. A good way to generate ideas for this is to think of some piece of software that you want but doesn’t yet exist. Alternatively, you could think of something that exists but that you wish worked a little differently, or pick some piece of software that you use all the time and build your own version. It doesn’t need to be the most original idea ever, but it should be at least be interesting to you.

Making sure your project is something on which you will learn useful skills that can be applied to a job is key. You may be interested in building a video game in Unity, but if your goal is to get a job as a back-end software developer, those skills won’t translate well. Building a game in Unity will help you learn Unity (and maybe some C#), but ultimately it won’t help you become a better back-end developer. An employer will not see that project as proof that you’ll be able to contribute as a back-end dev. Identify the kind of job you want and what skills you think you need for that job. Try looking at job postings for open positions to get an idea of what skills are required if your are unsure.

The point of your project is to learn how to build something, get exposure to what professionals are doing and demonstrate that you can do the work.

Avoid picking something overly ambitious. Nobody expects a first programming project to disrupt an industry or be an amazing, original piece of new software. It is most important that it’s something that you can actually build. For example, a mobile app that automatically tracks all of a user’s food intake and gives feedback on the nutritional content of it would be AMAZING. But, the technology to automatically track food eaten without any user input just doesn’t yet exist. A more realistic project would be to build an app where the user manually inputs their daily meals and then displays that food’s nutritional content. Make sure that you are trying to build something you’ll actually be able to complete. Don’t worry if your project isn’t super cool and fancy, that’s not the point. The point of your project is to learn how to build something, get exposure to what professionals are doing and demonstrate that you can do the work.

Pick Your Stack


There are many different decisions to make when choosing which tools to use in building a project. These will vary depending on the needs of each project and your existing skillset. Still, there are some common sense advice to help you make an appropriate choice.

Try to pick something you already have some familiarity with. If you already know Java or Python, it wouldn’t be the best use of your time to go learn Ruby on Rails for your first project. Instead, pick a framework like Django (for Python) or Spring (for Java). You already have plenty to learn — no need to make it harder by having to learn an entirely new language.

Once you have done some research and picked something you are comfortable with, stick with it. You will learn about many competing frameworks or databases and how each one is so much better than its competitor. It will be tempting to try all the things. Don’t. You have a lifetime to try them all. For your first project, it’s better to minimize the amount of new stuff you have to learn. If you spend all your time jumping around, it will be very difficult to make any progress.

Finally, when you do decide on what stack to use, set aside some time to learn it’s set of tools. Do a simple tutorial that takes you through the basics. Set up a dummy “Hello, World” app. You don’t have to spend months researching and reading every book on the subject, but take a little bit of time to familiarize yourself with the tools you will be using and how the pieces fit together before diving in head first. 


One Step At A Time


Ok, you’ve picked an idea and a stack. Now you’re ready to start building! There will be a natural tendency to build your project feature by feature, but it’s more efficient to build it piece by piece (as exemplified in the Agile Process). This may sound like a distinction without a difference, but is actually the most important piece of advice here. To really explain it, we need an example.

Let’s say you are building a server side web app. Your first feature is user logins. It sounds pretty straightforward — basically every web app has this — how hard could it be? Your first step is to build a sign_in page where you can accept a username and password to login. While creating your sign_in page and adding two text fields on the screen for username and password, you realize that you actually need a page to create a new user first. There are submit buttons, form data to send, server side  data to parse, passwords to encrypt and data that needs to be stored.  This goes on and on, and you still haven’t really made direct progress towards the original goal of signing in a user. Experienced engineers often have problems with this, it is an art, and one that will take years of practice to master. Here are some tips to help get you get a jump on it.

First, figure out which subtasks you absolutely need and which can be tabled to work on at a later date. For example, a login page also needs to have a way to create a new account in some way. You may not, however, need a place where users can edit their account and upload a nice photo. For your first project, remember YAGNI (You Ain’t Gonna Need It). Professional programmers use this to help organize work on their own features when it becomes tempting to over engineer a solution or to guess at future requirements of the feature. Don’t build things until you know you need them. It’s a simple way to keep your code simple and prevent stalling.

Second, when you’re working on something you know you do need, work towards the simplest implementation. There will be a thousand ways to complete your task, some more complete or better than others. It can be hard to proceed knowing there might be a better way to do things, but don’t get stuck trying to build the best thing ever. In order to make progress, you just need to build something. Build the simplest thing you can that will still accomplish what you need. You can always come back and improve your app later, but for now, create your MVP (minimal viable product). This is a term startups use to talk about the simplest version of an application fit for release. When you don’t have a lot of resources or money, it’s important to release your idea quickly so you can validate it. Create the simplest version of your application that you feel comfortable showing to potential employers.

Finally, remember to take a step back from your work. It is easy (and sometimes necessary) to get lost in the weeds, but it is also important to see the bigger picture. This means actually taking some time to plan out your work. You may have 4-5 features that you consider part of your MVP, but the list of subtasks to complete each feature is always going to grow and change. Try to take some time to write down the subtasks that you need to work on and check them off as you complete them. Keeping a running list of these things will help keep you on track with the larger project goal and help prevent the urge to drop your work (and context on the current problem) to add another feature. Instead, add the new problem to your running list and come back to it later.

The Take-Away


Take all advice with a grain of salt. There are no hard and fast rules to follow, no guaranteed process templates — consider the above general guidelines. These are pieces of advice learned the hard way shared to lessen a bit of your struggle. It is still going to take hours of Googling, countless tutorials, and many many moments where you hit a brick wall and feel like you can’t proceed. But don’t be intimidated. Take a break, sleep on the problem, and get back at it. Less smart and talented people than you have done this. Put in the hard work, time and perseverance, and you can do it too. It is not impossible even when it feels like it is. 

Good luck!
Read More...