Here's some code I have:
window.MyNamespace ?= {}
window.MyNamespace.Subnamespace ?= {}
window.MyNamespace.Subnamespace.Subsubnamespace ?= {}
Is there a way to clean this up in a CoffeeScripty way?
The only alternative I can think of, is to use this somewhat obscure syntax:
((window.MyNamespace ?= {}).Subnamespace ?= {}).Subsubnamespace ?= {}
See also this issue which proposes a way to create an object property if it doesn't exist.
Related
Here is a little background:
I am trying to test some functions. I CANNOT change anything in the function or any class variables.
So I am calling this function in my unit test, the problem is that, there is a boolean flag, this method simply will just not execute if this flag is not set to true. But this flag has a private setter, so I can directly set it.
I asked around someone told me to use a extension IN the test file to set the variable, but I've tried I don't think I can set it if the extension is not in the same file as the function. Am I doing something wrong? Or is there any other way to test it?
What they were referring to is to place an extension in the file with the class-under-test. So if you have something like:
class ToBeTested {
private(set) var bool: Bool
}
You can add an internal setter:
extension ToBeTested {
func setBoolTrue() { bool = true }
}
But this has to be in the same file with ToBeTested. If you cannot modify that file, this is not a solvable problem. If it needs to be tested this way, then the class will need to be designed to permit that.
When a property is marked private(set), the compiler can assume that the value cannot be changed in any way outside this file. That allows it to apply optimizations that may not be valid if the property were changeable outside this file. The "setter method" may not even exist if the compiler determines that it doesn't need it. For example, it may completely inline that operation, or eliminate it entirely if it can prove the value is never changed.
I'm using CoffeeScript to create a class and build a private method, but my code feels kludgy.
As in the example below, first I define the method with = and then I am forced to use the call method on the portion to be used. But this seems like a kludgy workaround, so I want to know if there is a cleaner solution.
class Human
constructor: (#name, #height, #weight) ->
_realWeight = ->
#weight
answerWeight: ->
console.log(_realWeight.call(#) - 5)
$ ->
ken = new Human('Ken', 165, 70)
ken.answerWeight()
TL;DR
No.
Longer Answer
There is only one way to have truly private data in javascript/coffeescript: closures.
First, lets consider some alternatives:
Symbols
Because symbols are unique they can be used to create psuedo-private data:
you can only access the property if you have a reference to the symbol its keyed to:
foo = Symbol('I am unique')
bar = {}
bar[foo] = "I am almost private"
Code that doesn't have access to foo can't easily get to that property of bar except for Object.getOwnPropertySymbols. So not easy to break, but breakable.
Underscores
Typical naming convention says that properties/methods prefixed or followed by an underscore are 'private', they are not to be used by an external caller. However, that 'privacy' is not in any way enforced by the runtime.
So lets talk about closures.
Simple Closure example
makeFoo = (something) -> getSomething: -> something
foo = makeFoo(3)
foo.something # undefined
foo.getSomething() # 3
Now there is no way to get at the parameter passed to the constructor except to call the method. This pattern, while slightly more elegant in coffeescript, is still kinda lame. Lots of duplicated function objects. Not so bad for just getSomething, but add a bunch of methods and it gets ugly fast. Also, typically not as easily optimized by the JIT compiler as foo = new Foo() would be. Fortunately, ES 2015 to the rescue:
Advanced Closure Example
Foo = null
do ->
privateData = new WeakMap()
getSomething = -> privateData.get(this)
Foo = class Foo
constructor: (something) -> privateData.set(this, something)
getSomething: getSomething
foo = new Foo(3)
foo.something # undefined
foo.getSomething() # 3
new Foo(42).getSomething() # 42
foo instanceof Foo # true
Now all instances of Foo share one copy of getSomething rather than each getting their own. The weakmap is hidden in the closure created by the IIFE, and because of the 'weak' part of WeakMap when the instance gets garbage collected the private data will be as well. You are also now potentially able to enjoy the benefits of the compiler optimizing newly created objects. Last but not least, instanceof still works properly (to the extent that it ever works properly).
Further reading.
Even More reading
Note
WeakMaps are not supported in all browsers (for IE its 11 or bust). There is a shim, but it cannot be completely polyfilled. Whether or not the shim gets close enough is a call you'll have to make.
Here is the code I write:
func printType<T: Any>(one: T.Type) {
print(one)
}
func printType2<T: Any>(one: T.Type, name: String) {
print(one)
}
printType(Set<Int>)
printType2(Set<Int>.self, name: "name")
I wonder why printType(Set<Int>) can work. And in printType2(Set<Int>.self, name: "name"), I can not leave out .self to make it work.
Edit:
I want to know which rule imply when I can omit .self. I had tried to find it in Apple official references, but failed.
Edit:
I test the codes in Xcode Version 7.1 (7B91b).
I also ask it in apple official forum, and get an answer there:
This is a famous undocumented feature of Swift, since 1.0 (or former > betas, which I cannot confirm).
When calling a method or function with single type argument, you can omit > .self .
I guess this feature is included into Swift to make sizeof-like functions > neat, but not sure.
https://forums.developer.apple.com/thread/24980
Since swift doesn't use headers to specify it's interface, but access modifiers instead, I wondered if there is a good way to split public and private methods (perhaps in files, extensions or just visually). I'm thinking of the Java-esque way of declaring a FooInterface and FooImpl, but I don't really like the idea. Is there a nicer way to achieve this?
The bottom line is I want to be able to have all public members in one location and the private stuff in another - it just helps to avoid visibility mistakes.
I generally use the technique of declaring a private extension:
private extension MyClass {
}
I do that later in the file. However, that only works for methods. Properties still need to be declared in the main type definition.
You can just declare the methods as private:
private func doSomething() {
}
First: why on Earth am I asking this?
I'd like to have a working 'invariant' check system with my classes, and this would allow a nice way to make it happen. Each level could provide their invariants (if any) and the base class would execute them at the end of the construction chain.
Similar question on Java: Running a method after the constructor of any derived class
Maybe this will help: Running code after subclass initialization