why static dispatch so quickly in swift - swift

I know that there is a methods list in class. And I also know the mechanism of dynamic dispatch. But I confused with static dispatch. Where are static methods in. Whether static methods in a global hash table. And how does the static dispatch work. What does the flow like.

You are confusing two separate concepts.
Static dispatch refers to the way a method body is called at runtime. If you have a class that could potentially have subclasses or any object where all you know about it is that it conforms to a certain protocol, you have to use dynamic dispatch, which means you have to look up the address of the method in a table (called a vtable or a witness table) and then jump to that location. If the compiler knows exactly what kind of object it has, e.g. a struct, a final class or a final method in a class, it knows the method cannot be overridden and can therefore directly jump to its address without doing the lookup.
A method that is declared static is a type method. It will be called on the type itself rather than an instance of the type i.e. inside the method self refers to the type not an instance of the type.
static methods can't be overridden so the compiler always knows the address at compile time and will use static dispatch for them. There's no need for any kind of hash table or witness table.

Related

What are some use cases for static methods and properties in classes?

PowerShell classes can contain static methods and properties:
class stack {
[string]
$name
[DateTime]
static $date = (GET-DATE)
stack($name) {
$this.name = $name
}
static [void] hello() {
Write-Host 'hello'
}
}
A couple use cases I've found so far for static methods:
organize my functions within a common context of a class.
I believe I have read somewhere that static methods are much more performant than functions. I've never verified it myself, though.
And for static properties:
They define variables that can be called from any scope, especially from within other classes without needing to pass the variable into the class as an argument.
I have the feeling that my reasons for using static methods / properties are pretty underdeveloped. Static properties in particular seem like more laborious alternatives to simple variables, although the omni-scope availability is very nice if you do run into that use case.
So my questions:
What use cases have you found for static methods/properties?
Does it ever make sense to set a static property without a default value?
Since PowerShell was given, I will give a .NET-centric answer.
Ultimately the details will vary from language to language, but static class instances are typically instantiated only once the first time a static member is called on it. This means you will have a single instance created for any code which needs to call it. Conversely, being able to call the constructor of a non-static class means you can create as many instances as times you can call the constructor. For classes with both static and non-static members, the static members are still only created a single time in memory for the static instance.
Create static methods if the method does not rely on instance data to get the job done. For example, a string class might include static utility methods that still require a source string to be passed in. Let's look at the signature of the built-in String.IsNullOrEmpty static method:
[string]::IsNullOrEmpty
# OverloadDefinitions
# -------------------
# static bool IsNullOrEmpty(string value)
IsNullOrEmpty makes sense to define as static because it does not make sense to have it operate on an instantiated string object instead. Think about what the method does. It checks for:
A null value; or
A value of [string]::Empty
It is a utility method in order check the conditions above against another string. If this were not a static method, we cannot check for a null string as the instance doesn't exist(you can't call a method on a null-valued expression). Even if we could have a null string and call the method, we would first need to create a string object to use it, which would allocate memory for IsNullOrEmpty for every single string object. None of this is efficient considering it's a utility method that can easily have a valid string passed into it.
The main benefit here is that you do not need to allocate memory for every static method for every string object created. As explained above, the static methods are instantiated only once for the static instance.
The same goes for properties, although oftentimes static properties are read only. One example might be a System Properties class, and the OS version may be a static string. Consider the static property I used above, [string]::Empty. If this were not a static property, we run into the same pitfalls as defining IsNullOrEmpty as a non-static member: it will get allocated more often than it needs to be, and we need to first create a non-null instance to use it. The latter occurs with static classes behind the scenes, so you are free to use static members without worrying about initialization or instantiation.
Note: Create a static class if all the members are planned to be static, as it does not make sense to create an instance when it would hold no stateful information. Static classes in .NET are classes that cannot be directly instantiated, except for a single static constructor.
To summarize, it's mostly about memory management. Static members are only created once during the lifetime of the program, while instance (non-static) members are created for each instance of the object created with new.

Why can't non-nullable fields be initialized in a constructor body in Dart?

Often times I have an instance field that needs to be initialized in a constructor. For example, it might be needed to be calculated based on other instance fields, hence I can't initialize it inline (where declared) or with a constructor initializer list.
But it either has to be nullable, or declared late, if I need to initialize it in constructor. The rationale behind late keyword is that programmer states "I'll initialize this before using, trust me", when it can not be determined by the compiler that initialization will take place before first usage. BUT: this "programmer guarantee" seems A) terrible and B) unnecessary in case of constructors, because it can be determined by compiler whether the field was initialized in a constructor (and constructor itself is obviously guaranteed to execute before any other instance methods).
Obvious downside to using late fields in such scenarios is that nothing enforces them compile-time to be actually initialized during construction (or anywhere, for that matter). Plus, every time the late field is read, a runtime check is inserted to make sure it has been assigned a value - I don't need that when I initialize in constructors.
Therefore, it seems that, technically it should be possible to have non-nullable non-late fields that are initialized within a constructor body (and if they are not - compiler can throw an error).
So what is the rationale of requiring constructor-initialized fields to be either nullable, or declared as late? Is there a technical reason why this limitation is imposed, or is it just a design oversight by the Dart team?
Dart executes constructor bodies inside-out, from base class to derived class. This allows virtual dispatch to occur in the constructor body. The fact that virtual dispatch can occur in the constructor body means that the compiler cannot statically determine what code will be executed by the constructor body, and therefore it cannot deduce what the constructor body might ultimately initialize.
That the constructor body can execute arbitrary code (including callbacks) that might initialize members or that might depend on initialized members makes it even more complicated.
Furthermore, allowing members to be not initialized when the constructor body runs would be error-prone and a source for confusion. For example, with:
class SomeClass {
int member;
SomeClass() {
updateMember(0);
}
void updateMember(int value) {
print(value); // Oops.
member = value;
}
}
With Dart's current design, all instance methods (and their overrides) can be guaranteed that members are initialized when the method is called. If members were allowed to be uninitialized when the constructor body is executed, that would not longer be true, and all instance methods then would need to consider if they might be invoked from the constructor (or from a base class constructor), possibly indirectly from other method calls, and whether accessed members might not be initialized yet.
(I'll grant that that previous point isn't terribly strong since it currently can still happen that a member is initialized to an object that the constructor body must mutate, but typically instance methods receiving an empty List, Map, etc. is less of a problem than receiving uninitialized members. The above situation also could happen with late members, but that's the baggage that comes with choosing to use late.)
Null-safety disallows the possibility of accessing uninitialized non-late variables, but your proposal would make that possible.
Also, because there is a distinction between initializing members via an initializer list and via a constructor body, people are encouraged to use initializer lists when possible.
The point that you are ignoring here is that when you want to pass a variable to a constructor you will definitely initialize it, otherwise you wouldn't be able to use that widget because you have to pass the variables needed to its constructor. so this late or nullable keywords can be used for the values that you are trying to pass to a widget and not in the widget itself that you are passing them to, but before it.

ABAP CALL METHOD: meaning of 'static' and 'dynamic'

I'm a little confused about the meaning of terms 'static' and 'dynamic' w.r.t. CALL METHOD in ABAP.
On the one hand, static refers to components of a class that can be accessed without instance. Dynamic refers to access via the content of a field at runtime.
So, (class)=>(meth) would be a dynamic call to a static method?!
What are the inverse terms then?
one meaning of dynamic is: (meth_name) meth_name expects a character-like field that must contain the name of a method when the statement is executed. Consequently, oref->meth is a static method call
A static component comp of a class can be accessed using the name class=>comp. Here, a component can be a method
Static have two meanings:
The methods (and attributes) of a class are either static or instance. In the latter case an instance of the class has to exist, to be able to call an instance method or access and instance attribute of the class. The syntax is different:
call an instance method: oref->method
call a static method: class=>method
Similarly for attributes:
static: class=>attribute
instance: oref->attribute
On the other hand the call of the method can be either static or dynamic.
Static call of a method:
oref->method (1) (or class=>method (2) )
Dynamic call of a method: oref->(method) (3) (or class=>(method) (4) )
To be exact:
(1) Static call of an instance method
(2) Static call of a static method
(3) Dynamic call of an instace method
(4) Dynamic call of a static method

Can one declare a static method within an abstract class, in Dart?

In an abstract class, I wish to define static methods, but I'm having problems.
In this simple example
abstract class Main {
static String get name;
bool use( Element el );
}
class Sub extends Main {
static String get name => 'testme';
bool use( Element el ) => (el is Element);
}
I receive the error:
function body expected for method 'get:name' static String get name;
Is there a typo in the declaration, or are static methods incompatible with abstract classes?
Dart doesn't inherit static methods to derived classes. So it makes no sense to create abstract static methods (without implementation).
If you want a static method in class Main you have to fully define it there and always call it like Main.name
== EDIT ==
I'm sure I read or heard some arguments from Gilad Bracha about it but can't find it now.
This behaviour is IMHO common mostly in statically typed languages (I don't know many dynamic languages). A static method is like a top level function where the class name just acts as a namespace. A static method has nothing to do with an instantiated object so inheritance is not applicable. In languages where static methods are 'inherited' this is just syntactic sugar. Dart likes to be more explicit here and to avoid confusion between instance methods and static methods (which actually are not methods but just functions because they don't act on an instance). This is not my primary domain, but hopefully may make some sense anyways ;-)
Looks like you are trying to 'override' a static method. I'm not sure what you are trying to achieve there. I'm not aware of any OO languages that support that (and not sure how they could).
A similar question in Java might help clarify Polymorphism and Static Methods
Note also that it is considered bad practice to refer to statics from an instance of the class in Java (and other OO languages). Interestingly I noticed Dart does not let you do this so is in effect removing this bad practice entirely.
So you couldn't even fool yourself into thinking it would behave polymorphically in Dart because you can't call the static from the instance.

Static variable in ObjectiveC

Static variables are variables allocated statically at compile time. My doubt is for what purpose some variables are declared statically? I didn't have used any static variable in my code till now. From the apple code http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Introduction/Intro.html
in securityWrapper.m, there is a line
static SecKeyWrapper * __sharedKeyWrapper = nil;
what is the use of statically allocating __sharedKeyWrapper here?
I have seen the use of static key word in so many codes. So kindly explain the use and benefits when static keyword.
Thanks in advance.
That file global is a singleton, used for sharing an instance of a class.
The reason it's static in Objective-C is internal linkage. In practice, this means the variable can not be seen outside the file it is declared in. If another file declares a variable with the same name, they're two different variables.
Keep in mind that the way Objective-C instances work, the instance won't actually be allocated automatically. Rather, you have a pointer to the instance. The code will still have to do something like:
if ( !_sharedKeyWrapper ) {
_sharedKeyWrapper = [[SecKeyWraper alloc] initBlahBlah];
}
See links for more.
When you define a new class of objects, you can decide what instance
variables they should have. Every instance of the class will have its
own copy of all the variables you declare; each object controls its own
data.
However, you can't prescribe variables for the class object; there are
no "class variable" counterparts to instance variables. Only internal
data structures, initialized from the class definition, are provided for
the class. The class object also has no access to the instance variables
of any instances; it can't initialize, read, or alter them.
Therefore, for all the instances of a class to share data, an external
variable of some sort is required. Some classes declare static variables
and provide class methods to manage them. (Declaring a variable static
in the same file as the class definition limits its scope to just the
class-and to just the part of the class that's implemented in the file.
Unlike instance variables, static variables can't be inherited by
subclasses.)
Static variables help give the class object more functionality than just
that of a "factory" producing instances; it can approach being a
complete and versatile object in its own right. A class object can be
used to coordinate the instances it creates, dispense instances from
lists of objects already created, or manage other processes essential to
the application. In the case when you need only one object of a
particular class, you can put all the object's state into static
variables and use only class methods. This saves the step of allocating
and initializing an instance.
Also static variables are initialized once. You can use static variables in recursive calls. Simple Example Factorial.