What are User-defined types?

1 minute read

User-defined types are a convenience.

People always quote the principles of Object-Oriented Programming as a reason for using classes - Obvious abstraction, free encapsulation, we can inherit all the goodness and, we get that sweet sweet runtime polymorphism.

But?

Abstraction is hard. Finding the right abstractions is hard. Implementing interactions between these abstractions is hard. Encapsulation is essential, but the level of encapsulation provided by object-oriented languages isn’t always needed. In many cases, you just need a C style struct and a utility file that has functions that manipulate this data. Forcing inheritance to get the benefits of it often doesn’t end well. It makes the code tightly coupled, hard to read/maintain, and I believe it’s commonly agreed upon at this point that deep inheritance is terrible and need to be avoided. Implementing interfaces and extending abstract datatypes is actually not too bad to get that sweet sweet runtime polymorphism.

In India, most devs learn object-oriented programming by writing Java code. And I don’t think it shapes intuition of types correctly. The problem with Java is, classes are forced. So, when designing a solution to a problem, you need to extract the entities that you want to model as classes and define how the instantiations of these classes(objects) interact. This pushes object-orientedness into design, and code is just implementation. But, people spend a lot of time writing programs that solve specific toy problems before they learn to design components of a fairly complex system. So, it is easy to stop seeing types for what they are and start seeing it as a language implication.

I think we should practice finding right abstractions, deciding on the right amount of encapsulation, and learn how to simplify object interactions. Only after that, User-defined types are truly a convenience, and they become a tool to keep the code maintainable and extensible.