Sub topic 5
Public versus private: what the specification hides
This chapter assumes you can write a package specification and body, as covered in the earlier chapters. It also assumes you know basic PL/SQL exception handling. Here you will learn exactly where the line between public and private falls, how the compiler enforces it, and how to use it to control what callers can do.
The one rule that decides visibility
Whether a package element is public or private depends on one question: is it declared in the specification?
- Declared in the specification: public. Any code with
EXECUTEprivilege on the package can reference it aspackage_name.element_name. Code inside the body can also reference it without a prefix. - Declared only in the body: private. Only code inside that package body can see it.
There is no keyword for either state. You never write PUBLIC or PRIVATE. The specification acts as a filter, and anything that does not appear in it stays hidden.
| Element | In the specification | Only in the body |
|---|---|---|
| Procedures and functions | Callable from outside | Callable only from the body |
| Constants and variables | Readable and, for variables, writable by anyone | Accessible only to the body |
| Types and subtypes | Usable in callers' declarations | Usable only in the body |
| Exceptions | Can be caught by name outside | Cannot be named outside |
| Cursors | Usable by callers | Usable only in the body |
Replace the empty block above with the diagram below. It shows the same boundary.
A private subprogram in practice
Recall the emp_api package. Its specification declares get_salary, raise_salary, a constant and an exception. The body also defines is_valid_pct, which the specification does not mention.
CREATE OR REPLACE PACKAGE BODY emp_api AS
-- Private: not declared in the specification, so callers cannot see it.
FUNCTION is_valid_pct(p_pct IN NUMBER) RETURN BOOLEAN IS
BEGIN
RETURN p_pct > 0 AND p_pct <= c_max_raise_pct;
END is_valid_pct;
FUNCTION get_salary(p_employee_id IN employees.employee_id%TYPE)
RETURN employees.salary%TYPE IS
l_salary employees.salary%TYPE;
BEGIN
SELECT salary INTO l_salary
FROM employees
WHERE employee_id = p_employee_id;
RETURN l_salary;
END get_salary;
PROCEDURE raise_salary(
p_employee_id IN employees.employee_id%TYPE,
p_pct IN NUMBER) IS
BEGIN
IF NOT is_valid_pct(p_pct) THEN
RAISE e_raise_too_large;
END IF;
UPDATE employees
SET salary = salary * (1 + p_pct / 100)
WHERE employee_id = p_employee_id;
END raise_salary;
END emp_api;
/Inside the body, raise_salary calls is_valid_pct and reads c_max_raise_pct with no package prefix. Both are in scope. From outside, the story changes:
DECLARE
l_ok BOOLEAN;
BEGIN
l_ok := emp_api.is_valid_pct(10);
END;
/The block fails at compile time, before it runs:
PLS-00302: component 'IS_VALID_PCT' must be declaredTo a caller, a private element does not exist. The error is the same one you would get for a misspelled name, and it carries no hint that the element is merely hidden. That is a useful property. You can rename, change or delete is_valid_pct without checking who might be using it, because nobody outside the body can be.
Hiding state behind accessors
The strongest use of privacy is protecting variables. A variable in the specification can be read and assigned by any caller, which means you cannot enforce rules about its value. Compare these two designs.
CREATE OR REPLACE PACKAGE log_settings_open AS
g_level VARCHAR2(10) := 'INFO'; -- anyone can assign anything
END log_settings_open;
/With this package, a caller can run log_settings_open.g_level := 'banana'; and nothing stops it. Now move the variable into the body and expose controlled access:
CREATE OR REPLACE PACKAGE log_settings AS
PROCEDURE set_level(p_level IN VARCHAR2);
FUNCTION get_level RETURN VARCHAR2;
END log_settings;
/
CREATE OR REPLACE PACKAGE BODY log_settings AS
-- Private state and private rule.
g_level VARCHAR2(10) := 'INFO';
FUNCTION is_known_level(p_level IN VARCHAR2) RETURN BOOLEAN IS
BEGIN
RETURN UPPER(p_level) IN ('DEBUG', 'INFO', 'WARN', 'ERROR');
END is_known_level;
PROCEDURE set_level(p_level IN VARCHAR2) IS
BEGIN
IF NOT is_known_level(p_level) THEN
RAISE_APPLICATION_ERROR(-20002, 'Unknown log level: ' || p_level);
END IF;
g_level := UPPER(p_level);
END set_level;
FUNCTION get_level RETURN VARCHAR2 IS
BEGIN
RETURN g_level;
END get_level;
END log_settings;
/The only way to change g_level is set_level, and set_level validates its input. This pattern is often called encapsulation. The cost is two small subprograms. The benefit is that the invariant (the level is always one of four values) holds for every caller, now and in the future.
BEGIN
log_settings.set_level('debug');
DBMS_OUTPUT.PUT_LINE(log_settings.get_level); -- DEBUG
log_settings.set_level('banana'); -- raises ORA-20002
END;
/Because the variable lives in the body, it also lives for the session, as the later chapter on package state explains. Privacy controls who can touch the value. It does not change how long the value lasts.
The specification is a contract the body must meet
Every subprogram in the specification must have a matching definition in the body. The headers must agree: same name, same parameter names, same modes, same datatypes, same return type. If one is missing, compiling the body fails:
PLS-00323: subprogram or cursor 'RAISE_SALARY' is declared in a package specification and must be defined in the package bodyIf the headers differ, for example p_pct IN NUMBER in the specification and p_percent IN NUMBER in the body, the body does not match, and you get an error such as PLS-00328 or PLS-00323 pointing at the mismatched subprogram.
The reverse is not an error. A subprogram defined in the body but absent from the specification simply becomes private. That is the intended behavior, but it creates a common mistake: you add a new function to the body, forget to add it to the specification, and then get PLS-00302 from the calling code. The body compiled cleanly because, to the compiler, you wrote a private helper.
Private elements and ordering
Inside a body, a name must be declared before it is used. Private subprograms therefore usually appear near the top of the body, before the public subprograms that call them. This is why is_valid_pct came first in emp_api. When two private subprograms need to call each other, order alone cannot solve it, and you use a forward declaration. The next chapter covers that.
Public elements are already declared by the specification, so the body can use them anywhere.
What outsiders can and cannot see
Hiding is enforced by the compiler, not by access to source text. Some details to keep straight:
DESCRIBE emp_apiin SQL*Plus or SQLcl lists only specification elements. Private elements do not appear.- The data dictionary views
USER_SOURCE,ALL_SOURCEandDBA_SOURCEstore the specification under typePACKAGEand the body under typePACKAGE BODY. A user who can see source for the body can read the private code. GrantingEXECUTEon a package does not by itself grant visibility of the body's source, but a privileged user can read it. - If you need to hide the implementation text itself, the
wraputility obfuscates the body. Privacy and wrapping are separate tools. Wrapping hides source, and privacy hides names from the compiler. - Public functions can be called from SQL, subject to the usual rules about side effects. Private functions can never appear in a SQL statement, even one run inside the body, because SQL statements are parsed by the SQL engine, which sees only the public interface of a package.
That last point catches people. Suppose emp_api had a private function bonus_for and you wrote this inside the body:
SELECT bonus_for(employee_id) INTO l_bonus FROM employees WHERE employee_id = p_id;The statement fails with PLS-00231: function 'BONUS_FOR' may not be used in SQL. Static SQL inside a package body can call package functions only if they are in the specification. If you want a function to be usable in a query, you must make it public.
Public variables: a warning
A public variable is shared mutable state with no gatekeeper. Any code can change it, and the compiler will not tell you who did. Two situations make this worse. Code you did not write may assign the variable, and a value left over from an earlier call in the same session may surprise a later caller.
A reasonable rule of thumb:
- Constants, types and exceptions that callers need to refer to by name go in the specification.
- Variables go in the body, with get and set subprograms where callers need access.
- Helper subprograms go in the body unless a caller has a real need for them.
Choosing what to expose
When you decide where an element belongs, ask these questions in order:
- Do callers need to name it, for example to catch an exception, pass a typed parameter or compare against a constant? If yes, it is public.
- Do callers need to invoke it? If yes, it is public.
- Does it enforce a rule or hold state? If yes, keep it private and expose the smallest interface that lets callers do their job.
- Otherwise, it is a helper, so keep it private.
A small public surface is easier to document, test and change. It is also easier for dependent objects, because, as a later chapter shows, a change to the specification forces dependent code to recompile, while a change to a private part of the body does not.
Exercise
A colleague adds a function format_name to the body of package hr_util, compiles the body with no errors, and then a calling block fails with PLS-00302: component 'FORMAT_NAME' must be declared. What happened, and what are two ways to fix it?
Show answer
The body compiled because a subprogram that appears only in the body is simply private, so the compiler found nothing wrong. The calling block cannot see it because the specification does not declare it. Fix 1: add the function header to the specification (with a matching signature), then recompile the specification and the body, which makes format_name public. Fix 2: if only code inside hr_util should use it, leave it private and move the caller's logic into a public subprogram of the package that calls format_name.
Exercise
A package specification contains g_max_retries PLS_INTEGER := 3;. Why might this be a design problem, and how would you restructure it so that no caller can set the value to a negative number?
Show answer
Any caller can assign to a public variable, so the package cannot guarantee that the value stays valid. To fix it, remove the variable from the specification and declare it in the body. Add a public FUNCTION get_max_retries RETURN PLS_INTEGER and a public PROCEDURE set_max_retries(p_value IN PLS_INTEGER) that raises an error when p_value < 0 before assigning. If the value never changes, declare it as a CONSTANT in the specification instead.