Does this break the abstraction barrier?

306 Views Asked by At

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;
}
2

There are 2 best solutions below

0
On

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:

  • The abstraction is defined by a simple public method String getThing().
  • The implementation uses a cast. But we don't care and shouldn't have to care about it: it could have a private String Thing or a private Thing object that can be transformed into a String; but it could as well have no private thing at all and instead compute some string ore return a random one.
  • Moreover, 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:

  • First, there is apparently no contractual guaranty, i.e. it is one of the possible outcome of this abstraction to trigger an exception instead of getting the string returned. In reality, you'd probably have a set of invariant, pre- and post-conditions that would make it clearer if an exception is acceptable or not.
  • Second, this is not a question of abstraction barrier: The barrier means that there are two distinct and complementary views: the client of your class who trusts your abstraction, and the implementor of your class who needs to make sure your abstraction is reliable. The fact that a particular implementation is not reliable does not break the abstraction barrier: It just means that you have a buggy implementation ;-)
0
On

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.