DEV Community

loading...
Cover image for Mixing FP and OOP

Mixing FP and OOP

michaelcurrin profile image Mike ・2 min read

Rather than going for Functional Programming or Object-Orientated Programming exclusively, you can go for a mixed approach, at in languages that support both such as JavaScript or Python.

For example, you can still use classes and then pass a class instance to your function.

Below we have a simplified code example. There is a generic function which accepts a dictionary / associative array, or an object instance.

function getAge(obj) {
  return obj.age
}

foo = new Car(name="Toyota", age=20)
getAge(foo)
// 20

bazz = { name: "Monster Truck", age: 5 }

cars = [foo, bar, bazz]
ages = cars.map(getAge)
// [ 20, 10, 5 ]
Enter fullscreen mode Exit fullscreen mode

The function doesn't care what type class is as long as it has the expected field. And you could use a type or interface in TypeScript to enforce this at compile time.

Maybe you can move all your methods out to functions in a module. Though if you end up just using your class to hold data and not have any methods, then consider another object type that is more suitable.

Like a dictionary / associative array. You can use types in TypeScript or Python (using Mypy) to enforce this. I have instructions for how to apply Mypy to your Python project here.

In Python you can use a namedtuple, which is immutable and let's you use the class-style syntax of getting attributes instead of using a string key.

Based on example. See also namedtuple in PY3 docs.

import collections


Person = collections.namedtuple('Person', 'name age gender')

bob = Person(name='Bob', age=30, gender='male')
bob.gender
# 'male'
Enter fullscreen mode Exit fullscreen mode

Or from Python 3.7, use a dataclass. This will not enforce the types - you'll still need Mypy to check that.

from dataclasses import dataclass

@dataclass
class Point:
     x: int
     y: int


p = Point(1, 2)
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide