mardi 4 juin 2019

When is it a good idea to define a static ruby class?

Are there some governing rules around when it makes sense to define a static class as opposed to a class that is instantiated?

Still puzzling over idiomatic ruby initialization vs static class definition.

From what I've found.

Static classes seem very effective.

  1. ruby is both a functional and object orientated language. it’s very possible to write both styles. a functional style in super useful for ‘functional’ things. some pieces of our our code base are static, others are instantiated.
  2. i regularly observe classes going from static to instantiated and then very quickly bloating. “now we have all this stuff.. why not do more.“. static classes have a natural tendency to taking on multiple responsibilities.
  3. when a class transitions from static to instantiated we arrive at less unit testing confidence, given things at run time might change in regards to memory allocation / assignment (as in, someone could accidentally get in between instantiation and call).
  4. static classes are easier to read because we don’t have to juggle potential state change considerations. less mutation = less complexity.

For me. The big issues are:

  1. Classes doing more than one thing.
  2. Instability in patterns across large old ruby code bases.

To address these 2 concerns, I’m thinking a static approach (where possible) seems to put a healthy amount of pressure on the code to adhere to SOLID principles.

Static

Serializer.transform(fruit:)

Instantiated

Serializer.new(fruit:).transform

What drives you to go static in ruby?

Aucun commentaire:

Enregistrer un commentaire