Jump to content

Break OO privacy: Difference between revisions

m (→‎{{header|Java}}: correct mixed use of tabs and spaces)
Line 72:
=={{header|Ada}}==
 
One of the great criticisms of Pascal was "there is no escape". The reason was that sometimes you have to convert the incompatible. ForWe thisstart purposewith a package, Adawhich hasdefines the genericdata functiontype Unchecked_Conversion,which thatholds can be used for suchthe purposessecret.
as breaking OO privacy. We start with the package that holds the "secret":
 
<lang Ada>package OO_Privacy is
Line 86 ⟶ 85:
end OO_Privacy;</lang>
 
When we later define an object C of type Confidential_Stuff, we can't read read the password stored in C -- except by breaking / bypassing OO privacy rules.
Second, the package that provides the "hack" into Confidential_Stuff:
 
=== Using Unchecked_Conversion ===
 
One way to read the password is by using the generic function Unchecked_Conversion:
 
<lang Ada>with OO_Privacy, Ada.Unchecked_Conversion, Ada.Text_IO;
Line 108 ⟶ 111:
 
<pre>The secret password is "default!"</pre>
 
=== Child Packages ===
 
Another way to bypass privacy is using a child package. Ada child packages have access to their parents' private data structures (somewhat similar to "friends" in C++"):
 
<lang Ada>package OO_Privacy.Friend is -- hhild package of OO.Privacy
function Get_Password(Secret: Confidential_Stuff) return String;
end OO_Privacy.Friend;</lang>
 
<lang Ada>package body OO_Privacy.Friend is -- implementation of the child package
function Get_Password(Secret: Confidential_Stuff) return String is
(Secret.Password);
end OO_Privacy.Friend;</lang>
 
Now here is the program that uses the child package, to read the secret:
 
<lang Ada>with OO_Privacy.Friend, Ada.Text_IO;
procedure Bypass_OO_Privacy is
C: OO_Privacy.Confidential_Stuff; -- which password is hidden inside C?
begin
Ada.Text_IO.Put_Line("Password: """ &
OO_Privacy.Friend.Get_Password(C) &
"""");
end Bypass_OO_Privacy;</lang>
 
Once again, we have been too lazy to overwrite the default password:
 
<pre>Password: "default!"</pre>
 
In fact, the password has to be the default one, because we cannot change the password. For that purpose, we would have to write a setter procedure, and either include it in the package OO_Privacy, or in a child package of OO_Privacy. (Or we could use Unchecked_Conversion to overwrite the default password -- but that is bad style.)
 
=={{header|C sharp}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.