Is there a difference between casting to Interface and to a contract instance? - interface

In solidity, most smart contracts cast external contract calls to interfaces (IERC20 vs. ERC20). Is there any difference casting between the two?
For example, if I write
IERC20 Token = IERC20(tokenContractAddress);
Is there any functional difference to
ERC20 Token = ERC20(tokenContractAddress);?
Just curious if there are factors to consider in terms of gas costs, compatibility issues, etc. Thanks!

If you just want to access the functions, you can use either. But in interfaces you cannot have state variables so if you need some state variables you cast to contract.
Also interfaces cannot inherit other contracts or interfaces. Maybe the contract is inheriting from contractB and in your contract you want to access to contractB.

Related

Why use interfaces

I see the benefit of interfaces, to be able to add new implementations via contract.
I dont see following problem:
Imagine you have interface DB with method "startTransaction".
Everything is fine you implement it in MySQL, PostgreSQL. But tomorrow you move to mongodb - then you have no transaction support.
What do you do?
1) Empty method - bad because you think you have transactions but u havent
2) Create your own - then you should have some parameters that will be different that regular "startTransaction" method.
And on top of that sometimes simple interfaces just doesnt work.
Example: You need additional parameters for different implementations.
If you're exposing the concept of transactions on your interface, then you must functionally support transactions no matter what, since users of the interface will logically depend on it. I.e., if a caller can start a transaction, then they expect to also be able to roll back a transaction of several queries. Since Mongo doesn't natively have any concept of rolling back transactions, there's one of two possibilities:
You implement the possibility of rolling back queries in code, emulating the functionality of transactions for a database which doesn't natively support it. (Whether that's even reliably possible in Mongo is a debatable topic.)
Your interface is working at the wrong level of abstraction. If your interface is promising functionality an implementation can't deliver, then either the interface or the implementation is unrealistic.
In practice, Mongo and SQL databases are such different beasts that you would either never make this kind of change without changing large parts of your business logic around it; or you specify your interface using an extremely minimal common-denominator interface only, most certainly not exposing technology-specific concepts on an abstract interface.
You are mostly correct, interfaces can be very useful, but also problematic in (fast) changing code, a best practice conserning interfaces is to keep them as small as possible.
When something can handle an transaction, create an interface only for handling an transaction. Split them up in as small as logically possible parts, in that way, when new classes emerge, you can assign them the specific interfaces that can determine their methods.
For the multiple parameter problem, this can indeed be problematic, see if you can determine if this specific value could be moved to a constructor, or indicates that the action that you are doing is indeed sightly different from the action that does not need this parameter.
I hope this helps, goodluck
You are right interfaces are used to add new implementations via contract but those implementations have to posses some similarity.
Let's take an example:
You cannot implement dog using human interface because dog is a living organism.
Same thing you are trying to do here.You are trying to implement a non-sql db using sql db implementation.

UML software design (specifically Abstract classes)

When designing software (think UML diagrams for example) and real world objects.
How does one identify a suitable case for an Abstract class?
For example if we had an [Employee] and [Fireman] and [paidFireman] and [unpaidFireman]...I am having trouble seeing whether a Fireman or Employee should be abstract and why?
Abstract classes are one of those more esoteric constructs in UML. Since classes are already an abstraction of real world things, an abstract class is even one level higher. Abstract classes can not be instantiated (since it is assumed they miss something for a real life). Whether you say that Fireman is abstract while the paid/unpaid are not, is a pure point of view and must be argued in the specific domain.
As a rule of thumb: leave abstract classes out of the door until you come to a point where you feel the urgent need for it. Introducing abstractness limits your model (and can help to avoid some malformed results of it). But without those limits the model is still valid as long as the architect sticks to common sense rules.
It mainly depends on your functional requirements.
If it makes sense in your application just to have simple employees (without designating them as firemen, policemen, or craftsmen), then the class may not be abstract, as the application will have to make instances just of the Employee class.
If that doesn't make sense, i.e. the occupation of each of your employees needs to be known at creation time, abstract classes come into consideration. But still they aren't necessary in every case. The easiest way to make sure the occupation is known is to model it as a mandatory attribute. Introducing a subclass only makes sense if there is specialized behavior for each of those subclasses. If, e.g., the salary of the firemen is calculated as 50$ * count of the fires he exstinguished, but the salary of the policemen is 1000$ + 50 * rank, then you model an abstract operation getSalary() in the Employee class, which will be concretely specified and implemented in each of the subclasses.
As the concept of interface also got mentioned in one of the answers, an interface describes the obligation to implement certain operations in all classes realizing that interface. That's much the same as an abstract operation in an abstract class. But the abstract class can contain much more than an interface: attributes and non-abstract operations.
So the rule of thumb is: For concepts of your domain for which interface and behavior can be fully described, use non-abstract classes. For concepts for which only interfaces and no behavior can be described, use interfaces. For concepts for which interfaces and part of the behavior can be described, use abstract classes.
There are many uses for an abstract class. An abstract class is one that cannot have any direct instances.
In software design, it is one way to describe an interface. Some of the declared operations can be implemented in the superclass. Any remaining implementations must be specified in sub-classes. Regardless of where the implementations exist, an abstract class means there can be no direct instances, only instances of some non-abstract subclass.
In a domain analysis, an abstract class is a way of modeling an abstraction. For example, think of the abstraction Role. It is useful to say that a Person plays a number of Roles. However, there is no instance of a Role that makes sense, without it also being a more specific kind of Role, such as Employee, Fireman, or Teacher. For this situation, you not only want Role to be abstract, you also want a covering axiom. For more on that, please read https://stackoverflow.com/a/35950236/2596664.

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).

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.

Interface doubts

Are interfaces a layer between objects(different objects) and actions(different object types trying to perform same action)? and Interface checks what kind of object is it and how it can perform a particular action?
I'd say that it's better to think of an interface as a promise. In Java there is the interface construct that allows for inheritance of an API, but doesn't specify behavior. In general though, an interface is comprised of the methods an object presents for interacting with the object.
In duck-typed languages, if an object presents a particular set of methods (the interface) specific to a particular class, then that object is like the specifying class.
Enforcement of interface is complicated, since you need to specify some set of criteria for behavior. An interesting example would the design-by-contract ideas in Eiffel.
Are you asking about the term "interface" as used in a specific language (such as Java or Objective-C), or the generic meaning of the term?
If the latter, then an "interface" can be almost anything. Pour oil on water -- the line between them is an "interface". An interface is any point where two separate things meet and interact.
The term does not have a rigorous definition in computing, but refers to any place where two relatively distinct domains interact.
To understand interfaces in .net or Java, one must first recognize that inheritance combines two concepts:
Implementations of the derived type will include all fields (including private ones) of the base type, and can access any and all public or protected members of the base type as if it were its own.
Objects of the derived type may be freely used in place of objects of the base type.
Allowing objects to use members of more than one base type as their own is complicated. Some languages provide ways of doing so, but there can often be confusion as to which portion of which base object is being referred to, especially if one is inheriting from two classes which independently inherit from a third. Consequently, many frameworks only allow objects to inherit from one base object.
On the other hand, allowing objects to be substitutable for more than one other type of object does not create these difficulties. An object representing a database table may, for example, allow itself to be passed to a routine that wants a "thing that can enumerate contents, which are of type T (IEnumerable<T> in .net)", or a routine that wants a "thing that can have things of type T added to it" (ICollection<T> in .net), or a thing that wants a "thing that wants to know when it's no longer needed (IDisposable in .net)". Note that there are some things that want notification when they're no longer needed that do not represent enumerable collections, and there are other things that represent enumerable collections that can be abandoned without notification. Thus, neither type of object could inherit from the other, but if one uses an interface to represent "things which can enumerate their contents, which are of type T", or "things that want to know when they are no longer needed", then there's no problem having classes implement both interfaces.