Is It Valid to Assign a Value Twice to the Same Property Within One Rule

Is it valid to assign a value twice to the same property within one rule?

It is valid to have multiple declarations that assign a value to a property so that the assignments apply to the same element, e.g.

h1 { color: red; }
h1 { color: blue }

Combining the declarations in the same rule does not change this.

There is no explicit statement about this in CSS specifications, so it is allowed simply because there is no rule that forbids it. Multiple declarations are very common, though mostly so that they are in different rules, often even in distinct style sheets. But they can also be used within a rule. A common technique is

 p { max-width: 25em; max-width: 60ch }

which means that older browsers that do not recognize the ch unit will use the setting max-width: 25em, whereas in newer browsers, the latter declaration takes effect.

A general rule in CSS is that all other things being equal, latter declaration wins; this is part of the cascade rules. In the case of h1 { color: red; color: blue }, all other things are equal. But in h1 { color: red !important; color: blue }, the first declaration would win.

LESSCSS: Assign a value to a property taken from another one's

This is possible starting with v3 of LESS! Here is the documentation on it.

The example use case they provide ends up with the background-color getting the same value as the color property when compiled:

.widget {
color: #efefef;
background-color: $color;
}

is it bad programming practice to call the same C# Property twice?

It depends if there is some computation to get the value of property (I consider doing some larger computation in property getter as bad practice, but you can't rely on that there is no such property).

The rule is: In most of the cases you will be ok calling property multiple times. ...but who knows, who implemented that god damn performance killer property, just because it was available to do it in that way....

Good - automatic property

public string MyValueProperty { get; set; }

is compiled to getter/setter like in java:

private string myValueProperty;
public string MyValueProperty
{
get{
return myValueProperty;
}
set{
this.myValueProperty = value;
}
}

You will get little or no performance hit calling such property multiple times. It is similar to calling basic getter/setter methods in java.

Bad - some computing is involved to get value of property

public string MyLongTimeToGetValueProperty
{
get
{
var res = DoSomeComputation();
return res;
}
}

It is better to avoid calling such properties multiple times. (Regardless that such kind of properties should be refactored to methods, because they behave like one)

Can an HTML element have the same attribute twice?

It is not valid to have the same attribute name twice in an element. The authoritative references for this are somewhat complicated, as old HTML versions were nominally based on SGML and the restriction is implied by a normative reference to the SGML standard. In HTML5 PR, section 8.1.2.3 Attributes explicitly says: “There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.”

What happens in practice is that the latter attribute is ignored. Well, future browsers might do otherwise. In the DOM, attributes appear as properties of the element node as well as in the attributes object, so there would be no natural way to store two values.

Assign same value to multiple variables in single statement

It's as simple as:

num1 = num2 = 5;

When using an object property instead of variable, it is interesting to know that the get accessor of the intermediate value is not called. Only the set accessor is invoked for all property accessed in the assignation sequence.

Take for example a class that write to the console everytime the get and set accessor are invoked.

static void Main(string[] args)
{
var accessorSource = new AccessorTest(5);
var accessor1 = new AccessorTest();
var accessor2 = new AccessorTest();

accessor1.Value = accessor2.Value = accessorSource.Value;

Console.ReadLine();
}

public class AccessorTest
{
public AccessorTest(int value = default(int))
{
_Value = value;
}

private int _Value;

public int Value
{
get
{
Console.WriteLine("AccessorTest.Value.get {0}", _Value);
return _Value;
}
set
{
Console.WriteLine("AccessorTest.Value.set {0}", value);
_Value = value;
}
}
}

This will output

AccessorTest.Value.get 5
AccessorTest.Value.set 5
AccessorTest.Value.set 5

Meaning that the compiler will assign the value to all properties and it will not re-read the value every time it is assigned.

What if I want to assign a property to itself?

Prior to Swift 3.1 you could assign the property name to itself with:

name = (name)

but this now gives the same error: "assigning a property to itself".

There are many other ways to work around this including introducing a temporary variable:

let temp = name
name = temp

This is just too fun not to be shared. I'm sure the community can come up with many more ways to do this, the crazier the better

class Test: NSObject {
var name: String? {
didSet {
print("It was set")
}
}

func testit() {
// name = (name) // No longer works with Swift 3.1 (bug SR-4464)
// (name) = name // No longer works with Swift 3.1
// (name) = (name) // No longer works with Swift 3.1
(name = name)
name = [name][0]
name = [name].last!
name = [name].first!
name = [1:name][1]!
name = name ?? nil
name = nil ?? name
name = name ?? name
name = {name}()
name = Optional(name)!
name = ImplicitlyUnwrappedOptional(name)
name = true ? name : name
name = false ? name : name
let temp = name; name = temp
name = name as Any as? String
name = (name,0).0
name = (0,name).1
setValue(name, forKey: "name") // requires class derive from NSObject
name = Unmanaged.passUnretained(self).takeUnretainedValue().name
name = unsafeBitCast(name, to: type(of: name))
name = unsafeDowncast(self, to: type(of: self)).name
perform(#selector(setter:name), with: name) // requires class derive from NSObject
name = (self as Test).name
unsafeBitCast(dlsym(dlopen("/usr/lib/libobjc.A.dylib",RTLD_NOW),"objc_msgSend"),to:(@convention(c)(Any?,Selector!,Any?)->Void).self)(self,#selector(setter:name),name) // requires class derive from NSObject
unsafeBitCast(class_getMethodImplementation(type(of: self), #selector(setter:name)), to:(@convention(c)(Any?,Selector!,Any?)->Void).self)(self,#selector(setter:name),name) // requires class derive from NSObject
unsafeBitCast(method(for: #selector(setter:name)),to:(@convention(c)(Any?,Selector,Any?)->Void).self)(self,#selector(setter:name),name) // requires class derive from NSObject
_ = UnsafeMutablePointer(&name)
_ = UnsafeMutableRawPointer(&name)
_ = UnsafeMutableBufferPointer(start: &name, count: 1)
withUnsafePointer(to: &name) { name = $0.pointee }

//Using NSInvocation, requires class derive from NSObject
let invocation : NSObject = unsafeBitCast(method_getImplementation(class_getClassMethod(NSClassFromString("NSInvocation"), NSSelectorFromString("invocationWithMethodSignature:"))),to:(@convention(c)(AnyClass?,Selector,Any?)->Any).self)(NSClassFromString("NSInvocation"),NSSelectorFromString("invocationWithMethodSignature:"),unsafeBitCast(method(for: NSSelectorFromString("methodSignatureForSelector:"))!,to:(@convention(c)(Any?,Selector,Selector)->Any).self)(self,NSSelectorFromString("methodSignatureForSelector:"),#selector(setter:name))) as! NSObject
unsafeBitCast(class_getMethodImplementation(NSClassFromString("NSInvocation"), NSSelectorFromString("setSelector:")),to:(@convention(c)(Any,Selector,Selector)->Void).self)(invocation,NSSelectorFromString("setSelector:"),#selector(setter:name))
var localVarName = name
withUnsafePointer(to: &localVarName) { unsafeBitCast(class_getMethodImplementation(NSClassFromString("NSInvocation"), NSSelectorFromString("setArgument:atIndex:")),to:(@convention(c)(Any,Selector,OpaquePointer,NSInteger)->Void).self)(invocation,NSSelectorFromString("setArgument:atIndex:"), OpaquePointer($0),2) }
invocation.perform(NSSelectorFromString("invokeWithTarget:"), with: self)
}
}

let test = Test()
test.testit()

Why is object with duplicated property accepted in JavaScript?

What you state has no problem if you assign it to a variable, if you don't however, you get the error you mention. Which makes all the difference from a syntax point of view.

When you wrap any structure in parens you are causing that syntax to be evaluated as an expression, the result of which is stored as a temporary variable. The error I get when not doing so in Firefox is unexpected label or invalid label, so it seems without assignment, or parens, this object construction is not treated as an object construction - instead it is treated as a block with multiple label statements that are defined illegally:

{
a: function(){
alert('a');
},
b: function(){
alert('b');
}
}

The above should be totally acceptable as an object, however you get a similar error if you evaluate it without assinging it to some form of variable, or evaluating it with parens. Put simply the duplication of the attribute name is not causing the error :)

Basically imagine your first example, but like this:

function (){
"a": 4,
"b": 5
}

That is roughly how these browsers are treating it, which is now obviously illegal javascript syntax... whereas it wasn't so obvious before.

Defining a property in a record twice

The correct way to do this is:

record Cat(int PawCount)
{
public int PawCount { get; init; } = PawCount;
}

This is useful as it allows you to do e.g. validation

record Cat(int PawCount)
{
private int _pawCount;
public int PawCount {
get => _pawCount;
init => _pawCount = value < 0 ? throw new ArgumentException() : value;
} = PawCount;
}

The spec for this is here: https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/records.md#members-of-a-record-type

Members are synthesized unless a member with a "matching" signature is declared in the record body or an accessible concrete non-virtual member with a "matching" signature is inherited. Two members are considered matching if they have the same signature or would be considered "hiding" in an inheritance scenario.

So since a property with the same name as the parameter already exists, the compiler wont synthesize a PawCount property, and so just silently ignores the parameter unless you use it yourself explicitly.

WatchEffect is triggered twice when watching a reactive object

According to the documentation, watchEffect

Runs a function immediately [emphasis added] while reactively tracking its dependencies
and re-runs it whenever the dependencies are changed.

So it is expected that it should run twice in this situation: once when it is first defined, and then again when the value changes.



Related Topics



Leave a reply



Submit