I’m a mid level Swift developer and I’ve only ever worked with the Object Orientated Programming paradigm.
I’ve heard about functional programming and I tried Googling what it is, but I couldn’t understand the resources that explained it. Also, reading functional code is even more confusing.
So I was hoping that someone who understood it could break it down in incredibly basic and simple terms, and the benefits/drawbacks that it has compared to OOP.
In: Engineering
Functional programming deals with functions, that is programming snippets that are basically “given this, do that and return the results”
I think I should use an example: you have a program that draws a bouncing ball.
In OOP, you would have a Ball object, and the program would then operate on it – change its properties like position, ask it to draw itself and such.
In functional programming, you would have a bunch of functions, probably running in a loop, like drawBall, or moveBall, and some variables to track its position. If those are pure functions, they wouldn’t even affect the state directly – for example, your moveBall function would return new coordinates of the ball and then your program would set the state to the new position.
If you then would want another ball, you would add more variables (maybe an array), adjust the functions to take an index of the ball to move or draw, and if one day you would like to have other things like cubes moving around, you would have to accommodate all that.
With OOP, you would just add more Ball objects, and you could also create new Cube objects, and then have them both inherit from a more general object.
At that point your moving and drawing code wouldn’t need to know anything about the balls and the cubes except that they all have positions and can be drawn.
Latest Answers