Why annotation based libraries are not so popular in Scala? - scala

When I write Java code, I found annotation based libraries are very popular, e.g. hibernate, Jackson, Gson, Spring-MVC. But in Scala, most of the popular libraries are not providing annotations, or provided but recommend non-annotation approaches, e.g. squerly, slick, argonaut, unfiltered, etc.
Sometimes, I found the annotations are easier to read and maintain, but why people are not so interested in them?

One reason is that annotations often have to be used at declaration-site. Hence, you have to "pollute" your domain models with code not relevant to your business logic. Solutions based on macros or type classes on the other hand are usually applied on use-site. This allows higher reusability of your domain models.
E.g., what if you need different serialization logic for different tasks? With annotations you have usually no other choice than implementing an additional representation of your model with modified annotations. With type classes (probably automatically derived through macros), you have to just implement another instance and inject it accordingly to your needs.

Macros and implicits can often be used as a substitute for annotations and have the benefit of being statically checked.

Related

Scala, GUI and immutability

I created an algorithm that calculates certain things. This can be considered as the model. The algorithm is implemented in a fully functional way, so it uses immutable classes only.
Now using this model, I would like to develop a GUI layer on the top of it. However I do not know anything about the best-practises of building GUI in Scala. I intend to use ScalaFX.
My problem is the following: in ScalaFX (similarly to JavaFX) you can bind values from the GUI to object properties. This clearly violates the functional paradigm, but seems very convenient.
This would require rewriting my classes to use bindable properties which would feel like the tail wagging the dog — the model would depend on the GUI.
On the other hand, I could have an independent GUI layer. In this case I would need proxy objects to bind to and I would have to create my model objects based on these proxy objects. This would feel more idiomatic but implies a lot of code duplication and extra work. My model and the proxy objects would have to be kept in sync and I would have to take care of copying the attributes.
What is a good way of doing this? A GUI is always full of mutability so functional programming does not feel right here. Nevertheless I love Scala so I would like to keep using it for the GUI, too.
Despite the extra effort, take the second approach. Create small mutable "view" instances for each of your model. Bind the views to the widgets and install observers or hooks that update the view proxies based on changes in your model. Don't let the GUI API dictate how your concurrency approach and model should look like.
I believe there are a few open source libraries around that provide a more functional and/or reactive abstraction layer to the plain Scala-Swing or Scala-FX.

Are scala reflection API Names or Symbols adequate for use inside transfer objects?

Introduction
I am working on an API written in Scala. I use data transfer objects (DTOs) as parameters passed to the API's functions. The DTOs will be instanciated by the API's user.
As the API is pretty abstract / generic I want to specify the attributes of a object that the API should operate on. Example:
case class Person(name: String, birthdate: Date)
When an instance of Person "P" is passed to the API, the API needs to know the attributes of "P" it should operate on: either just name or birthdate, or both of them.
So I need to design a DTO that contains the instance of "P" itself, some kind of declaration of the attributes and maybe additional information on the type of "P".
String based approach
One way would be to use Strings to specify the attributes of "P" and maybe its type. This would be relatively simple, as Strings are pretty lightweight and well known. As there is a formal notation of packages, types and members as Strings, the declarations would structured to a certain degree.
On the other side, the String-declarations must be validated, because a user might pass invalid Strings. I could imagine types that represent the attributes with dedicated types instead of String, which may have the benefit of increased structure and maybe even those type are designed so that only valid instances can exist.
Reflection API approach
Of course the reflection API came to my mind and I am experimenting to declare the attributes with types out of the reflection API. Unfortunately the scala 2.10.x reflection API is a bit unintuitive. There are names, symbols, mirrors, types, typetags which can cause a bit of confusion.
Basically I see two alternatives to attribute declaration with Strings:
Attribute declaration with reflection API's "Names"
Attribute declaration with reflection API's "Symbols" (especially TermSymbol)
If I go this way, as far as I can see, the API's user, who constructs the DTOs, will have to deal with the reflection API and its Names / Symbols. Also the API's implementation will have to make use of the reflection API. So there are two places with reflective code and the user must have at least a little bit of knowledge of the reflection API.
Questions
However I don't know how heavyweight these approaches are:
Are Names or Symbols expensive to construct?
Does the reflection API do any caching of expensive operation results or should I take care about that?
Are Names and Symbols transferable to another JVM via network?
Are they serializable?
Main question: Are scala reflection API Names or Symbols adequate for use inside transfer objects?
It seems complicated to do this with the reflection API. Any hints are welcome. And any hints on other alternatives, too.
P.S.: I did not include my own code, yet, because my API is complex and the reflection part is in pretty experimental state. Maye I can deliver something useful later.
1a) Names are easy to construct and are lightweight, as they are just a bit more than strings.
1b) Symbols can't be constructed by the user, but are created internally when one resolves names using APIs like staticClass or member. First calls to such APIs usually involve unpacking type signatures of symbol's owners from ScalaSignature annotations, so they might be costly. Subsequent calls use already loaded signatures, but still pay the cost of a by-name lookup in a sort of a hashtable (1). declaration costs less than member, because declaration doesn't look into base classes.
2) Type signatures (e.g. lists of members of classes, params + return type of methods, etc) are loaded lazily and therefore are cached. Mappings between Java and Scala reflection artifacts are cached as well (2). To the best of my knowledge, the rest (e.g. subtyping checks) is generally uncached with a few minor exceptions.
3-4) Reflection artifacts depend on their universe and at the moment can't be serialized (3).

class versus interface in uml

As we know in OOP that interface provides a set of operations without implementation but
class is the opposite.
in Object oriented design ,we use uml the interface has a set of operations without implementation
and the class also has a set of operations without implementation(i know class has attributes in addition to its operations)?
so, what is the difference in UML?
As we know in OOP that interface provides a set of operations without implementation but class is the opposite.
Not quite true - abstract classes are classes that have one or more methods declared but not defined (in C++ and Java these are abstract methods). You can have a class defined with all its methods abstract - in which case there is close similarity with an interface.
One key idea in UML, though, is that an interface is a set of methods exposed to other classes or components. The purpose is to define a set of operations.
However, moving to programming, a method may be made abstract to aid development (e.g. by ensuring all subclasses have an implementation). This method might be purely internal to the class.
One last observation: the term interface and class in UML are not quite synonymous to interface and class in a language, say Java. For example, Java does not allow multiple class inheritance. Instead Java has the interface which allows a class to implement multiple types (not classes - a subtle difference)
EDIT
Quick note technical words:
Declare: Stating to the system that a variable or operation exists and its type or signature
Define: Same as declaring, but additionally providing a complete implementation of a variable or operation
Interface: A set of declarations of operations
Type: An object's interface(s) and other operations
Class: An object's class defines (not declares) how the object is implemented, including its internal state and the implementation of its operations
Define is to Declare as Class is to Type.
(see What is the difference between Type and Class?)
The purpose of interface is to define a set of operations but we are do the same for class also define a set of operations?
So the purpose of the interface is to declare (not define) a set of public operations that other objects want to use. A class (in UML) is the complete set of operations (public and private). A class (in Java, C++, etc.) additionally defines all non-abstract operations.
So the key is the intent: When other components of the system want to use a set of operations, use interface. When you're using UML to describe an implementation (of a component, algorithm, etc.) use class.
when I go to class that assumed to implement those operations I can't see any implementation for those operations as a diagram describe those operations or anything give a sign for implementation?
UML tool is for modelling and so deliberately avoids providing a place where you enter operation definitions - that is left for later. The idea is that you:
Define the model in UML
Use the UML tool to generate code in the target language
(And some allow you to import your code back into the tool to modify the model with any changes made during implementation. This is called "round-trip" modelling, something which the old TogetherJ product excelled at)
This deliberate gap (you might say deficiency) means that 'define' vs. 'declare' in UML is meaningless. Sorry.
Perhaps you've just seen models created for describing an overview, rather than modelling the system fully, but you can model the behaviour of a class's operations in most UML tools, and some tools also model the behaviour sufficiently that it can be executed .
The behaviour associated with an operation can be modelled using UML state machines, using UML action semantics or in several other ways. Quite often this is left out of the model - it is not always useful to go to that level of detail, so the implementations may just be hinted at in the documentation associated with the operation. But concrete classes in UML definitely have concrete behaviours associated with their operations, so the difference between UML and programming is that UML focuses on behaviour rather than implementation.
According to Wikipedia -
Unified Modeling Language (UML) is a standardized general-purpose
modeling language in the field of object-oriented software
engineering. The Unified Modeling Language includes a set of graphic
notation techniques to create visual models of object-oriented
software-intensive systems.
So, most important thing is UML is general-purpose and graphical. It is not only about classes and interfaces.
UML offers a standard way to visualize a system's architectural blueprints.
Software Construction Needs a Plan. Structure diagrams, Behavior diagrams, Interaction diagrams helps to Visualise In Multiple Dimensions and Levels of Detail which is
Appropriate For Both New and Legacy Systems.
Unified and Universal, Accommodates Parallel Development of Large Systems.
When I think of UML, one term which comes to mind is software quality. One thing that has plagued the software industry in recent year is poor software design. While the software industry has done fairly well for the last decade, the impact of globalization is changing the ways in which software is designed.

Dependency Injection & using interfaces?

I've noticed that a lot of developers define an interface for EVERY class that is going to be injected using DI framework. What are the advantages of defining Interfaces for every class?
Letting your application components (the classes that contain the application logic) implement an interface is important, since this promotes the concept of:
Program to an interface, not an implementation.
This is effectively the Dependency Inversion Principle. Doing so allows you to replace, intercept or decorate dependencies without the need to change consumers of such dependency.
In many cases developers will be violating the SOLID principles when having an almost only one-to-one mappings between classes and an interfaces in their applications. One of the principles that is almost certainly violated in that case is the Open/closed principle, because when every class has its own interface, it is not possible to extend (decorate) a set of classes with cross-cutting concerns (without dynamic proxy generation trickery that is).
In the systems I write, I define two generic interfaces that cover the bulk of the code of the business layer. They are called ICommandHandler<TCommand> and an IQueryHandler<TQuery, TResult>:
public interface ICommandHandler<TCommand>
{
void Handle(TCommand command);
}
public interface IQueryHandler<TQuery, TResult> where TQuery : IQuery<TResult>
{
TResult Handle(TQuery query);
}
Besides the nice side effect of not having to define many interfaces, this allows great flexibility and ease of testing. You can read more about it here and here.
Depending on the system I write, I might also use interfaces such as:
IValidator<T> for validating messages
ISecurityValidator<T> for applying security restrictions on messages
IRepository<T>, the repository pattern
IAuthorizationFilter<T> for applying authorization/security filtering on IQueryable<T> queries.
Depending on the system I write, somewhere between 80% and 98% of all components implement one of these generic interfaces I define. This makes applying cross-cutting concerns to those so called joinpoints trivial.
If you don't design to interfaces, you are going to be hamstrung when it comes time to refactor your code and/or add enhancements. Using a DI framework is not really at issue when it comes to designing to an interface. What DI gives you is late-binding and much better ability to write unit tests.

Use cases of Scala collection forwarders and proxies

Scala's collection library contains the forwarders IterableForwarder, TraversableForwarder, SeqForwarder and proxies like IterableProxy, MapProxy, SeqProxy, SetProxy, TraversableProxy, etc. Forwarders and proxies both delegate collection methods to an underlying collection object. The main difference between these two are that forwarders don't forward calls that would create new collection objects of the same kind.
In which cases would I prefer one of these types over the other? Why and when are forwarders useful? And if they are useful why are there no MapForwarder and SetForwarder?
I assume proxies are most often used if one wants to build a wrapper for a collection with additional methods or to pimp the standard collections.
I think this answer provides some context about Proxy in general (and your assumption about wrapper and pimping would be correct).
As far as I can tell the subtypes of Proxy are more targeted to end users. When using Proxy the proxy object and the self object will be equal for all intent and purposes. I think that's actually the main difference. Don't use Proxy if that assumption does not hold.
The Forwarder traits only seems to be used to support ListBuffer and may be more appropriate if one needs to roll out their own collection class built on top of the CanBuildFrom infrastructure. So I would say it's more targeted to library writers where the library is based on the 2.8 collection design.