What is the philosophy of creating default instance variables in Scala?

What is the philosophy for creating public variables by default in Scala. Shouldn't they be made private by default, forcing developers to make fewer mistakes and encourage composition?

+6
source share
4 answers

First, you should know that when you write:

class Person( val name: String, val age: Int ) { ... } 

name and age are not instance variables, but getters, which are publicly accessible by default.

If you write instead:

 class Person( name: String, age: Int ) { ... } 

name and age are only instance variables that are private, as you might expect.

Scala's philosophy is to give preference to immutable instance variables, then using open access methods is no longer a problem.

+11
source

Private encourages monoliths. As soon as it’s easier to put unrelated functionality into a class just because it needs to read some variables that are private, classes start to grow.

This is simply bad by default and one of the main reasons for classes with over 1000 lines in Java.

Scala defaults to immutable, which removes a massive class of errors that people often use private to limit (but not delete, since the class’s own methods can still mutate variables) in Java.

+5
source
  • with immutable, which are preferred in many places, the public is not so much a problem.
  • you can replace the public shaft with getters and setters without changing the client code, so you do not need an additional layer of getters and setters just in case you need it. (Actually, you get this layer, but you don’t notice it most of the time.)
  • java anti-private field pattern + public setters and getters do not encapsulate anyway.
+3
source

(Optional view, complementing the other answers :)

One of the main factors underlying the encapsulation of Java fields was the uniform access policy, i.e. you did not need to know or care about whether something was implemented simply as a field or calculated on the fly. The big disadvantage of this is that the supporting class in question can switch between them as needed, without the need to change other classes.

In Java, this required that everything be accessible using a method in order to provide syntactic flexibility to calculate the value, if necessary.

In Scala, methods and fields can be accessed through the equivalent syntax - so if you have a simple property, there is no loss in encapsulation to expose it directly, since you can choose it as a method without an argument later without your callers who need to know anything about this change.

+3
source

Source: https://habr.com/ru/post/903277/


All Articles