No. Let's consider both the operator on its own, and the heavily chained use you have for it.
On its own .?A
depends upon the same amount of knowledge of the class the left-value is and of the type returned by the method as .A != null
does, viz. It needs to know about that the A
property exists and returns a value that can be compared with null
.
We can only argue that this violates the law of Demeter if typed properties do. We aren't even forced to have A
as a concrete type (its value could be of a derived type). The coupling here is minimal.
Now lets consider var x = A?.B?.C?.D?.E?.F
.
Which means that A
must be of a type that could be null, or could have a B
property, which must be of a type that could be null or have a C
property, and so on until the type of the E
property being something that could be null or could have an F
property.
In other words, we need to be doing this with either a statically-typed language or have applied a constraint on the types that can be returned if the typing is loose. C# in most cases uses static typing, so we've changed nothing.
If we had then the following code would also violate the law:
ExplicitType x;
var b = A.B;
if (b == null)
x = null;
else
{
var c = b.C;
if (c == null)
x = null;
else
{
var d = c.D;
if (d == null)
x = null;
else
{
var e = d.E;
if (e == null)
x = null;
else
x = e.F;
}
}
}
Which is exactly the same. This code that is using the coupling of different elements needs to "know" about the full chain of coupling, but it is using code that doesn't violate the Law of Demeter to do so, with each unit having a well-defined coupling with the next.
A?.B?.C?.D?.E?.F?
would violate it - LoD is not about how many dots and if the calling method has such information about the structure that isn't in violation with its points, such a call would be perfectly acceptable. That such code could violate LoD isn't enough to say that all uses of it do violate LoD. – user40980 Oct 7 '15 at 18:25X.Y.Z.W.U
is a violation to the "law". But, in my experience dealing with code, 90% of the time it is just plain ugly coupled code. – Arthur Rizzo Oct 7 '15 at 20:28.?
no more violates LoD than+
or-
does. – user40980 Oct 7 '15 at 20:59