Sql – PL/SQL private object method

oracleoracle10gplsqlsql

I'm a bit new to Oracle's PL/SQL (using 10g), I was wondering if there's a way to make a private method in an object type, as is often done for private helper methods in other languages (Java, C++, C#, etc…). I know it is possible to make private methods in packages, but I can't seem to find a way to do this for object types. I keep getting compiler errors telling me:

Error: PLS-00539: subprogram 'FOO' is declared in an object type body 
and must be defined in the object type specification.

Best Answer

If you just need to use the subprogram (function/procedure) from one subprogram PL/SQL does allow you to nest a subprogram within another in the declaration block.

It's not as ideal as having private methods or functions but it might be worth a try before you go creating an inheritance hierarchy.

create or replace type body some_t
as

member function foo
    return varchar2
    as
        function some_private_foo
            return varchar2
            as
            begin
                return 'Foo!';
            end some_private_foo;
    begin
        return some_private_foo();
    end foo;

end;

If you're on Oracle 12 you're in luck. You can create a package that only your type can code against using the ACCESSIBLE BY clause. In the example below the PL/SQL compiler will only allow code from FOO_T to reference FOO_PRIVATE_PKG.

CREATE OR REPLACE package foo_private_pkg 
accessible by ( foo_t )
as

function some_private_foo ( object_in in out nocopy foo_t )
    return varchar2;
end;