Binding times can be classified between two types: static and dynamic. What is the difference between static and dynamic binding?
Could you give a quick example of each to further illustrate it?
In the most general terms, static binding means that references are resolved at compile time.
Animal a = new Animal();
a.Roar(); // The compiler can resolve this method call statically.
Dynamic binding means that references are resolved at run time.
public void MakeSomeNoise(object a) {
// Things happen...
((Animal) a).Roar(); // You won't know if this works until runtime!
}
It depends when the binding happens: at compile time (static) or at runtime (dynamic). Static binding is used when you call a simple class method. When you start dealing with class hierarchies and virtual methods, compiler will start using so called VTABLEs. At that time the compiler doesn't know exactly what method to call and it has to wait until runtime to figure out the right method to be invoked (this is done through VTABLE). This is called dynamic binding.
See Wikipedia article on Virtual tables for more details and references.
I came accross this perfect answer of a quora user "Monis Yousuf". He explain this perfectly. I am putting it here for others.
Binding is mostly a concept in object oriented programming related to Polymorphism.
Firstly, understand what Polymorphism is. Books say that it means "one name and multiple forms". True, but too abstract. Let us take a real-life example. You go to a "Doctor", a doctor may be an eye-specialist, ENT specialist, Neuro-Surgeon, Homeopath etc.
Here, a "doctor" is a name and may have multiple types; each performing their own function. This is polymorphism in real life.
Function Overloading: This concept depicts Static Binding. Function overloading may be roughly defined as, two or more methods (functions) which have the same name but different signatures (including number of parameters, types of parameters, differt return types) are called overloaded methods (or functions).
Suppose you have to calculate area of a rectangle and circle. See below code:-
class CalculateArea {
private static final double PI = 3.14;
/*
Method to return area of a rectangle
Area of rectangle = length X width
*/
double Area(double length, double width) {
return (length * width);
}
/*
Method to return area of circle
Area of circle = π * r * r
*/
double Area(double radius) {
return PI * radius * radius;
}
}
In above code, there are two methods "Area" with different parameters. This scenario qualifies as function overloading.
Now, coming to the real question: How is this static binding?
When you call any of the above functions in your code, you have to specify the parameters you are passing. In this scenario, you will pass either:
Two parameters of type double [Which will call the first method, to
calculate are of a rectangle]
Single parameter of type double [Which will call the second method, to calculate area of a circle]
Since, at compile time the java compiler can figure out, WHICH function to call, it is compile-time (or STATIC) binding.
Function Overriding: Function overriding is a concept which is shown in inheritance. It may roughly be defined as: when there is a method present in a parent class and its subclass also has the same method with SAME signature, it is called function overriding. [There is more to it, but for the sake of simplicity, i have written this definition] It will be easier to understand with below piece of code.
class ParentClass {
int show() {
System.out.println("I am from parent class");
}
}
class ChildClass extends ParentClass{
int show() {
System.out.println("I am from child class");
}
}
class SomeOtherClass {
public static void main (String[] s) {
ParentClass obj = new ChildClass();
obj.show();
}
}
In above code, the method show() is being overridden as the same signature (and name) is present in both parent and child classes.
In the third class, SomeOtherClass, A reference variable (obj) of type ParentClass holds the object of ChildClass. Next, the method show() is called from the same reference variable (obj).
Again, the same question: How is this Dynamic Binding?
At compile time, the compiler checks that the Reference variable is of type ParentClass and checks if the method show() is present in this class. Once it checks this, the compilation is successful.
Now, when the programs RUNS, it sees that the object is of ChildClass and hence, it runs the show() method of the ChildClass. Since this decision is taken place at RUNTIME, it is called Dynamic Binding (or Run-time Polymorphism).
Link for original answer
Static Binding: is the process of resolving types, members and operations at compile-time.
For example:
Car car = new Car();
car.Drive();
In this example compiler does the binding by looking for a parameterless Drive method on car object. If did not find that method! search for methods taking optional parameters, and if did not found that method again search base class of Car for that method, and if did not found that method again searches for extension methods for Car type. If no match found you'll get the compilation error!
I this case the binding is done by the compiler, and the binding depends on statically knowing the type of object. This makes it static binding.
Dynamic Binding: dynamic binding defers binding (The process of resolving types, members and operations) from compile-time to runtime.
For example:
dynamic d = new Car();
d.Drive();
A dynamic type tells the compiler we expect the runtime type of d to have Drive method, but we can't prove it statically. Since the d is dynamic, compiler defers binding Drive to d until runtime.
Dynamic binding is useful for cases that at compile-time we know that a certain function, member of operation exists but the compiler didn't know! This commonly occurs when we are interoperating with dynamic programming languages, COM and reflection.
Binding done at compile time is static binding and binding done at run time is dynamic binding.In static binding data type of the pointer resolves which method is invoked.But in dynamic binding data type of the object resolves which method is invoked.
* Execution time:-* bindings of variables to its values,as well as the binding of variable to particular storage location at the time of execution is called execution time binding.
IT MAY BE OF TWO TYPES
on entry to a subprogram.
At arbitrary points during execution time.
COMPILE TIME BINDING :- (TRANSLATION TIME)
It consist of the following.
Binding chosen by programmer.
Binding chosen by the translator.
Binding chosen by the loader.
Related
I am aware that a variable can be dynamically typed with the def keyword in Groovy. But I have also noticed that in some circumstances it can be left out, such as when defining method parameters, eg func(p1, p2) instead of func(def p1, def p2). The latter form is discouraged.
I have noticed that this is extendable to all code - anytime you want to define a variable and set its value, eg var = 2 the def keyword can be safely left out. It only appears to be required if not instantiating the variable on creation, ie. def var1 so that it can be instantiated as a NullObject.
Is this the only time def is useful? Can it be safely left out in all other declarations, for example, of classes and methods?
Short answer: you can't. There are some use cases where skipping the type declaration (or def keyword) works, but it is not a general rule. For instance, Groovy scripts allow you to use variables without specific type declaration, e.g.
x = 10
However, it works because groovy.lang.Script class implements getProperty and setProperty methods that get triggered when you access a missing property. In this case, such a variable is promoted to be a global binding, not a local variable. If you try to do the same on any other class that does not implement those methods, you will end up getting groovy.lang.MissingPropertyException.
Skipping types in a method declaration is supported, both in dynamically compiled and statically compiled Groovy. But is it useful? It depends. In most cases, it's much better to declare the type for a better readability and documentation purpose. I would not recommend doing it in the public API - the user of your API will see Object type, while you may expect some specific type. It shows that this may work if your intention is to receive any object, no matter what is its specific type. (E.g. a method like dump(obj) could work like that.)
And last but not least, there is a way to skip type declaration in any context. You can use a final keyword for that.
class Foo {
final id = 1
void bar(final name) {
final greet = "Hello, "
println greet + name + "!"
}
}
This way you can get a code that compiles with dynamic compilation, as well as with static compilation enabled. Of course, using final keyword prevents you from re-assigning the variable, but for the compiler, this is enough information to infer the proper type.
For more information, you can check a similar question that was asked on SO some time ago: Groovy: "def" keyword vs concrete type
in Groovy it plays an important role in Global and Local variable
if the variable name is same with and without def
def is considered local and without def its global
I have explained here in detail https://stackoverflow.com/a/45994227/2986279
So if someone use with and without it will make a difference and can change things.
It is a Sequence Diagram HowTo question, not a HowTo code.
I am using Visio 2010 and developing >> reverse engineering from Microsoft Dynamics AX 2012 / X++. Yes people its all about how to map static on UML.
My class is instantiated from FORM using at its void static main(). This calls another static method, say construct() which returns an instance of the same class.
I want to show the class (in static methods) and the resulting object separately some like the meta class runs (self msgs) and finally produces the class object which finally takes over. But how will a self msg call return a value ? How do I connect it with the resulting object of the class ? I hope I make enough sense to make you guys understand.
Note, the class is not a static class, but it has a static constructor.
If you want to depict a call to constructor (i.e. static operation that is responsible for creating an object and (usually) returning it as a reply) then you have to use a createMessage construct i.e. a dashed line with an open arrow and the word create on it. While this is not directly stated in specification, usually in such case the arrow points on the lifeline box (rectangle) rather than a line itself (however I've seen information that both notations are correct).
Note that in this case the logic of constructor is hidden (encapsulated) which is a good idea in general.
You can find more details in UML specification in section 17.4, especially 17.4.4.1 and an example in section 17.6.5 on Figure 17.14.
If you want to use a static operation other than constructor and call it without a use of class instance you have to model class as object (after all class is an object itself at least on analytical level). Note that the type of message can be either synchronous or asynchronous depending on your needs.
With this approach you can provide details on how the class handles this function (i.e. what other calls does it make).
For more details see "Applied UML and Patterns" by Craig Larman, section 15.4, Figure 15.20. Note however that Larman suggest a use of <<metaclass>> stereotype. Yet the called object is a class (metaclass is a class whose instance is class so this is not our case) so the stereotype should be <<class>>.
This is what I am trying to do:
public void method(int myVal, string myOtherVal)
{
// doing something
}
dynamic myVar = new SomeDynamicObjectImplementer();
method(myVar.IntProperty, myVar.StringProperty);
Note that my properties are also DynamicObjects. My problem is that the TryConvert method is never called and that I get a runtime error saying the method signature is invalid.
The following is working great:
string strVar = myVar.StringProperty;
int intVar = myVar.IntProperty;
And I would like to avoid
method((int)myVar.IntProperty, (string)myVar.StringProperty);
Is it possible to override something in DynamicObject to allow this? (or something else)
Thank you
The problem is your assumption that it will try a dynamic implicit convert on arguments of an dynamic invocation to make a method call work, this is not true.
When your arguments aren't statically typed, it will use the runtime type to find the best matching method (if the runtime type matches the static rules for implicit conversion to the argument type this will work too), since your your IntProperty,StringProperty seem to be returning a DynamicObject rather than an Int and a String or something that could statically be converter implicitly, this lookup will fail.
If SomeDynamicObjectImplementer could actually return an Int for IntProperty and a String for StringProperty your method call for without casting would actually work. It's also probably a better dynamic typing practice if you data type is based on the actually type of data rather than usage using try convert. You could add actually implicit convert methods for every possible type that you could return to that returned DynamicObject type, but that could cause strange resolution issues to depending on how much you are overloading.
However, another option to keep your dynamic implementation the same is to mix a little controlled static typing in, you can use ImpromputInterface (in nuget) to put an interface on top of a dynamic object, if you do that then the TryConvert method would be called on your returned DynamicObjects.
public interface ISomeStaticInterface{
int IntProperty {get;}
string StringProperty {get;}
}
...
var myVar = new SomeDynamicObjectImplementer().ActLike<ISomeStaticInterface>();
method(myVar.IntProperty, myVar.StringProperty);
Instead of using myVar.IntProperty can't you just put them in variables first, like you already did, and then use then for your method?
so method(intVar , strVar); seems fine. At least more elegant than casting.
Of course, if you're already certain your object will have IntProperty and StringProperty, why not just make an actual object with those properties instead?
Why are you doing the cast?
method(myVar.IntProperty, myVar.StringProperty);
should compile.
If the two properties must be the types suggested by the names then they shouldn't be dynamic.
I'm in a situation where I need to return an object of an anonymous type from a method, is it a good idea to use dynamic as a return type? what considerations to take?
public dynamic MyMethod()
{
// process and return the object of an anonymous type
}
It doesn't make any sence, you can return object with the same effect.
P.S.: Also anonymous types are not that good as return types.
Yes it has sense If you "guarantee" that you'll always return an object with some characteristics , with an Id for example (ignoring that perhaps it would be better to use an Interface)
public dynamic MyMethod()
{
var temp = new ExpandoObject();
temp.Id = 5;
return temp;
}
Console.WriteLine(MyMethod().Id);
So if you guarantee that all your objects can Turn Left-Right but you don't guarantee if they are airplanes, cars, motos, boats. (so it's good if you are doing Duck typing When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.)
Note that if you then need to reflect on your objects, it can become ugly: How do I reflect over the members of dynamic object?
Returning a dynamic object does have the benifit of allowing you to access the properties from the anonmymous type without using reflection (albeit without intellisense). If you take this approach you need to make sure that the properties on the anonymous type match what you are accessing on the dynamic object. Otherwise you will get runtime errors
However, I would suggest you consider returning a concrete type instead
I'm using code contract (actually, learning using this).
I'm facing something weird to me... I override a method, defined in a 3rd party assembly. I want to add a Contract.Require statement like this:
public class MyClass: MyParentClass
{
protected override void DoIt(MyParameter param)
{
Contract.Requires<ArgumentNullException>(param != null);
this.ExecuteMyTask(param.Something);
}
protected void ExecuteMyTask(MyParameter param)
{
Contract.Requires<ArgumentNullException>(param != null);
/* body of the method */
}
}
However, I'm getting warnings like this:
Warning 1 CodeContracts:
Method 'MyClass.DoIt(MyParameter)' overrides 'MyParentClass.DoIt(MyParameter))', thus cannot add Requires.
[edit] changed the code a bit to show alternatives issues [/edit]
If I remove the Contract.Requires in the DoIt method, I get another warning, telling me I have to provide unproven param != null
I don't understand this warning. What is the cause, and can I solve it?
You can't add extra requirements which your callers may not know about. It violates Liskov's Subtitution Principle. The point of polymorphism is that a caller should be able to treat a reference which actually refers to an instance of your derived class as if it refers to an instance of the base class.
Consider:
MyParentClass foo = GetParentClassFromSomewhere();
DoIt(null);
If that's statically determined to be valid, it's wrong for your derived class to hold up its hands and say "No! You're not meant to call DoIt with a null argument!" The aim of static analysis of contracts is that you can determine validity of calls, logic etc at compile-time... so no extra restrictions can be added at execution time, which is what happens here due to polymorphism.
A derived class can add guarantees about what it will do - what it will ensure - but it can't make any more demands from its callers for overridden methods.
I'd like to note that you can do what Jon suggested (this answers adds upon his) but also have your contract without violating LSP.
You can do so by replacing the override keyword with new.
The base remains the base; all you did is introduce another functionality (as the keywords literally suggest).
It's not ideal for static-checking because the safety could be easily casted away (cast to base-class first, then call the method) but that's a must because otherwise it would violate LSP and you do not want to do that obviously. Better than nothing though, I'd say.
In an ideal world you could also override the method and call the new one, but C# wouldn't let you do so because the methods would have the same signatures (even tho it would make perfect sense; that's the trade-off).