When developing software you may encounter situations where the values that you want to store in a variable are not always the same kind each time thr

Search code, repositories, users, issues, pull requests...

submited by
Style Pass
2024-07-26 06:30:07

When developing software you may encounter situations where the values that you want to store in a variable are not always the same kind each time through. While you are usually not concerned about storing strings and numbers in the same spot, you may need to store one of a few related types depending on what that data is meant to represent at that moment.

For example, your application may have both a customer and a supplier definition that share only some of the same properties and you may need to perform a similar operation on both in a fashion that depends on the differences.

Typically, this is where you might choose to distribute those specialized implementations into the types themselves and expose them through common abstract methods or interfaces. However, this is only good practice when those types exist primarily for the purpose of the operation or it makes sense for the operation to appear as an intrinsic part of the type. If the types have a broader purpose, polluting them with methods like this can be undesirable.

The alternative is to make the same logic handle both types, and if you do this, at some point you will need to declare a parameter or variable that can contain either.

Leave a Comment