If a method returns a private field which is type casted, does this consider as breaking the abstraction barrier?
e.g.
private Object thing;
public getThing() {
return (String) thing;
}
If a method returns a private field which is type casted, does this consider as breaking the abstraction barrier?
e.g.
private Object thing;
public getThing() {
return (String) thing;
}
Regardless the property type which is Object and you make string type casting, it doesn't break abstraction barrier, because you're just type-casting a property inside the same property class, and the code you implement inside that method on the "thing" property means you "abstracted" the implementation on that property, if you change the access modifier from private to public and from outside as a client you make something like let's say className.thing = Obj, then you do break abstraction barrier.
The abstraction barrier is about ensuring that the client of an abstraction can rely on the abstraction without having to know anything about its specific implementation. This means that one implementation of the abstraction could be replaced by a completely different one, as long as it uses the same implicit or explicit interface and it offers the same "contract" (i.e. the set or rules that define the invariants of the abstraction and the pre and postcondition for each of its operation.
In your example the abstraction barrier seems not broken at first sight:
String getThing()
.String Thing
or a privateThing
object that can be transformed into aString
; but it could as well have no private thing at all and instead compute some string ore return a random one.String
is immutable. So the user cannot accidentally use a leaked internal object to pass the abstraction barrier and break the class invariants.What about the downcasting without first checking ? One could claim that this could easily trigger an exception and prevent the
String
from being returned. Although completely true (and I would encourage to avoid such wild downcasts), this claim does not affect the abstraction barrier: