The Dangers of Weak Typing

Most of you are probably familiar with the benefits of strongly-typed programming languages. They can greatly reduce the mistakes made during coding. However, after several years of web programming, I've come to realize that relying solely on strongly-typed languages is not enough.

Most of today's mainstream programming languages allow the implementation of strong typing through user-defined data types. However, many developers still predominantly use generic primitive data types, such as int, Guid, and `string. This can lead to mistakes and make maintenance more challenging.

To illustrate the maintenance challenge more concretely, let's consider the following function:

int GetGrade(Guid courseID, Guid userID, Guid termID)
{
    ...
}

This function retrieves the grade for a specific user. However, what if a different developer later changes the order of the parameters?

int GetGrade(Guid userID, Guid courseID, Guid termID)
{
    ...
}

All call sites would need to adjust the order of their arguments. Such changes are easy to overlook, and they can be challenging to spot during code reviews. You might not even realize the problem until the server is running.

In web programming, functions often have many parameters, and these kinds of mistakes occur frequently. It's crucial to leverage the compiler's validation capabilities in these situations.

Leading with Java in the OOP paradigm, there were suggestions to utilize domain-specific data types through domain modeling. For example, instead of using Guid, one might create and use a UserID` class. However, due to performance degradation related to object creation (and thus garbage collection), this approach has fallen out of favor.

Interestingly, in C++, objects can be created on the stack, which largely mitigates performance concerns. But considering that C++ is rarely used in the most problematic domain of web programming, this might seem like a moot point.

Fortunately, in the latest versions of C#, one can use record struct` to address these issues to some extent.

My company has recently begun to actively employ this technique, and I will introduce this method in a future post.