5 ms·
Values that get passed around together go together into a structure, making code that deals with them more succinct. The functions that care about that sort of
by jtolmar 9y ago
Values that get passed around together go together into a structure, making code that deals with them more succinct. The functions that care about that sort of structure go into a class, not because this is inherently better, but because following this convention solves the "where did I put that function?" problem for a wider variety of cases than most other conventions.
Values that are supposed to change at the same time (or care about each other, or would otherwise need to be in sync somehow) would normally have to be passed around together to maintain that property, but this can lead to errors because it's the sort of thing people forget. If you put them into a structure together then hide the ability to actually use them behind functions that maintain the property you want, you prevent that sort of error.
- zumu 9y ago> The functions that care about that sort of structure go into a class, not because this is inherently better but because following this convention solves the "where did I put that function?" So you attach functions that operate on a data structure to the data structure solely for organizational purposes? Seems almost identical to defining a record and module of functions that operate on said record. Except that in OO, by attaching the functions you create new copies of each function with a bound reference to the instance of data structure. Are there other advantages?
- jtolmar 9y ago> Seems almost identical to defining a record and module of functions that operate on said record. OO is mostly that plus the ability to forbid people from using the record without using the functions. > by attaching the functions you create new copies of each function with a bound reference to the instance of data structure. Yes, but the compiler won't actually copy the function, it'll implement it as something closer to the record plus modules approach (for example a record plus a pointer to the module). This might not be true if you're trying to use OO in a functional language.
- zumu 9y agoThanks for taking the time to give these detailed responses. One more question (restated from below): Coming from FP where immutability is sacrosanct, I often wind up writing classes that are largely immutable, which doesn't seem like correct OOP. Is there a proper way to marry immutable data structures with OO?
- jtolmar 9y agoThe object-oriented world has been moving towards more immutable and mostly-immutable classes. This is sometimes awkward with large classes, so people use the builder pattern to get around it. (It's a case of languages having not caught up with practices.)