Sub topic 13
Designing packages well
This chapter assumes you can write a package specification and body, know the difference between public and private elements, and understand that package variables persist for a session. It turns those mechanics into design decisions: what to expose, what to hide, when state is worth having, and how to keep changes from rippling through your code.
Start from the interface, not the implementation
A package is a contract. Callers depend on the specification, and the body can change freely as long as the specification stays the same. Design the specification first, as if you were writing documentation for another developer.
Ask these questions before you add anything to a specification:
- Does a caller outside this package need it?
- Can I describe the package's purpose in one sentence?
- Would I be comfortable keeping this signature unchanged for years?
If the answer to the first question is "no," the item belongs in the body. You can move a private item into the specification later without breaking anyone. Removing a public item breaks every caller that uses it.
Keep packages cohesive
A cohesive package groups things that change for the same reason. emp_api (employee operations) is cohesive. A package named utils that holds date helpers, email routines and salary rules is not. Every change to any of those areas recompiles and possibly invalidates the whole package, and every caller depends on parts it never uses.
Signs a package needs splitting:
- Its name is vague (
utils,common,misc). - Its subprograms use unrelated tables and types.
- Different teams edit it for unrelated reasons.
- Its specification is hard to read in one screen or two.
Decide what goes in the specification
The specification holds the public interface. The body holds everything else.
| Item | Put in specification | Put in body |
|---|---|---|
| Subprograms callers invoke | Yes | Implementation only |
| Helper subprograms | No | Yes |
| Constants callers need (limits, status codes) | Yes | No |
| Constants used only internally | No | Yes |
| Named exceptions callers handle | Yes | Raise them here |
| Record and collection types used in parameters | Yes | No |
| Types used only inside the body | No | Yes |
| Variables | Almost never | Yes, if state is needed |
Avoid public variables
A variable declared in the specification can be read and written by any caller. You can no longer enforce rules on it, and you cannot change its type without breaking callers. Keep variables in the body and offer a getter and setter if callers need access:
CREATE OR REPLACE PACKAGE app_context_api AS
PROCEDURE set_tenant(p_tenant_id IN NUMBER);
FUNCTION get_tenant RETURN NUMBER;
END app_context_api;
/
CREATE OR REPLACE PACKAGE BODY app_context_api AS
g_tenant_id NUMBER;
PROCEDURE set_tenant(p_tenant_id IN NUMBER) IS
BEGIN
IF p_tenant_id IS NULL OR p_tenant_id <= 0 THEN
RAISE_APPLICATION_ERROR(-20010, 'Tenant id must be positive');
END IF;
g_tenant_id := p_tenant_id;
END set_tenant;
FUNCTION get_tenant RETURN NUMBER IS
BEGIN
RETURN g_tenant_id;
END get_tenant;
END app_context_api;
/The setter validates its input. A public variable could not do that. Constants are the exception: a public CONSTANT cannot be changed, so exposing it is safe.
Anchor types with %TYPE and %ROWTYPE
The earlier emp_api examples declare parameters as employees.employee_id%TYPE. This keeps the interface in step with the table. If the column grows from NUMBER(6) to NUMBER(10), the package follows. Note the cost: a table change that alters the column's definition can invalidate the package, which then recompiles on next use.
Layer your packages
Large systems usually split packages by responsibility. A common arrangement has three layers:
- An API package that other applications or modules call. It validates input and defines the transaction boundary.
- Business-logic packages that hold rules.
- Data-access packages that contain the SQL for one table or a small group of tables.
Each layer calls only the layer below it.
flowchart TDThe block above is not valid for the platform, so the diagram follows in the correct form here:
Layering limits how far a change spreads. If the table changes, only emp_dao needs editing. If a rule changes, callers of emp_api are unaffected.
Avoid circular dependencies between packages. Oracle can compile mutually dependent packages, but circular references make compile order fragile and invalidation unpredictable. If two packages need each other, extract the shared part into a third package that both call.
Be careful with package state
State is the feature that most often causes surprises. Package variables live for the session, which gives you caching and context, and also gives you hidden dependencies between calls.
Prefer stateless packages. A stateless package holds no variables in the body or specification, other than constants, so each call depends only on its arguments and the database. Stateless packages are easier to test, and they behave the same under connection pooling.
Use state deliberately when it earns its cost. A lookup cache is a reasonable use:
CREATE OR REPLACE PACKAGE dept_cache AS
FUNCTION name_of(p_department_id IN departments.department_id%TYPE)
RETURN departments.department_name%TYPE;
PROCEDURE reset;
END dept_cache;
/
CREATE OR REPLACE PACKAGE BODY dept_cache AS
TYPE t_names IS TABLE OF departments.department_name%TYPE
INDEX BY PLS_INTEGER;
g_names t_names;
FUNCTION name_of(p_department_id IN departments.department_id%TYPE)
RETURN departments.department_name%TYPE IS
l_name departments.department_name%TYPE;
BEGIN
IF g_names.EXISTS(p_department_id) THEN
RETURN g_names(p_department_id);
END IF;
SELECT department_name
INTO l_name
FROM departments
WHERE department_id = p_department_id;
g_names(p_department_id) := l_name;
RETURN l_name;
END name_of;
PROCEDURE reset IS
BEGIN
g_names.DELETE;
END reset;
END dept_cache;
/Risks of stateful packages
- Stale data. The cache in each session copies the table at the time of the first read. Another session can change the department name, and this session keeps the old value until it calls
reset. Cache only data that rarely changes, and provide a reset procedure. - Memory use. Package state is held in each session's memory (the PGA, or process global area). A collection that grows without bound multiplies across every connected session.
- Connection pools. A pooled connection carries state from one user's request to the next. Code that assumes "my variables are fresh" can see another request's leftovers. Reset or reinitialize state at the start of each request.
- Recompilation. When a stateful package is recompiled, sessions that already used it lose their state. The next call in such a session fails with
ORA-04068: existing state of packages has been discarded. A retry normally succeeds because the package state is rebuilt, but the failed call does not run. Compile stateful packages during quiet periods, and have clients retry on this error.
Keep the initialization section small
The initialization section runs once per session, on first reference to the package. Use it for cheap setup, such as setting defaults. Avoid work that can fail or take long, such as querying large tables, because an exception in the initialization section propagates to whichever caller happened to touch the package first. That makes the failure look unrelated to its cause. A lazy approach is usually better: load data on the first call that needs it, as dept_cache does.
Handle errors through the interface
Declare the exceptions callers should expect in the specification, bind them to an error number with PRAGMA EXCEPTION_INIT, and raise them from the body. Callers then write WHEN emp_api.e_raise_too_large instead of testing error numbers. Choose numbers in the -20000 to -20999 range and keep a record of which package owns which number so that two packages do not reuse one.
Do not catch WHEN OTHERS and swallow the error. If you must catch it, log it and re-raise with RAISE.
Use overloading and forward declarations with restraint
Overloading suits cases where the same operation applies to different datatypes, as in fmt.to_text. It does not suit cases where the overloads behave differently. Two issues to watch:
- Overloads that differ only in parameter names, or only in the datatypes within the same family (such as
NUMBERandPLS_INTEGERin some contexts), can lead to ambiguous calls or compile errors. Make the parameter datatypes clearly distinct. - Overloads that differ only in return type are not allowed.
Forward declarations are a fix for ordering. If you can reorder private subprograms so each is defined before it is used, do so and skip the declaration. Reserve forward declarations for true mutual recursion.
Choose AUTHID deliberately
The default is definer rights: the package's SQL runs with the owner's privileges. That suits an API package that gives controlled access to tables the callers cannot touch directly. Use AUTHID CURRENT_USER for utility packages that should act on the caller's own objects. Set the choice on purpose and write it in a comment, because changing it later changes what the package can see.
Protect callers from change
The body can be recompiled without invalidating the objects that call the package. Dependents are invalidated when the specification changes in a way that affects them. Recent Oracle versions track dependencies at a finer grain than the whole package, so adding a new subprogram does not always invalidate callers, but you should not rely on that. Treat the specification as stable:
- Add new subprograms rather than changing the signatures of existing ones.
- Give new parameters default values at the end of the parameter list.
- When you must break a signature, create a new subprogram, mark the old one as deprecated in a comment, and remove it after callers move.
You can check what depends on a package before you change its specification:
SELECT name, type
FROM user_dependencies
WHERE referenced_name = 'EMP_API'
AND referenced_type = 'PACKAGE'
ORDER BY type, name;A short design checklist
- State the package's purpose in one sentence.
- Write the specification first, with only what callers need.
- Expose constants and exceptions, not variables.
- Prefer stateless code. Document and bound any state.
- Keep the initialization section short and safe.
- Avoid circular dependencies between packages.
- Set
AUTHIDon purpose. - Treat the specification as a stable contract.
Exercise
A package report_cfg declares g_page_size PLS_INTEGER := 50; in its specification, and several programs assign to it. Name two problems with this design and describe a better one.
Show answer
Any caller can set the variable to an invalid value such as 0 or NULL, and the package cannot validate it. Changing the variable's name or type later breaks every caller. The value also lives only in the current session, so it can differ between pooled connections. A better design keeps g_page_size in the body and exposes set_page_size (which validates the value) and get_page_size. If the value never changes, declare it as a public constant instead.
Exercise
Users report ORA-04068: existing state of packages has been discarded right after you deployed a new version of the body of a package that holds a cache. Why does it happen, and how do you reduce the impact?
Show answer
Recompiling the body discards the package state held in sessions that had already used the package, so the first call in each such session fails with ORA-04068. The next call works because the state is rebuilt. To reduce the impact, deploy during quiet periods, have clients retry once on this error, and consider moving the state out of the package, or making it cheap to rebuild.