Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Implementing OOP inheritance in T-SQL (not an O/R question)

$
0
0

Is it possible to cleanly obtain the inheritance benefit of object-oriented programming in T-SQL? This is not about O/R mapping, which has been discussed to death all over the web, but rather specifically about implementing a form of inheritance in T-SQL.

Here’s why I would ask such an insane question: I maintain a large body of existing T-SQL that implements logic that has to be tightly tied to the database. It’s not heavily declarative (i.e., does not rely heavily on large monolithic SQL statements and set manipulations), because the operations that have to be carried out are by their nature sequential. (And imperative code can be tested in bite-size pieces, whereas huge, tight, brittle declarative SQL is difficult to maintain.) And I can’t rewrite it.

I’m now faced with the prospect of implementing new functionality, which will have the effect of introducing slight variations across the current functionality.  An obvious way to implement this would be with tests and branches in every place where the functionality has to vary. This would spread the new functionality across the existing code in a rather unstructured way, making maintenance difficult. At the other extreme, I could clone the entire codebase, and make the alterations in the cloned code for the new functionality. At run-time, you would call into the correct code.  This would cause incredible code bloat and the attendant maintenance headaches.

Inheritance and virtual functions would solve this nicely: the common code would be placed in one class, and the parts that vary in two other separate classes.  Alas, T-SQL does not implement inheritance.

There is a third way: implement virtual functions by hand in T-SQL.  At virtual function call sites, you would simply employ a lookup to determine the correct virtual function, and then call it dynamically. This could be easily expanded to handle a third set of logic and so on. It would only require modifying the entire codebase once, to insert the virtual function call points. The vtable of virtual functions could be stored as a table in SQL Server. But this sounds like an awful thing to do to future maintainers.

Has anyone else faced this situation, and how did you address it?  Does anyone know of any other approach that would mimic inheritance in T-SQL and/or avoid the uglinesses of the above?  Thanks.



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>