Sub topic 16
Design, naming, and testing guidelines
This chapter assumes you can already create procedures, functions, and packages, and that you know IN, OUT, and IN OUT parameters, RAISE_APPLICATION_ERROR, and the basics of EXECUTE grants. It turns those features into habits that keep subprograms readable, safe to change, and easy to verify. Examples use the employees table from the Oracle HR sample schema.
Design guidelines
Choose the subprogram type by its job
A procedure performs an action. A function computes a value. Most design mistakes come from blurring that line.
- Use a procedure when the main result is a change: DML, a status update, a file write.
- Use a function when the caller needs one value back and the call has no visible side effects.
- Do not give a function OUT parameters. A function with OUT parameters cannot be called from SQL, and callers can no longer tell what it returns.
- If a routine must return several values, use a procedure with OUT parameters or return a record or collection.
- Do not put DML or
COMMITinside a function you plan to call from SQL. Oracle restricts this, and a function that changes data per row is hard to reason about.
Keep each subprogram small and single-purpose
A subprogram should do one thing that you can name in a short phrase. If you need "and" in the name, split it. Long bodies usually hide steps that deserve their own private helper in a package body. Helpers that are not in the package specification cannot be called from outside, so you can change them freely.
Put related code in packages
Standalone procedures are fine for small utilities. For anything with several related routines, use a package:
- The specification is the public contract. Keep it small.
- Private helpers, constants, and state stay in the body.
- Changing the body does not invalidate callers. Changing the specification does. This is the dependency behavior from the compilation chapter, and it is the main practical reason to package code.
Anchor types and validate inputs
Declare parameters and variables with %TYPE or %ROWTYPE so they follow the column definitions. Validate inputs at the top of the subprogram and fail early with a specific error number. Check for NULL explicitly, because NULL <= 0 is neither true nor false.
Handle errors on purpose
- Catch only the exceptions you can handle.
WHEN NO_DATA_FOUNDin a lookup function is a decision.WHEN OTHERS THEN NULLis a bug that hides failures. - If you catch
WHEN OTHERS, log the error and re-raise it with a bareRAISE;. - Reserve
RAISE_APPLICATION_ERRORfor conditions the caller should understand, and document the numbers (-20000 to -20999) you use. - Leave
COMMITandROLLBACKto the code that owns the transaction, usually the outermost caller. A subprogram that commits on its own makes reuse and testing harder.
Naming guidelines
Consistent prefixes make it obvious where a name comes from. This matters because of scope resolution inside SQL statements, which is explained below the table.
| Item | Convention | Example |
|---|---|---|
| Parameter | `p_` prefix | `p_employee_id` |
| Local variable | `v_` prefix | `v_name` |
| Constant | `c_` prefix | `c_max_percent` |
| User-defined exception | `e_` prefix | `e_invalid_percent` |
| Procedure | Verb phrase | `raise_salary`, `archive_orders` |
| Function | Noun phrase or `get_` | `get_full_name`, `tax_rate_for` |
| Package | Domain plus role | `emp_salary_api` |
Other naming rules:
- Do not reuse a built-in or table name for a subprogram or variable.
- Keep names under 30 bytes if your database may be older than 12.2, where that is the identifier limit.
- Name a function after what it returns and a procedure after what it does.
- Pick one language for names and one style (snake case is the norm in PL/SQL) and apply it everywhere.
A package designed with these rules
The package below applies the guidelines: a small public specification, a named exception, a constant, input validation, and a clear error for an unknown employee.
CREATE OR REPLACE PACKAGE emp_salary_api AS
c_max_percent CONSTANT NUMBER := 50;
e_invalid_percent EXCEPTION;
PRAGMA EXCEPTION_INIT(e_invalid_percent, -20002);
PROCEDURE raise_salary (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
);
END emp_salary_api;
/
CREATE OR REPLACE PACKAGE BODY emp_salary_api AS
PROCEDURE raise_salary (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
) IS
BEGIN
IF p_percent IS NULL OR p_percent <= 0 OR p_percent > c_max_percent THEN
RAISE_APPLICATION_ERROR(-20002,
'Percent must be above 0 and at most ' || c_max_percent);
END IF;
UPDATE employees
SET salary = salary * (1 + p_percent / 100)
WHERE employee_id = p_employee_id;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee not found: ' || p_employee_id);
END IF;
END raise_salary;
END emp_salary_api;
/Callers can handle emp_salary_api.e_invalid_percent by name instead of comparing error numbers. The procedure does not commit, so the caller decides when the change becomes permanent.
Testing guidelines
A subprogram is only finished when you have shown how it behaves for good input, bad input, and edge cases. You do not need a framework to start.
What to test
- The normal case, checking the actual result in the table or the return value.
- Each error you raise on purpose, checking the error number.
NULLinputs, becauseNULLpasses many comparisons silently.- Boundary values, such as a percent of exactly 0 and exactly the maximum.
- Empty results, such as a function called with a key that does not exist.
- Defaults, by calling once with the parameter and once without it.
A repeatable test block
Run SET SERVEROUTPUT ON in SQL*Plus or SQLcl first so the output is visible. The block below tests the package and rolls back its data change, so you can run it as often as you like.
DECLARE
v_before employees.salary%TYPE;
v_after employees.salary%TYPE;
PROCEDURE report (p_test IN VARCHAR2, p_passed IN BOOLEAN) IS
BEGIN
DBMS_OUTPUT.PUT_LINE(
RPAD(p_test, 32) || CASE WHEN p_passed THEN 'PASS' ELSE 'FAIL' END);
END report;
BEGIN
-- Normal case
SELECT salary INTO v_before FROM employees WHERE employee_id = 100;
emp_salary_api.raise_salary(100, 10);
SELECT salary INTO v_after FROM employees WHERE employee_id = 100;
report('raises salary by 10 percent', v_after = v_before * 1.1);
ROLLBACK;
-- Percent above the limit
BEGIN
emp_salary_api.raise_salary(100, 500);
report('rejects 500 percent', FALSE);
EXCEPTION
WHEN emp_salary_api.e_invalid_percent THEN
report('rejects 500 percent', TRUE);
END;
-- NULL percent
BEGIN
emp_salary_api.raise_salary(100, NULL);
report('rejects NULL percent', FALSE);
EXCEPTION
WHEN emp_salary_api.e_invalid_percent THEN
report('rejects NULL percent', TRUE);
END;
-- Unknown employee
BEGIN
emp_salary_api.raise_salary(-1);
report('rejects unknown employee', FALSE);
EXCEPTION
WHEN OTHERS THEN
report('rejects unknown employee', SQLCODE = -20001);
END;
ROLLBACK;
END;
/Each negative test reports FAIL if no exception is raised. That case is easy to forget, and without it a test for a missing error passes by accident.
Checks around the code
- After each
CREATE OR REPLACE, queryUSER_ERRORSfor the object. A "Warning: compiled with errors" message is easy to miss in scripts. - Query
USER_OBJECTSforSTATUS = 'INVALID'before and after a deployment to catch broken dependencies. - Enable compiler warnings with
ALTER SESSION SET PLSQL_WARNINGS = 'ENABLE:ALL';during development. They flag unreachable code and unused variables. - Test functions in SQL as well as in blocks. A function that works in a block can fail in a query because of the purity restrictions.
- For larger projects, use a unit-test framework such as utPLSQL. It provides assertions, setup and teardown, and reports that a build server can read.
Review checklist
| Question | Why it matters |
|---|---|
| Is it a procedure or a function for the right reason? | Prevents side-effect surprises in SQL |
| Do all parameters and variables carry prefixes and anchored types? | Avoids name capture and type drift |
| Are inputs validated, including `NULL`? | Fails early with a clear message |
| Does any handler hide an error? | `WHEN OTHERS THEN NULL` loses information |
| Does the code commit when it should not? | Keeps transaction control with the caller |
| Is there a test for every error path? | Proves the error numbers are real |
Exercise
A procedure has the parameter salary IN NUMBER and contains UPDATE employees SET salary = salary WHERE employee_id = p_employee_id;. The developer expected the salary column to be set to the parameter value. What actually happens, and what two changes fix it?
Show answer
In the SQL statement, salary on the right-hand side resolves to the column, not the parameter, so each row is set to its own current value and nothing changes. Rename the parameter with the p_ prefix (p_salary) and use SET salary = p_salary. Alternatively, qualify the parameter with the subprogram name (procedure_name.salary), but renaming is the simpler and more consistent fix.
Exercise
Your test calls emp_salary_api.raise_salary(100, 500) inside a block that has EXCEPTION WHEN emp_salary_api.e_invalid_percent THEN report('rejects 500 percent', TRUE);. The call is followed by report('rejects 500 percent', FALSE);. Why is that last line needed, and where must it be placed?
Show answer
Without it, the test prints nothing when the procedure raises no error, so a missing check goes unnoticed. It must come directly after the call, inside the same BEGIN section and before the EXCEPTION keyword, so it runs only when no exception was raised. If the exception is raised, control jumps to the handler and skips it.