In Scala I see such feature as object-private variable. From my not very rich Java background I learnt to close everything (make it private) and open (provide accessors) if necessary. Scala introduces even more strict access modifier. Should I always use it by default? Or should I use it only in some specific cases where I need to explicitly restrict changing field value even for objects of the same class? In other words how should I choose between
class Dummy {
private var name = "default name"
}
class Dummy {
private[this] var name = "default name"
}
The second is more strict and I like it but should I always use it or only if I have a strong reason?
EDITED: As I see here private[this]
is just some subcase and instead of this
I can use other modifiers: "package, class or singleton object". So I'll leave it for some special case.
I don't think it matters too much, since any changes will only touch one class either way. So the most important reason to prefer private
over protected
over public
doesn't apply.
Use private[this]
where performance really matters (since you'll get direct field access instead of methods this way). Otherwise, just settle on one style so people don't need to figure out why this property is private
and that one is private[this]
.