This code throws an error:
if (modalMessage != null && contains(modalMessage))
{
removeChild(modalMessage); // the error is here
modalMessage = null;
}
The Error is:
[Fault] exception, information=ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
how can this be? i am checking if it is a child beforehand.
contains() will return true if the subject is a descendant of the caller. This will return true for indirect descendants too, children of children etc.
Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. The search includes the entire display list including this DisplayObjectContainer instance. Grandchildren, great-grandchildren, and so on each return true.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#contains%28%29
You could check the parent:
if(modalMessage && modalMessage.parent && modalMessage.parent == this)
Or, for a more general purpose disposal solution:
if(modalMessage) {
if(modalMessage.parent) DisplayObjectContainer(modalMessage.parent).removeChild(modalMessage);
modalMessage = null;
}
Related
void main() => Foo() == 1;
class Foo {
#override
bool operator ==(Object other) {
print(super == this); // true
// print(this == super); // Compile error
return super == other;
}
}
There are 2 questions.
Why can't I do this == super?
If you look at the return statement return super == other, you can tell the operator == is called on the Object class, so is the entire == implementation not a call which has been delegated to the Object class?
Let me explain the 2nd question further if it wasn't clear. Let's say I check for
Foo() == 1
The == operator defined in Foo class will be invoked and there all I'm doing is return super == other that means Object's == operator is being invoked and the other is int, so where the Foo instance in above code is? Here, it is only Object and int. I think super is doing something else too, not sure what is.
To answer your questions:
You can't do this == super because super is not an expression which is explained if you try run the program (the analyzed could give a better explanation):
bin/stackoverflow.dart:7:19: Error: Can't use 'super' as an expression.
To delegate a constructor to a super constructor, put the super call as an initializer.
print(this == super); // Compile error
^^^^^
Which also make sense since super is not an object. It is a concept we can use to specify if we want to refer to fields/methods that are overridden. But we cannot use super as some kind of object since our object is not multiple objects in layers where you can extract a layer and then represent this as another object. Instead, our object is a combined implementation based on how you define your class.
Yes, you're basically calling the Object's == operator when you return super == other.
Supplementary example:
But remember, we are just calling the == operator defined in Object. Our object is still a combined data structure which can be illustrated by this example:
class A {
final int a = 5;
int getA() => a;
}
class B extends A {
int get a => 10;
int getA() {
return super.getA();
}
}
void main() {
print(B().getA()); // 10
}
You can see that even if we call super.getA() we are still operating on a B object where we have overridden the a field but we are calling the A.getA() method.
What should IEquatable<T>.Equals(T obj) do when this == null and obj == null?
1) This code is generated by F# compiler when implementing IEquatable<T>. You can see that it returns true when both objects are null:
public sealed override bool Equals(T obj)
{
if (this == null)
{
return obj == null;
}
if (obj == null)
{
return false;
}
// Code when both this and obj are not null.
}
2) Similar code can be found in the question "in IEquatable implementation is reference check necessary" or in the question "Is there a complete IEquatable implementation reference?". This code returns false when both objects are null.
public sealed override bool Equals(T obj)
{
if (obj == null)
{
return false;
}
// Code when obj is not null.
}
3) The last option is to say that the behaviour of the method is not defined when this == null.
leppie is right. Just to elaborate on his answer (and confirm his suspicion that F# doesn't guarantee this != null): discriminated unions may be marked with the attribute [<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>] allowing cases to be represented by the value null. Option<'T> is such a type. The None case is represented by null at run-time. (None : option<int>).Equals(None) is syntactically valid. Here's a fun example:
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type Maybe<'T> =
| Just of 'T
| Nothing
[<CompilationRepresentation(CompilationRepresentationFlags.Instance)>]
member this.ThisIsNull() = match this with Nothing -> true | _ -> false
Decompiling ThisIsNull with Reflector shows
public bool ThisIsNull()
{
return (this == null);
}
And the result:
Nothing.ThisIsNull() //true
The reason F# does this (I suspect) to optimize empty lists as null.
By adding this check, it allows one to call an instance method on a null instance without any problems.
See my blog post from a while back.
In C#, this is irrelevant.
To answer the question:
It should return true as both instances are null and deemed equal.
If this is null, the code can't be called, so that case needn't be considered (in C# anyway, there are cases where languages allow a null object to have a method dereferenced though obviously if it internally examines any of its non-existent fields it will error. Consider:
return x.Equals(y);
If x is null, we don't even get to call into Equals for the null check to count.
Hence we need only consider:
public bool Equals(T obj)
{
if(obj == null)
return false;
//logic defining equality here.
}
Where the possibility of both objects being null does come up, is when we are examining them from a static == operator override or from an IEqualityComparer<T> implementation:
public bool Equals(T x, T y)
{
if(x == null)
return y == null;
if(y == null)
return false;
//logic defining equality here.
}
Note that a useful shortcut here if equality can be lengthy to determine (e.g. comparing long strings), then we may take advantage of the fact that identity entails equality - that is something is always equal to itself, even Ayn Rand could figure that out ;) There are also algorithms that make comparing an item with itself quite common, making this shortcut well worth including. In this case the identity comparison already includes the check for both being null, so we leave it out again:
public bool Equals(T x, T y)
{
if(ReferenceEquals(x, y))
return true;
if(x == null || y == null)
return false;
//logic defining equality here.
}
For most methods I assume undefined behavior when called with this==null. That's because most programmers write their code under the assumption that this!=null, which is guaranteed by the C# specification if the calling code is written in C#.
That's why every sane caller of x.Equals(y) should either know for sure that that x is not null, or add a manual null check.
In most cases I wouldn't call Equals directly at all, but instead use EqualityComparer<T>.Default.
I would definitelly go with option 1:
if (this == null)
{
return obj == null;
}
if (obj == null)
{
return false;
}
null object always equals null object.
Sample code is in the MSDN: http://msdn.microsoft.com/en-us/library/ms131190.aspx?ppud=4
If this==null you will get a runtime exception calling Equals() on that object.
The following equals code returns wrong result for domain
boolean equals(o) {
if (o == null) return false
if (this.is(o)) return true
getClass() == o.class && id == o.id
}
For two loaded entities with same id return false. Id are equals (one record in DB). But classes not same.
The entities -- fields in another domains. And it looks like GORM used some wrapper classes.
How to avoid this kind of problem?
As you are seeing, requiring that the classes be the same is overly strict. Using instanceof is usually safer, e.g.
class Foo {
boolean equals(o) {
if (!o) return false
if (is(o)) return true
o instanceof Foo && id == o.id
}
}
Using id in equals or hashCode is generally a bad idea in domain classes since you can't compare persistent and non-persistent classes. For example
class Foo {
String name
boolean equals(o) {
if (!o) return false
if (is(o)) return true
o instanceof Foo && id == o.id
}
}
With this class, this would fail:
new Foo(name: 'foo').save()
assert Foo.findByName('foo') == new Foo(name: 'foo')
but all of the important class data (in this case just the name property) is identical in both cases.
Even worse, assuming you create a hashCode method that's similarly broken, if you add a non-persistent instance to a hash-based collection (e.g. HashSet) and then save it, its id will change from null to some long value and so will its hashcode value. This will cause the instance to become "lost" in the collection.
Where is special method in GormInstanceApi
/**
* Proxy aware instanceOf implementation.
*/
boolean instanceOf(D o, Class cls) {
if (o instanceof EntityProxy) {
o = (D)((EntityProxy)o).getTarget()
}
return o in cls
}
Using of this method solved problem
I am using transaction event handlers to do security checking on deleted nodes, to make sure whether a current user is allowed to do this.
To make sure I have the right node to check I first have to find out whether it has a certain property and then check the value of another property, so ideally the code should be something like this:
graphDatabaseService.registerTransactionEventHandler(new TransactionEventHandler.Adapter<Object>() {
#Override
public Object beforeCommit(TransactionData data) throws Exception {
for (Node node : data.deletedNodes()) {
if (node.hasProperty("checkProperty")){
if (node.hasProperty("propertyToCheck")){
String value = (String) node.getProperty("propertyToCheck");
... do checking on value
}
}
}
return null;
}
But this fails with exception
Caused by: java.lang.IllegalStateException: Node[11] has been deleted in this tx
at org.neo4j.kernel.impl.core.WritableTransactionState$CowEntityElement.assertNotDeleted(WritableTransactionState.java:141)
at org.neo4j.kernel.impl.core.WritableTransactionState$CowEntityElement.getPropertyAddMap(WritableTransactionState.java:129)
at org.neo4j.kernel.impl.core.WritableTransactionState$CowNodeElement.getPropertyAddMap(WritableTransactionState.java:155)
at org.neo4j.kernel.impl.core.WritableTransactionState.getCowPropertyAddMap(WritableTransactionState.java:529)
at org.neo4j.kernel.impl.core.Primitive.hasProperty(Primitive.java:306)
at org.neo4j.kernel.impl.core.NodeImpl.hasProperty(NodeImpl.java:53)
at org.neo4j.kernel.impl.core.NodeProxy.hasProperty(NodeProxy.java:160)
The only workaround I found is this:
for (Node node : data.deletedNodes()) {
boolean check = false;
String valueToCheck = null;
for (PropertyEntry prop : data.removedNodeProperties()) {
if (node.equals(prop.entity())) {
if (prop.key().equals("checkProperty")) {
check = true;
}
if (prop.key().equals("propertyToCheck")) {
valueToCheck = (String) prop.previouslyCommitedValue();
}
}
}
if (check){
... do checking on value
}
}
But this goes through ALL deleted properties, so this is obviously not a nice solution.
So my question is: is there a better way to do this?
Using neo4j 1.9.3
Since the code in TransactionEventHandler#beforeCommit is itself part of the transaction you cannot access any property on a deleted node or relationship. As you've discovered the only way to access deleted properties is via TransactionData#removedNodeProperties() and TransactionData#removedRelationshipProperties().
You can optimize your code by running a single iteration over removedNodeProperties() (just pseudo code below):
for (PropertyEntry<Node> pe: data.removedNodeProperties()) {
if (pe.key().equals("checkProperty")) {
runCheckForDeletedNodeAndValue(pe.entity(), pe.previouslyCommitedValue())
}
}
public void runCheckForDeletedNodeAndValue(Node node, Object oldValue) {
// throw exception if current user is not allowed to delete
// this will rollback whole transaction
}
Your snippet would iterate this collection for each deleted node.
Is there a method in the JDK that compares two objects for equality, accounting for nulls? Something like this:
public static boolean equals(Object o1, Object o2)
{
if (o1 == null)
{
return o2 == null; // Two nulls are considered equal
}
else if (o2 == null)
{
return false;
}
return o1.equals(o2);
}
It seems silly to write this method myself since I would think that it has to exist already somewhere.
Java 7.0 added a new handy class: Objects.
It has a method exactly for this: Objects.equals(Object a, Object b)
Apache Commons Lang has such a method: ObjectUtils.equals(object1, object2). You don't want generics on such a method, it will lead to bogus compilation errors, at least in general use. Equals knows very well (or should - it is part of the contract) to check the class of the object and return false, so it doesn't need any additional type safety.
FWIW, this was my implementation:
private static boolean equals(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
In my application, I know that a and b will always be the same type, but I suspect this works fine even if they aren't, provided that a.equals() is reasonably implemented.
public static boolean equals(Object object1, Object object2) {
if (object1 == null || object2 == null) {
return object1 == object2;
}
return object1.equals(object2);
}
If you are worried about NullPointerExceptions you could just test equality like:
if (obj1 != null && obj1.equals(obj2)) { ... }
The general contract of equals() is that a non-null object should never be equal to a null reference, and that the equals() method should return false if you are comparing an object to a null reference (and not throw a NPE).
Whenever I come across a need and think "this is so common Java must have it" but find it doesn't, I check the Jakarta Commons project. It almost always has it. A quick search of the commons-lang API (which has the most basic of common utilities) shows an equals() method that provides what you want.
Jakarta Commons Lang API has what you are looking for ObjectUtils.equals(Object,Object)