Static Members in a Global class - class

export class Globals
{
static m_Name : string = "Hello world";
static m_Version : number = 1.0;
static m_Canvas : HTMLCanvasElement = null;
static m_Foo : Foo = null;
}
public OnDocumentLoad() : void
{
Globals.m_Canvas = <HTMLCanvasElement>document.getElementById('myCanvas');
Globals.m_Foo = new Foo(m_Name, m_Version);
}
Is this acceptable use of static in TypeScript? I'm unsure of what static is doing in this case other than making the member variables class members that everyone can access regardless of instance. But, for example, is m_Foo and m_Canvas valid instances within the Globals class, kind of like singletons so to speak (without any undefined checking and presumably anytime after OnDocumentLoad of course)
Originally I didn't have Globals as a class and they were just generic var declarations I had in a .ts file I was referencing everywhere. But I wanted to organize them into a nice little Globals class. This works in my experience testing it so far, but I wanted to see if there was anything I was missing about what static is doing here.
The most I found on the subject was here in the Specification:
http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf
Member declarations with a static modifier are called static member declarations. Static property
member declarations declare properties in the constructor function type (section 8.2.5), and must specify
names that are unique among all static property member declarations in the containing class, with the
exception that static get and set accessor declarations may pairwise specify the same name.
Note that the declaration spaces of instance and static property members are separate. Thus, it is possible
to have instance and static property members with the same name
From that I gleam that you can make an instance of Globals and its members will have a different meaning from just calling the Globals.m_Name for example, but I don't intend to do that here.

If you want to create a namespace object, use module:
export module Globals
{
export var m_Name : string = "Hello world";
export var m_Version : number = 1.0;
export var m_Canvas : HTMLCanvasElement = null;
export var m_Foo : Foo = null;
}

Related

Creating namespaces with classes in Swift

I am a newb to Swift, I am looking to create some nested namespaces, like so:
import Foundation
public class Foo {
class Moo {
class Bar{}
}
}
and then I can do:
var f = Foo.Moo.Bar()
do we not need to use the static keyword here? I don't understand why I don't need to do it like so:
import Foundation
public class Foo {
static class Moo {
static class Bar{}
}
}
var f = Foo.Moo.Bar()
can anyone explain why?
Foo.Moo.Bar is just the name of the class. You're not accessing a particular instance of Foo or Moo when you do this:
var f = Foo.Moo.Bar()
You're just creating an instance of the Foo.Moo.Bar class.
can anyone explain why?
Can you explain why not? What would a static class even mean? How can a class be static? Maybe you come from a language where that keyword means something special in this context?
In any case, in Swift it wouldn't mean anything. The word static has just one very simple meaning in Swift: A type member, i.e. a property (var or let) or method (func) is either an instance member or a type member; to distinguish the latter case, we say static (or class). This is neither of those. It is, as you rightly say, merely a namespaced type.

How can I give clients read-access to an array in Swift? [duplicate]

In Swift, what is the conventional way to define the common pattern where a property is to be externally readonly, but modifiable internally by the class (and subclasses) that own it.
In Objective-C, there are the following options:
Declare the property as readonly in the interface and use a class extension to access the property internally. This is message-based access, hence it works nicely with KVO, atomicity, etc.
Declare the property as readonly in the interface, but access the backing ivar internally. As the default access for an ivar is protected, this works nicely in a class hierarchy, where subclasses will also be able to modify the value, but the field is otherwise readonly.
In Java the convention is:
Declare a protected field, and implement a public, read-only getter (method).
What is the idiom for Swift?
Given a class property, you can specify a different access level by prefixing the property declaration with the access modifier followed by get or set between parenthesis. For example, a class property with a public getter and a private setter will be declared as:
private(set) public var readonlyProperty: Int
Suggested reading: Getters and Setters
Martin's considerations about accessibility level are still valid - i.e. there's no protected modifier, internal restricts access to the module only, private to the current file only, and public with no restrictions.
Swift 3 notes
2 new access modifiers, fileprivate and open have been added to the language, while private and public have been slightly modified:
open applies to class and class members only: it's used to allow a class to be subclassed or a member to be overridden outside of the module where they are defined. public instead makes the class or the member publicly accessible, but not inheritable or overridable
private now makes a member visible and accessible from the enclosing declaration only, whereas fileprivate to the entire file where it is contained
More details here.
As per #Antonio, we can use a single property to access as the readOnly property value publicly and readWrite privately. Below is my illustration:
class MyClass {
private(set) public var publicReadOnly: Int = 10
//as below, we can modify the value within same class which is private access
func increment() {
publicReadOnly += 1
}
func decrement() {
publicReadOnly -= 1
}
}
let object = MyClass()
print("Initial valule: \(object.publicReadOnly)")
//For below line we get the compile error saying : "Left side of mutating operator isn't mutable: 'publicReadOnly' setter is inaccessible"
//object.publicReadOnly += 1
object.increment()
print("After increment method call: \(object.publicReadOnly)")
object.decrement()
print("After decrement method call: \(object.publicReadOnly)")
And here is the output:
Initial valule: 10
After increment method call: 11
After decrement method call: 10

Making a class in Swift 2

How should I correctly create such a class which can be used from any .swift-file of my project and does not need to be initialized with a variable?
I mean that I want not to have to write something like
someVar = myClass()
in each file where I want this class to be usable. I just want this class to have a global public variables and change them from a .swift-file of my project by doing something like
myClass.myVar = value
I'm thinking about making this class a separate file. What's a correct way to do this?
You can create a static property inside a class or struct and call it anywhere. E.g:
//Config.swift
struct Config
{
static var field1 : String = "Field_Value"
static var field2 : String = "Field_Value"
}
You can use the property calling StructName.propertyName.
E.g:
//MyCode.swift
print(Config.field1)
Config.field1 = "New Value"
You can create a new class, make a variable off that class outside any class.
Class Awesome{
}
let awesomeness = Awesome()
you can than use 'awesomeness' as class instance in every other swift file

In Haxe (JS Target) is there a way to make static members available to another class as if it was its own?

I have this Haxe class that is growing quite large. It consists mostly of static methods & properties. (It's a module set to compile as JS target).
I would like to separate some of the complex static functions into another class.
Is there any way to mark it with a metatag / indicate the other class is an "extension" to the original class?
Something like #:native("OriginalClass") class OtherClass {...}
The goal is to avoid having to write the full variable access (ex: OriginalClass.LOG_QUEUE vs. LOG_QUEUE) or clutter the imports with each OriginalClass's static methods / properties used at the top of the OtherClass. Basically, something to make it aware that it "is" using the same members as the OriginalClass (whenever an 'undefined' one is found, at compile-time).
Example:
If OriginalClass has static var LOG_QUEUE:Array<String>; then OtherClass would be aware that any usage of LOG_QUEUE compiles to this JS code OriginalClass.LOG_QUEUE
Alright, got a solution after discussing with Dima Granetchi from the Haxe experts group on Slack.
Now, although this will still generate the OtherClass that makes use of the OriginalClass's static members, you can cut down on the quantity of import statements for most (if not all) of the module/class's static members by using the wildcard * symbol, like in this example:
// OriginalClass.hx
package somePackage;
class OriginalClass {
public static var LOG_QUEUE:Array<String>;
public static function main() {
LOG_QUEUE = [];
OtherClass.doSomething();
}
public static function doSomethingOriginal() {
LOG_QUEUE.push("World!");
}
}
// OtherClass.hx
import somePackage.OriginalClass.*; // <-- Demonstrating the WILDCARD (*) symbol
class OtherClass {
public static function doSomething() {
LOG_QUEUE.push("Hello"); //Resolved to OriginalClass.LOG_QUEUE
doSomethingOriginal(); //Resolved to OriginalClass.doSomethingOriginal()
}
}
Although this is a minimal example, it becomes more useful when you have a few different dozen static members used in your OtherClass.
Note
TypeDefs defined in the OriginalClass used inside the OtherClass doesn't seem to get recognized/resolved (may be due to missing public accessor, but I was unable to set it on my typedefs). You can always import those specific TypeDefs with individual import statements, like so:
//Somewhere at the top of OtherClass.hx...
import somePackage.OriginalClass.MyTypeDef;

What's the rationale behind not inheriting static variables, in Dart?

In Dart, if one class extends another, the extended class inherits all of the super classes non-static variables, but inherits none of its static variables.
For example
class TestUpper {
static final String up = 'super';
String upup = 10;
}
class TestLower extends TestUpper {
static final String low = 'lower';
String lowlow = 11;
}
var lower = new TestLower();
print( lower.lowlow ); // <== 11
print( lower.upup ); // <== 10
print( TestLower.low ); // <== "lower"
print( TestLower.up ); // <== No static getter 'get:up' declared in class 'TestLower'
Is this the normal behavior? If so, I would appreciate if someone explained the rationale behind it.
Yes, there's no inheritance of static members. See Static Methods section of the language specification :
Inheritance of static methods has little utility in Dart. Static methods cannot be overridden. Any required static function can be obtained from its declaring library, and there is no need to bring it into scope via inheritance. Experience shows that developers are confused by the idea of inherited methods that are not instance methods.
Of course, the entire notion of static methods is debatable, but it is retained here because so many programmers are familiar with it. Dart static methods may be seen as functions of the enclosing library.