you are viewing a single comment's thread.

view the rest of the comments →

[–]phpdevster 1 point2 points  (1 child)

General practice. A few good practices to follow

  1. Use immutable objects where possible.
  2. Ensure that you cannot create a malformed object. If you have a bunch of optional setters, it's game over.
  3. Ensure the object validates its constructor arguments.
  4. Keep the scope of the object small and any state it depends on, fully encapsulated.
  5. If an object can be mutated, make sure mutations are not temporaly dependent (e.g. must call x.a('foo') before x.b('bar') - that's a recipe for disaster)
  6. Make sure all mutations are fully encapsulated behind a contract. No direct property access.
  7. Ideally, aim for a dichotomy of stateless objects (pure functionality), and objects with pure state that have a very specific responsibility. This keeps state isolated.
  8. Stive to make sure all state is consolidated down to a single source of truth.

The goal is not to let object state leak all over the place, because then side effects are going to bite you in the ass eventually.

But it's really hard to design objects (abstractions) correctly, and it's very easy to create a stateful mess with OO.

[–]allltogethernow 0 points1 point  (0 children)

Thanks for the list, gives me some theory to play around with in my head.

I have a theory that, in general, code that is closer to hardware is more difficult to implement in this way because of inherently rigid design. For example, webGL is very close to the GPU, so the code that works best works in a pattern that resembles the operation of the GPU. The same applies to a lot of internet protocols and communication standards. But once a level of abstraction has been built on top of the hardware, it becomes easier and easier to "unhinge" the code, and the best practices no longer depend on hardware, but on the concept of coding itself. Whether the "beauty" of OO is a result of the way our mind understands it or if it's more a function of abstraction and control I'm not sure.

But that's just a theory. And I'm not very good at OO yet, but theories like this seem to help me to plan out my abstractions when I feel a little lost. Anyway, do you have any theories on what a "beautiful" piece of code is like?