For what I know, encapsulation is useful because:
- if you use directly an attribute and change its type in a static typed language you have to change all the code that uses the class. On the contrary, if you have declared getters and setters for that attribute you have not to do this
- it hides the internal functioning of your class, useful if, for example, you're offering an API
- it avoids that another class that inherits your class will overwrite attributes or methods
My considerations about dynamic typed, interpreted programming language are:
- since the types are dynamic there's no need to encapsulate your class for this reason
- you can see the code of an interpreted language, so I think there's not a way to really hide your API
- this could be a problem when this is unintended, but my opinion is that it should be better to make attention to unintended overwriting instead of limiting by default this possibility. Python is a good example: if you declare for example, the name of an attribute or method starting it with a double underscore, you can declare it also in a inherited class, but they are threated as two distinct variables even if they have the same name (thank you delnan)
a method name that starts with a "_" character raises a warning if overwritten by a method of an inheriting class.
Am I missing something important?
_
is a convention and nothing special. A leading__
(double underscore) invokes name mangling, but that doesn't cause a warning when overriding, it's just a hack that makes accidental overwriting much less likely by incorporating the class name into the attribute name.from mypackage import *
. On the contrary methods and attributes that start with a double underscore are in a sort of "class namespace". Read stackoverflow.com/questions/70528/… and docs.python.org/3/tutorial/classes.html