coderefinery / modular-code-development

Modular code development lesson.
Creative Commons Attribution 4.0 International
3 stars 4 forks source link

Tone down emphasis on pure, functional programming #21

Open ashwinvis opened 4 years ago

ashwinvis commented 4 years ago

I find two issues with this lesson:

  1. I think while this lesson is well-intended, it delivers the message that pure, functional programming is the only right way to do programming. There is no mention of other paradigms. For instance, object-oriented programming, when done right, makes code reuse easier through inheritance.

  2. I agree that pure functions and functional programming paradigm is usually desirable for a lot of use cases which are fast to compute. However for computational sciences (for example, computational fluid dynamics) there are two recurring themes:

    • array operations: Array creation is expensive.
    • states: Arrays have states. These are mutable and evolve over time

Take an example of an imaginary function foo which updates an array every time step.

# pure function
def update(old_array):
    new_array = foo(old_array)
    return new_array

# impure function
def update(old_array):
    old_array[:] = foo(old_array)

# impure method, but states are tracked as attributes of a class
class State:
    def __init__(self, N):
        self.array = np.zeros(N)

    def update(self):
        self.array[:] = foo(self.array)

Which is better?

In other languages such as Fortran, modules are very often used as a container for arrays. This IMHO mimics classes in Python and structs or classes in C++. To quote the Zen of Python:

Special cases aren't special enough to break the rules. Although practicality beats purity.

bast commented 4 years ago

Thanks for the good suggestion! I agree that the presentation should be more balanced. There are indeed situations where mutable data structures are preferred. I will teach this lesson in a week and will try to adjust it until then.

My goal with this lesson was not to say that functional style is always good but rather to say that object oriented programming is not always the best solution. But sometimes it is. I agree that the text needs to be more balanced for this.

ashwinvis commented 4 years ago

Okay, so we are on the same page :)

I agree it is good practice to resort to functional style when it leads to clean codes. It is hard to define a rule for when to use it or not.