What is the philosophy behind making instance variables public by default in Scala? - scala

What is the philosophy behind making the instance variables public by default in Scala. Shouldn't making them private by default made developers make less mistakes and encourage composition?

First, you should know that when you write:
class Person( val name: String, val age: Int ) {
...
}
name and age aren't instance variables but accessors methods (getters), which are public by default.
If you write instead:
class Person( name: String, age: Int ) {
...
}
name and age are only instance variables, which are private as you can expect.
The philosophy of Scala is to prefer immutable instance variables, then having public accessors methods is no more a problem.

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 happen to be private, classes start to grow.
It's just a bad default and one of the big reasons for classes with more than 1000 lines in Java.
Scala defaults to immutable, which removes a massive class of errors that people often use private to restrict (but not remove, as the class' own methods can still mutate the variables) in Java.

with immutables which are preferred in many places, public isn't so much of an problem
you can replace a public val with getters and setters without changing the client code, therefore you don't need the extra layer of getters and setters just in case you need it. (Actually you do get that layer but you don't notice it most of the time.)
the java anti pattern of private field + public setters and getters doesn't encapsulate much anyway

(An additional view supplementing the other answers:)
One major driver behind Java's encapsulation of fields was the uniform access policy, i.e. you didn't have to know or care whether something was implemented simply as a field, or calculated by a method on the fly. The big upside of this being that the maintainer of the class in question could switch between the two as required, without needing other classes to be modified.
In Java, this required that everything was accessed via a method, in order to provide the syntactic flexibility to calculate a value if needed.
In Scala, methods and fields can be accessed via equivalent syntax - so if you have a simple property now, there's no loss in encapsulation to expose it directly, since you can choose to expose it as a no-arg method later without your callers needing to know anything about the change.

Related

Why use accessors and mutators with simple classes?

For simple classes (and I mean really simple ones), why do we use accessor and mutator methods? Why do not we just make the data members public?
For example, the following class header (in C++) and could have been implemented with much less effort; as it is actually a couple of data members with accessors and mutators that do nothing but access/modify those data members.
I appreciate the advantage of the use of accessors and mutators in more complex classes.
template<class T>
class Node
{
private:
T item; // A data item
Node<T>* next; // Pointer to next node
public:
Node();
Node(const T& anItem);
Node(const T& anItem, Node<T>* nextNodePtr);
void setItem(const T& anItem);
void setNext(Node<T>* nextNodePtr);
T getItem() const;
Node<T>* getNext() const;
}; // end Node
This is a very fundamental, basic, and well-defined design principle in OOP - why to use accessors and mutators, in spite of whether a class is big or small.
I would still say, that implementation-usage of this principle still varies from language to language, but the core principle of Object Oriented Design - Encapsulation - remains always same and mandates, that you should always hide everything that is possible to hidden.
This is kind of duplicate of your question, and it refers to why getters and setters are in the play; however, I'll try to bring some other points as well.
Encapsulation, aspect of which is the topic in questions (mutators/accessors), is a fundamental and probably the most important principle of Object Oriented Programming.
First and foremost:
The main point of the Encapsulation is not(!) to restrict/block the access to the member variable, but rather to constrain the access policy and mandate the reasonable access, and therefore avoid any unintended interference, implicit misuse, or accidental accesses.
Think about it: if the user invokes .setUserName("MyUser") the one really intends to write the data into the member field, and that's explicitly clear! otherwise, it would mean that the client has (1) accidentally provided the "MyUser" data as an argument into setter method, and they (2) accidentally invoked the .setUserName method, which is way less likely to happen accidentally both together, then just publicly accessing that field, which takes only one move to do.
That being said, using the principle of encapsulation and advocating it as a core OOP feature, software developers, a lot of frameworks and libraries very often conventionally agree and make use of data classes, ordinary classes, business classes, service, or any other types, relying on the widespread Conventional Design and best practice of how to use member variables - using mutators to mutate and accessors to access the fields.
Many frameworks explicitly invoke setters and getters when they implement IoC or DI.
So, it's the best practice, conventionally agreed, non-smelling code style, and the most safe design of the class members, to use encapsulation and interact with them through mutators and accessors.

Swift: Constant's internal implementation

In swift, how is constants implemented?
I read this article, which says
In Swift, constants are generally implemented as (inlined) function calls.
I am not clear of this statement.
Does Swift use a special approach to make constants?
Could anyone explain?
Are you familiar with "getter" and "setter" methods from other languages, such as Java? If a variable is made public in a language like Java, it's exposed to other classes to access directly. In the future, if this variable has to be changed, there's no way to do so without changing all of the other classes dependent upon. With getter/setter methods, dummy implementations can be made that don't do anything besides read/write the value. In the case that a change needs to be made, the implementation of these methods can be changed without effecting the public API of the class.
Swift implements variables with "properties", which are like a backing private variable with public getter/setter methods that are automatically generated. In the future, you can replace a property with a computer property with a special getter/setter implementation, without effecting the public API of the class, just like before. The difference here is that you don't need to write all of the default getters/setters yourself.

Access specifiers- private vs protected

Are there any risks involved with using the protected member access specifier instead of the private member access specifier?
You have not specified which lamguage but, I assume in OO language like java, a protected member is "visible" to child classes. Latter can use them and may break if you happen to change protected members later due to evolution of your class or change in requirements. No such risk in case of private members. A child class can extend the protected members and make it exposed to the outside (public) world.
This answer assumes you are using a language like java:
private members can only be seen by its own class (and inner classes). This is the safest field visibility since it is hidden from all outsiders. Since it's completely hidden, you are free to change the implementation details or even get rid of the field completely later on.
protected members can not only be seen by all subclasses but also from ALL classes that are in the same package. This makes it much harder to later change the field because more classes might be referencing it.

Why doesn't Scala have static members inside a class?

I know you can define them indirectly achieve something similar with companion objects but I am wondering why as a language design were statics dropped out of class definitions.
The O in OO stands for "Object", not class. Being object-oriented is all about the objects, or the instances (if you prefer)
Statics don't belong to an object, they can't be inherited, they don't take part in polymorphism. Simply put, statics aren't object-oriented.
Scala, on the other hand, is object oriented. Far more so than Java, which tried particularly hard to behave like C++, in order to attract developers from that language.
They are a hack, invented by C++, which was seeking to bridge the worlds of procedural and OO programming, and which needed to be backwardly compatible with C. It also admitted primitives for similar reasons.
Scala drops statics, and primitives, because they're a relic from a time when ex-procedural developers needed to be placated. These things have no place in any well-designed language that wishes to describe itself as object-oriented.
Concerning why it's important to by truly OO, I'm going to shamelessly copy and paste this snippet from Bill Venners on the mailing list:
The way I look at it, though, is that singleton objects allow you to
do the static things where they are needed in a very concise way, but
also benefit from inheritance when you need to. One example is it is
easier to test the static parts of your program, because you can make
traits that model those parts and use the traits everywhere. Then in
the production program use a singleton object implementations of those
traits, but in tests use mock instances.
Couldn't have put it better myself!
So if you want to create just one of something, then both statics and singletons can do the job. But if you want that one thing to inherit behaviour from somewhere, then statics won't help you.
In my experience, you tend to use that ability far more than you'd have originally thought, especially after you've used Scala for a while.
I also posted this question on scala users google group and Bill Venners one of the authors of "Programming in scala" reply had some insights.
Take a look at this: https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/6vZJgi42TIMJ and https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/oTrLFtwGjpEJ
Here is an excerpt:
I think one
goal was simply to be simpler, by having every value be an object,
every operation a method call. Java's statics and primitives are
special cases, which makes the language more "complicated" in some
sense.
But another big one I think is to have something you can map Java's
statics to in Scala (because Scala needed some construct that mapped
to Java's statics for interop), but that benefits from OO
inheritance/polymorphism. Singleton objects are real objects. They can
extend a superclass or mix in traits and be passed around as such, yet
they are also "static" in nature. That turns out to be very handy in
practice.
Also take a look at this interview with Martin Odersky (scroll down to Object-oriented innovations in Scala section) http://www.artima.com/scalazine/articles/goals_of_scala.html
Here is an excerpt:
First, we wanted to be a pure object-oriented language, where every value is an object, every operation is a method call, and every variable is a member of some object. So we didn't want statics, but we needed something to replace them, so we created the construct of singleton objects. But even singleton objects are still global structures. So the challenge was to use them as little as possible, because when you have a global structure you can't change it anymore. You can't instantiate it. It's very hard to test. It's very hard to modify it in any way.
To Summarize:
From a functional programming perspective static members are generally considered bad (see this post by Gilad Bracha - the father of java generics. It mainly has to do with side effects because of global state). But scala had to find a way to be interoperable with Java (so it had to support statics) and to minimize (although not totally avoid) global states that is created because of statics, scala decided to isolate them into companion objects.
Companion objects also have the benefit of being extensible, ie. take advantage of inheritance and mixin composition (separate from emulating static functionality for interop).
These are the things that pop into my head when I think about how statics could complicate things:
1) Inheritance as well as polymorphism would require special rules. Here is an example:
// This is Java
public class A {
public static int f() {
return 10;
}
}
public class B extends A {
public static int f() {
return 5;
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
System.out.println(a.f());
B b = new B();
System.out.println(b.f());
A ba = new B();
System.out.println(ba.f());
}
}
If you are 100% sure about what gets printed out, good for you. The rest of us can safely rely on mighty tools like #Override annotation, which is of course optional and the friendly "The static method f() from the type A should be accessed in a static way" warning. This leads us to
2) The "static way" of accessing stuff is a further special rule, which complicates things.
3) Static members cannot be abstract. I guess you can't have everything, right?
And again, these are just things which came to my mind after I gave the matter some thought for a couple of minutes. I bet there are a bunch of other reasons, why statics just don't fit into the OO paradigm.
It's true, static member don't exists, BUT, it's possible to associate a singleton object to each class:
class MyClass {
}
object MyClass {
}
to obtain similar results
Object oriented programming is all about objects and its states(Not touching state full and stateless objects in Java). I’m trying to stress “Static does not belong to objects”. Static fields cannot be used to represent a state of an object so it’s rational to pull off from objects.

In Scala, plural object name for a container of public static methods?

I've written a Scala trait, named Cache[A,B], to provide a caching API. The Cache has the following methods, asyncGet(), asyncPut(), asyncPutIfAbsent(), asyncRemove().
I'm going to have a few static methods, such as getOrElseUpdate(key: A)(op: => B). I don't want methods like this as abstract defs in the Cache trait because I don't want each Cache implementation to have to provide an implementation for it, when it can be written once using the async*() methods.
In looking at Google Guava and parts of the Java library, they place public static functions in a class that is the plural of the interface name, so "Caches" would be the name I would use.
I like this naming scheme actually, even though I could use a Cache companion object. In looking at much of my code, many of my companion objects contain private val's or def's, so users of my API then need to look through the companion object to see what they can use from there, or anything for that matter.
By having a object named "Caches" is consistent with Java and also makes it clear that there's only public functions in there. I'm leaning towards using "object Caches" instead of "object Cache".
So what do people think?
Scala's traits are not just a different name for Java's interfaces. They may have concrete (implemented) members, both values (val and var) and methods. So if there's a unified / generalized / shared implementation of a method, it can be placed in a trait and need not be replicated or factored into a separate class.
I think the mistake starts with "going to have a few static methods". Why have static methods? If you explain why you need static methods, it will help figure out what the design should be.