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

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.

Related

why static dispatch so quickly in 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.

Characteristics of a class

In OOP, class fields are characterized with several mutually exclusive options:
public vs private
final vs changeable (?)
static vs instance
Are there any other important characteristics of classes in Java or other common OOP languages, such as C++ and C#?
In programming, object oriented programming is a tool that has unleashed the real power of computing. OOP allows a programmer to define their own types and subsets of variables that they are able to use. Types like integers, doubles, strings, are all defined as a certain set of bits in the computers memory, so OOP gives a programmer the power to create their own types of mailable objects that can have different characteristics.
Public vs Private
These words reference the access that one has to variables and methods within a certain class. Public variables and methods are accessible anywhere meaning they can be called outside of the class that it exists in. Private methods and variables on the other hand, can only be called in the class where they exist.
Eg:
public class Vehicle{
private int milesPerGallon;
public int getMPG{
return this.milesPerGallon;
}
}
Vehicle car1 = new Vehicle();
In this example, the variable milesPerGallon is private while the accessor method (getMPG()) that returns this value is public. So, in order to get the miles per gallon for the car1 object, the programming could not call car1.milesPerGallon. They would instead have to call car1.getMPG() because that method is public.
The use of private variables may seem counterintuitive, but private class members are a way to manage complexity. If all members were public, then bugs and problems in code could be linked to any one of these public members. It is difficult to trace back problems to public members becasue they can be called anywhere. If something were to happen to a pri
A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort by a factor of 1000.
-tdammers
Final vs Changeable
These two concepts refer to the malleability of variables within a class. If a member is final, this means that it cannot be changed later in the program. But without the final keyword, then the variables are free to change at any time. Say for example, you were writing a cash register class.
public class Register{
private final double valueOfPenny = .01;
private final double valueOfNickel = .05;
ect...
private int numberOfPennies;
private int numberOfNickels;
ect...
}
In the Register class you will obviously need to know the value of a penny, nickel, dime, ect. But these values are going to stay constant through out the program. So we can set the value of each coin to be a final variable so that it does not accidentally get changed on accident. On the other hand, the number of each coin inside of the register may change through out the program, so we cannot make these variables final.
Static vs Instance
A instance variable means that every object has its own copy of each instance variable. An easy way to remember this is to think that every instantiation of a variable has a copy of the instance variable in a class. By default, all variables of a class are instance variables.
Static variables on the other hand, belong only once to the entire class. No matter how many instantiations of the class have been made, the static variable still only belongs to the class as a whole.
Eg:
public class Vehicle{
private double milesPerGallon;
public static int numberOfVehicles;
}
Vehicle car1 = new Vehicle();
Vehicle car2 = new Vehicle();
Both car1 and car2 have a variable called milesPerGallon. This makes sense because different instances of the Vehicle class will have different values of MPG. But, the variable numberOfVehicles is static because it only acts as a counter for how many vehicles there are. Every vehicle does not need to know this information because it is pointless for car1 and car2 to know that there are 2 vehicles. Only the class must know the value of this variable.
Constructors
You asked if there was any additional information about OOP that would be important and I feel as if constructors are at the top of the list. The constructor is a method that gets called whenever a programmer makes a copy of a class. In other words, whenever the programmer makes a call and instantiates a class, the constructor is the first and only method that gets called. In Java, the constructor is required and the name of the constructor is the same name as the class. If you do not provide Java with a constructor, then it will generate a blank constructor for you. But the power of the constructor is very useful and should often be utilized. Let's go back to the Vehicle example. Let's say you want to make a vehicle that has a certain manufacturer and the year it was made. You can save these two pieces of information as private instance variables as we mentioned above. But every time a Vehicle object is created, you want these two variables to be set right away. (i.e. you want to construct the object).
public class Vehicle{
private makeOfVehicle;
private yearOfVehicle;
public Vehicle(String make, int year){ //constructor
this.makeOfVehicle = make;
this.yearOfVehicle = year;
}
}
Vehicle car1 = new Vehicle("Toyota",2005);
Vehicle car2 = new Vehicle("BMW",2002);
By using the constructor, you can set attributes of objects as they are created!
Please let me know if you have any questions concerning these concepts/code or any other OOP concepts

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.

What is the philosophy behind making instance variables public by default in 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.