Break OO privacy: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1:
{{task}} [[Category:Object oriented]]
{{omit from|AWKtask}}
{{omit from|BASIC}}
{{omit from|BBC BASIC}}
{{omit from|C}}
{{omit from|Déjà Vu}}
{{omit from|GUISS}}
{{omit from|Haskell}}
{{omit from|Locomotive Basic}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Mathematica}}
{{omit from|R}}
{{omit from|Rust}}
{{omit from|SmileBASIC}}
{{omit from|ZX Spectrum Basic}}
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|Z80 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|x86 Assembly}}
{{omit from|ARM Assembly}}
 
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
Line 28 ⟶ 8:
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
 
=={{header|ABAP}}==
 
Similar to C++, ABAP allows the declaration of friends which can be both classes and interfaces. All subclasses of friend classes are automatically friends of the source class. For example if classA (source) has classB as a friend and classC is a subclass of classB then classC is a friend of classA. Similarly all implementing classes of friend interfaces are friends of the source class. Also all interfaces which contain the befriended interface as a component are friends of the source class.
 
<syntaxhighlight lang=ABAP"abap">class friendly_class definition deferred.
 
class my_class definition friends friendly_class .
Line 75 ⟶ 54:
endclass.
</syntaxhighlight>
 
=={{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. We start with a package, which defines the data type which holds the secret.
 
<syntaxhighlight lang=Ada"ada">package OO_Privacy is
 
type Confidential_Stuff is tagged private;
Line 97 ⟶ 75:
One way to read the password is by using the generic function Unchecked_Conversion:
 
<syntaxhighlight lang=Ada"ada">with OO_Privacy, Ada.Unchecked_Conversion, Ada.Text_IO;
 
procedure OO_Break_Privacy is
Line 122 ⟶ 100:
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++"):
 
<syntaxhighlight lang=Ada"ada">package OO_Privacy.Friend is -- child package of OO.Privacy
function Get_Password(Secret: Confidential_Stuff) return String;
Line 128 ⟶ 106:
end OO_Privacy.Friend;</syntaxhighlight>
 
<syntaxhighlight lang=Ada"ada">package body OO_Privacy.Friend is -- implementation of the child package
function Get_Password(Secret: Confidential_Stuff) return String is
Line 137 ⟶ 115:
Now here is the program that uses the child package, to read the secret:
 
<syntaxhighlight lang=Ada"ada">with OO_Privacy.Friend, Ada.Text_IO;
procedure Bypass_OO_Privacy is
Line 154 ⟶ 132:
 
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|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Reflection;
 
Line 175 ⟶ 152:
}</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">42</syntaxhighlight>
 
=={{header|C++}}==
 
C++ has the 'friend' keyword to indicate that one class should have access to the private data of another. Here's a simple use case. (Please note that this code is not thread-safe.)
 
<syntaxhighlight lang="cpp">#include <iostream>
 
class CWidget; // Forward-declare that we have a class named CWidget.
Line 249 ⟶ 225:
}</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">Widget spawning. There are now 1 Widgets instanciated.
Widget spawning. There are now 2 Widgets instanciated.
Widget dieing. There are now 1 Widgets instanciated.
Line 258 ⟶ 234:
Without the "friend" mechanism, it's still possible to meaningfully modify any member in another class, as long as you know that member's address in memory, and its type. Here's the same program as above, but using a pointer to m_uicount, rather a reference to the factory:
 
<syntaxhighlight lang="cpp">#include <iostream>
 
class CWidget; // Forward-declare that we have a class named CWidget.
Line 324 ⟶ 300:
delete pWidget2;
}</syntaxhighlight>
 
=={{header|Clojure}}==
You can use the var-quote macro to get values from private variables. Here's an example of a variable 'priv' marked private in namespace 'a':
<syntaxhighlight lang="clojure">
(ns a)
(def ^:private priv :secret)
Line 338 ⟶ 313:
 
Clojure can also access Java private variables with the same strategy that Java uses. As a convenience, use the [http://clojuredocs.org/clojure_contrib/clojure.contrib.reflect/get-field get-field] function from clojure.contrib.reflect. Here's an example of grabbing the private field "serialVersionUID" from java.lang.Double:
<syntaxhighlight lang="clojure">
user=> (get-field Double "serialVersionUID" (Double/valueOf 1.0))
-9172774392245257468
</syntaxhighlight>
 
=={{header|Common Lisp}}==
 
Line 358 ⟶ 332:
A symbol can be present in more than one package, such that it can be internal in some of them, and external in others.
 
<syntaxhighlight lang="lisp">(defpackage :funky
;; only these symbols are public
(:export :widget :get-wobbliness)
Line 410 ⟶ 384:
*** - READ from #<INPUT BUFFERED FILE-STREAM CHARACTER #P"funky.lisp" @44>:
#<PACKAGE FUNKY> has no external symbol with name "WOBBLINESS"</pre>
 
=={{header|D}}==
 
Line 416 ⟶ 389:
 
breakingprivacy.d:
<syntaxhighlight lang=D"d">module breakingprivacy;
 
struct Foo
Line 429 ⟶ 402:
 
app.d:
<syntaxhighlight lang=D"d">import std.stdio;
import breakingprivacy;
 
Line 447 ⟶ 420:
 
{{out}}
<syntaxhighlight lang="text">Foo([1, 2, 3], 42, "Hello World!", 3.14)
foo.x = 42
Modified foo: Foo([1, 2, 3], 42, "Not so private anymore!", 3.14)</syntaxhighlight>
 
=={{header|E}}==
 
Line 456 ⟶ 428:
 
{{improve|E|Show an example of such an evaluator once it is available.}}
 
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<syntaxhighlight lang="fsharp">open System
open System.Reflection
 
Line 477 ⟶ 448:
{{out}}
<pre>System.Int32 = 42</pre>
 
=={{header|Factor}}==
From the [http://docs.factorcode.org/content/article-word-search-private.html documentation for private words]: ''"Privacy is not enforced by the system; private words can be called from other vocabularies, and from the listener. However, this should be avoided where possible."''
Line 483 ⟶ 453:
This example uses the private word ''sequence/tester'' from the vocabulary ''sets.private''. It tries to count the elements in an intersection of two sets.
 
<syntaxhighlight lang="factor">( scratchpad ) USING: sets sets.private ;
( scratchpad ) { 1 2 3 } { 1 2 4 } sequence/tester count .
2</syntaxhighlight>
Line 489 ⟶ 459:
There is better way to do the same, without any private words.
 
<syntaxhighlight lang="factor">( scratchpad ) USE: sets
( scratchpad ) { 1 2 3 } { 1 2 4 } intersect length .
2</syntaxhighlight>
 
=={{header|Forth}}==
{{works with|Forth}}
Line 499 ⟶ 468:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<syntaxhighlight lang="forth">include FMS-SI.f
 
99 value x \ create a global variable named x
Line 517 ⟶ 486:
f1 print \ 50
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
FreeBASIC generally does a good job of maintaining OO privacy as it doesn't support reflection and even its OffsetOf keyword cannot obtain the offset within a user defined type of a private or protected field. You therefore have to guess the offset of a non-public field in order to be able to access it using a raw pointer though this is not generally a difficult task.
 
However, as usual, macros come to the rescue and one can easily access non-public members by the simple expedient (or, if you prefer, 'dirty hack') of redefining the Private and Protected keywords to mean Public:
<syntaxhighlight lang="freebasic">'FB 1.05.0 Win64
 
#Undef Private
Line 548 ⟶ 516:
1 2 3
</pre>
 
=={{header|Go}}==
Go has a <code>reflect</code> and <code>unsafe</code> package that together can do this.
Line 555 ⟶ 522:
A relevant Go Blog article is
[http://blog.golang.org/laws-of-reflection The Laws of Reflection].
<syntaxhighlight lang="go">package main
 
import (
Line 658 ⟶ 625:
 
==Icon and {{header|Unicon}}==
{{omit from|Icon}}
Unicon implements object environments with records and supporting procedures for creation, initialization, and methods. The variables in the class environment can be accessed like any other record field. Additionally, with the ''fieldnames'' procedure you can obtain the names of the class variables.
 
Line 664 ⟶ 630:
 
Note: Unicon can be translated via a command line switch into icon which allows for classes to be shared with Icon code (assuming no other incompatibilities exist).
<syntaxhighlight lang="unicon">link printf
 
procedure main()
Line 689 ⟶ 655:
var 1 of foo x = 1
foo var1=-1, var2=2, var3=3</pre>
 
=={{header|J}}==
 
Line 697 ⟶ 662:
 
J does support a "[http://www.jsoftware.com/help/dictionary/dx003.htm Lock Script]" mechanism - to transform a J script so that it's unreadable. However, anyone with access to a machine running the code and ordinary developer tools or who understands the "locking" technique could unlock it.
 
=={{header|Java}}==
Private fields (and in general all members) of a Java class can be accessed via reflection, but must pass a security check in order to do so. There are two such security checks, one for discovering the field at all, and another for granting access to it in order to be able to read and write it. (This in turn means that trusted applications can do this — it is in fact a mechanism used by important frameworks like Spring — but untrusted applets cannot.)
<syntaxhighlight lang="java">import java.lang.reflect.*;
class Example {
Line 737 ⟶ 701:
 
(Note: somewhere between Java 8 and Java 11 this stopped working because the <code>value</code> field of <code>String</code> is <code>final</code>. The reflective access is still possible, but changing a final field isn't.)
<syntaxhighlight lang=Java"java">import java.lang.reflect.*;
public class BreakString{
public static void main(String... args) throws Exception{
Line 753 ⟶ 717:
5
</pre>
 
=={{header|Julia}}==
 
Julia's object model is one of structs which contain data and methods which are just functions using those structs, with multiple dispatch, rather than object methods, used to distinguish similarly named calls for different object types. Julia does not therefore enforce any private fields in its structures, since, except for constructors, it does not distinguish object methods from other functions. If private fields or methods are actually needed they can be kept from view by placing them inside a module which cannot be directly accessed by user code, such as in a module within a module.
 
=={{header|Kotlin}}==
For tasks such as this, reflection is your friend:
<syntaxhighlight lang="scala">import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible
 
Line 781 ⟶ 743:
secret -> 42
</pre>
 
=={{header|Logtalk}}==
Logtalk provides a ''context switching call'' control construct that allows a call to be executed as from within an object. It's mainly used for debugging and for writing unit tests. This control construct can be disabled on a global or per object basis to prevent it of being used to break encapsulation.
 
In the following example, a prototype is used for simplicity.
<syntaxhighlight lang="logtalk">:- object(foo).
 
% be sure that context switching calls are allowed
Line 799 ⟶ 760:
:- end_object.</syntaxhighlight>
After compiling and loading the above object, we can use the following query to access the private method:
<syntaxhighlight lang="logtalk">| ?- foo<<bar(X).
X = 1 ;
X = 2 ;
X = 3
true</syntaxhighlight>
 
=={{header|Lua}}==
 
Line 811 ⟶ 771:
These can be accessed indirectly through the [https://www.lua.org/manual/5.1/manual.html#5.9 debug library].
 
<syntaxhighlight lang=Lua"lua">local function Counter()
-- These two variables are "private" to this function and can normally
-- only be accessed from within this scope, including by any function
Line 848 ⟶ 808:
 
Note that there's an infinite number of other more complex ways for functions to store values in a "private" manner, and the introspection functionality of the debug library can only get you so far.
 
=={{header|M2000 Interpreter}}==
We want to read two private variables, and change values without using a public method (a module or a function), and without attach a temporary method (we can do that in M2000). There is a variant in READ statemend to set references from group members (for variables and arrays, and objects) to names with a reference for each. So using these names (here in the exaample K, M) we can read and write private variables.
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module CheckIt {
Group Alfa {
Line 873 ⟶ 832:
CheckIt
</syntaxhighlight>
 
=={{header|Nim}}==
File oo.nim:
<syntaxhighlight lang="nim">type Foo* = object
a: string
b: string
Line 884 ⟶ 842:
Foo(a: a, b: b, c: c)</syntaxhighlight>
By not adding a <code>*</code> to <code>Foo</code>'s members we don't export them. When we import this module we can't use them directly:
<syntaxhighlight lang="nim">var x = createFoo("this a", "this b", 12)
 
echo x.a # compile time error</syntaxhighlight>
The easiest way to get a debug view of any data:
<syntaxhighlight lang="nim">echo repr(x)</syntaxhighlight>
Output:
<pre>[a = 0x7f6bb87a7050"this a",
Line 894 ⟶ 852:
c = 12]</pre>
More fine-grained:
<syntaxhighlight lang="nim">import typeinfo
 
for key, val in fields(toAny(x)):
Line 912 ⟶ 870:
Key c
is an integer with value: 12</pre>
 
=={{header|Objective-C}}==
In older versions of the compiler, you can simply access a private field from outside of the class. The compiler will give a warning, but you can ignore it and it will still compile. However, in current compiler versions it is now a hard compile error.
Line 919 ⟶ 876:
One solution is to use Key-Value Coding. It treats properties and instance variables as "keys" that you can get and set using key-value coding methods.
 
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface Example : NSObject {
Line 964 ⟶ 921:
Another solution is to use a category to add methods to the class (you can have categories in your code modify any class, even classes compiled by someone else, including system classes). Since the new method is in the class, it can use the class's private instance variables with no problem.
 
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface Example : NSObject {
Line 1,023 ⟶ 980:
Finally, you can access the instance variable directly using runtime functions.
 
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
#import <objc/runtime.h>
 
Line 1,066 ⟶ 1,023:
Hello, I am Edith
</pre>
 
=={{header|OCaml}}==
 
Line 1,077 ⟶ 1,033:
The reader is advised to stop reading here.
 
<syntaxhighlight lang="ocaml">class point x y =
object
val mutable x = x
Line 1,117 ⟶ 1,073:
Broken coord: (-1, -1)
(0, 0)</pre>
 
=={{header|Oforth}}==
 
Line 1,123 ⟶ 1,078:
 
There is no other way to access attributes values from outside but to call methods on the object.
 
=={{header|Perl}}==
Perl's object model does not enforce privacy. An object is just a blessed reference, and a blessed reference can be dereferenced just like an ordinary reference.
<syntaxhighlight lang="perl">package Foo;
sub new {
my $class = shift;
Line 1,144 ⟶ 1,098:
<pre>I am ostensibly private
I am ostensibly private</pre>
 
=={{header|Phix}}==
{{libheader|Phix/Class}}
Line 1,150 ⟶ 1,103:
We can easily break that privacy mechanism via low-level routines with the required simulated/fake context,<br>
and at the same time be reasonably confident that no-one is ever going to manage to achieve that by accident.
<!--<syntaxhighlight lang=Phix"phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no class under p2js)</span>
<span style="color: #008080;">class</span> <span style="color: #000000;">test</span>
Line 1,175 ⟶ 1,128:
"this breaks privacy"
</pre>
 
=={{header|PHP}}==
While normally accessing private variables causes fatal errors, it's possible to catch output of some debugging functions and use it. Known functions which can get private variables include: <code>var_dump()</code>, <code>print_r()</code>, <code>var_export()</code> and <code>serialize()</code>. The easiest to use is <code>var_export()</code> because it's both valid PHP code and doesn't recognize private and public variables.
 
{{works with|PHP|5.1}}
<syntaxhighlight lang="php"><?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
Line 1,204 ⟶ 1,156:
{{works with|PHP|4.x}}
{{works with|PHP|5.x}}
<syntaxhighlight lang="php"><?php
class SimpleClass {
private $answer = 42;
Line 1,215 ⟶ 1,167:
{{works with|PHP|5.3}}
Since php 5.3, one can easily read and write any protected and private member in a object via reflection.
<syntaxhighlight lang="php"><?php
class fragile {
private $foo = 'bar';
Line 1,236 ⟶ 1,188:
}
</pre>
 
=={{header|PicoLisp}}==
PicoLisp uses [http://software-lab.de/doc/ref.html#transient "transient symbols"] for variables, functions, methods etc. inaccessible from other parts of the program. Lexically, a transient symbol is enclosed by double quotes.
The only way to access a transient symbol outside its namespace is to search for its name in other (public) structures. This is done by the '[http://software-lab.de/doc/refL.html#loc loc]' function.
<syntaxhighlight lang=PicoLisp"picolisp">(class +Example)
# "_name"
 
Line 1,253 ⟶ 1,204:
(setq Foo (new '(+Example) "Eric"))</syntaxhighlight>
Test:
<syntaxhighlight lang=PicoLisp"picolisp">: (string> Foo) # Access via method call
-> "Hello, I am Eric"
 
Line 1,273 ⟶ 1,224:
: (get Foo (loc "_name" +Example))
-> "Edith"</syntaxhighlight>
 
=={{header|Python}}==
Python isn't heavily into private class names. Although private class names can be defined by using a double underscore at the start of the name, such names are accessible as they are mangled into the original name preceded by the name of its class as shown in this example:
<syntaxhighlight lang="python">>>> class MyClassName:
__private = 123
non_private = __private * 2
Line 1,292 ⟶ 1,242:
123
>>> </syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
We may call into the MOP (Meta-Object Protocol) via the <tt>.^</tt> operator, and the MOP knows all about the object, including any supposedly private bits. We ask for its attributes, find the correct one, and get its value.
<syntaxhighlight lang="raku" line>class Foo {
has $!shyguy = 42;
}
Line 1,305 ⟶ 1,254:
{{out}}
<pre>42</pre>
 
=={{header|Ruby}}==
Ruby lets you redefine great parts of the object model at runtime and provides several methods to do so conveniently. For a list of all available methods look up the documentation of <code>Object</code> and <code>Module</code> or call informative methods at runtime (<code>puts Object.methods</code>).
<syntaxhighlight lang="ruby">
class Example
def initialize
Line 1,327 ⟶ 1,275:
p example.instance_variable_get :@private_data # => 42
</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<syntaxhighlight lang="scala">class Example(private var name: String) {
override def toString = s"Hello, I am $name"
}
Line 1,342 ⟶ 1,289:
println(foo)
}</syntaxhighlight>
 
=={{header|Sidef}}==
Sidef's object model does not enforce privacy, but it allows storing private attributes inside the container of an object, which is an hash:
<syntaxhighlight lang="ruby">class Example {
has public = "foo"
method init {
Line 1,360 ⟶ 1,306:
# Access private attributes
say obj{:private}; #=> "secret"</syntaxhighlight>
 
=={{header|Swift}}==
Swift reflection provides a Collection of label-value pairs for struct properties
<syntaxhighlight lang=Swift"swift">struct Example {
var notSoSecret = "Hello!"
private var secret = 42
Line 1,377 ⟶ 1,322:
{{out}}
<pre>Value of the secret is 42</pre>
 
=={{header|Tcl}}==
Tcl's object properties are just variables in the a per-instance namespace; all that's required to get hold of them is to discover the name of the namespace concerned:
<syntaxhighlight lang="tcl">package require Tcl 8.6
 
oo::class create Example {
Line 1,393 ⟶ 1,337:
Hello, I am Eric
Hello, I am Edith
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
Line 1,400 ⟶ 1,343:
Like the other .NET languages, VB can use Reflection ([https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection Microsoft docs]).
 
<syntaxhighlight lang="vbnet">Imports System.Reflection
 
' MyClass is a VB keyword.
Line 1,418 ⟶ 1,361:
{{out}}
<pre>42</pre>
 
=={{header|Wren}}==
In Wren all instance and static fields of a class are private and are prefixed by an underscore and a double underscore respectively. There is no way to break the privacy of such fields that I'm aware of (Wren doesn't have reflection). If one wants to provide public access to fields then this is done via getter and/or setter methods.
 
However, there is no such thing as a private method. Although conventionally methods which are not intended to be called from outside the class are suffixed with an underscore, this doesn't prevent anyone from accessing them as the following example shows.
<syntaxhighlight lang="ecmascript">class Safe {
construct new() { _safe = 42 } // the field _safe is private
safe { _safe } // provides public access to field
Line 1,440 ⟶ 1,382:
84
</pre>
 
=={{header|zkl}}==
In zkl, privacy is more convention than enforced (unlike const or protected).
<syntaxhighlight lang="zkl">class C{var [private] v; fcn [private] f{123} class [private] D {}}
C.v; C.f; C.D; // all generate NotFoundError exceptions
However:
Line 1,451 ⟶ 1,392:
C.vars //-->L(L("",Void)) (name,value) pairs</syntaxhighlight>
In the case of private vars, the name isn't saved.
{{omit from|6502 Assembly}}
 
{{omit from|8086 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|ARM Assembly}}
{{omit from|AWK}}
{{omit from|BASIC}}
{{omit from|BBC BASIC}}
{{omit from|C}}
{{omit from|Déjà Vu}}
{{omit from|GUISS}}
{{omit from|Haskell}}
{{omit from|Icon}}
{{omit from|Locomotive Basic}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Mathematica}}
{{omit from|Rust}}
{{omit from|R}}
{{omit from|SmileBASIC}}
{{omit from|Standard ML|not OO}}
{{omit from|x86 Assembly}}
{{omit from|Z80 Assembly}}
{{omit from|ZX Spectrum Basic}}
10,333

edits