3 ms·
To me, objects is a data abstraction technique which is about abstracting the said data under a set of operations known as the interface; You are no more thinki
by CodeArtisan 9y ago
To me, objects is a data abstraction technique which is about abstracting the
said data under a set of operations known as the interface; You are no more
thinking about the data but about the operations which then allows all kind of
interface abstraction techniques known as design patterns. Once you break that
abstraction, you break everything which is relying on.
Even for small classes where there is no design pattern involved, it is important
to think about the interface first then the data. take for example, a rectangle,
you may think (g/s)etters would be pointless and be tempted to do
class Rectangle:
public x, y, w, h;
public Rectangle(x, y, w, h):
this.x = x;
...
Then you need the area
class Rectangle:
...
public area():
return w * h;
Then you need to cache the area
class Rectangle:
public x, y, w, h, cached_area;
public Rectangle(w, h):
this.w = w;
this.h = h;
cached_area = w * h;
public area():
return cached_area;
Problem here is that w and h being public, user can corrupt the area, you now need
to rely on (s/g)etters.
class rectangle
...
private w;
public setWidth(w):
this.w = w;
updateArea();
private updateArea():
cached_area = w * h;
If you had start with an interface only having operations, you would never had that problem.
interface Rectangle:
getX();
setX(x);
getWidth();
setWidth(w);
area();
...
// implementations are irrelevant to the user.
class RectangleCached implements Rectangle:
...
class RectangleLazy implements Rectangle:
...
class RectangleWhatever implements Rectangle:
...
One of the great leaps in OO is to be able to answer the question "How does this work?" with
"I don't care" (Alan Knight)
Note that another solution in this case would be immutability but this is another discussion.