As programmers, we look for patterns. And when we find them, we refactor them into reusable code. Keep it DRY: Don't Repeat Yourself. PeopleCode offers two reusable code containers:
- Function Libraries
- Application Classes
And this brings us to the great debate. Which is better? Object-oriented App Classes or procedure-based Function Libraries? I often ask my students this question. And if they prefer one over the other, why? Let's review the benefits of each:
Function Library:
- Stateless
- Simple
- Must be declared
Application Class:
- Stateful
- Dynamic execution
There are other differences, but they are irrelevant for this comparison. For example, Application Classes have inheritance (some would say inheritance is NOT a benefit). The value of inheritance is reuse, but then a function can call a function, which is also reuse.
When asking students about their preference, here are a few of my favorite answers:
- Choose App Classes because they are new.
- Choose App Classes because they are object-oriented.
- Choose App Classes because we are supposed to.
- Choose App Classes because everyone is doing it.
- Choose Function Libraries because they work!
One of the most valuable features of App Classes is dynamic PeopleCode. Unlike Function Libraries, App Classes do not have to be imported/declared before use. This is how every PeopleTools framework works. As a developer, we create an App Class and register it with the framework. At runtime, the framework reads the metadata and invokes the App Class. A framework such as AWE, for example, knows nothing about my custom App Class. But it invokes my code nevertheless through functions such as CreateObject, ObjectDoMethod, ObjectGetProperty, and ObjectSetProperty.
Which one do I choose? Here are my decision criteria:
- If I need dynamic PeopleCode, meaning no declaration, then the only solution is an App Class. Another way to think about it is if I'm writing code that invokes another code block and I don't know that code block at design time, but will fetch the name from the database, then I have to use an App Class.
- If I'm writing code to plug into another framework, such as Event Mapping or Integration Broker, I will use an App Class.
- If I want testable code to test through PSUnit, I will create an App Class (because PSUnit is a framework that will invoke dynamic code).
- If I need to maintain state between method invocations, I'll choose an App Class.
- Otherwise, I choose a Function Library.
Which do you prefer and why? What are other benefits of one over the other? Leave a comment to let us know what you think!
At JSMpros, we recognize the value of Application Classes and offer a two-day course dedicated to teaching object-oriented best practices. In fact, our next session starts on August 9, 2021. Register now!