I'm new to programming and trying to understand why classes are considered useful when functions can contain other functions. Couldn't I organize a program with one larger function containing several smaller helper functions instead? What do classes provide that nested functions don't, and when would one approach be preferable to the other?
4 Answers
Functions and classes are both ways to organize code, and neither is automatically better. A function is usually best for packaging an operation: give it inputs and get a result or side effect. A class is useful when you want to group persistent state with the operations that work on that state. Functional programming often avoids classes entirely, while object-oriented programming uses them as a way to model related data and behavior.
Classes can make larger systems easier to navigate by giving related data and behavior a named home. They can support encapsulation, shared interfaces, and polymorphism, which are useful in areas such as GUI frameworks or systems with many interchangeable components. However, inheritance and elaborate class hierarchies can also make code harder to maintain, so using functions, modules, or simpler data types may be the better choice. The important skill is choosing an organization that keeps the program understandable.
A class can act like a reusable type. Instead of passing several related values—such as x, y, and z coordinates—through every function, you can group them into a Point object and pass that around. The object can also enforce rules when its data changes, which helps prevent invalid state and keeps bookkeeping in one place.
Nested functions are especially useful for small helpers and closures. A closure can remember variables from the surrounding scope, so it actually can represent state. In fact, a closure is often implemented internally as something similar to an object containing captured data and a function to call. The difference is mostly how the programmer expresses and organizes that state.
The practical distinction is that classes usually make the relationship between the data and its methods explicit, while closures can keep that relationship more local and lightweight.

You can achieve similar organization with structs, closures, or functions that receive and return records. Classes are one convenient tool, not the only possible design.