Weird opEquals Problem

Jonathan M Davis jmdavisProg at gmx.com
Wed Feb 22 18:32:02 PST 2012


On Wednesday, February 22, 2012 18:22:59 H. S. Teoh wrote:
> On Wed, Feb 22, 2012 at 09:08:24PM -0500, Jonathan M Davis wrote:
> [...]
> 
> > I don't remember _exactly_ how the free function version of opEquals lined
> > out (I believe that TDPL explains it),
> 
> Yes, TDPL lays out the entire function (slightly simplified).
> 
> > but it's something like
> > 
> > bool opEquals(Object a, Object b)
> > {
> > 
> > if(a is b)
> > return true;
> > 
> > if(a is null || b is null)
> > return false;
> 
> IIRC that line should read:
> 
> if (a is null && b !is null || a !is null && b is null)

Why? If you have

if(a is b)

(which should be there for efficiency if nothing else), then you've already 
verified that they're not both null, so there's no point in checking that they 
aren't both null like you're doing there. If the actual implementation is
doing what you suggest, it should be fixed.

> Somewhere in here is also:
> 
> if (typeof(a)==typeof(b))
> return a.opEquals(b);
> 
> as a slightly optimization for the case when both are the same type.

Possibly, I don't recall for sure. It wouldn't surprise me.

> > This helps some of the problems you get with opEquals in other
> > languages such as Java. It also checks for null, so you don't have to
> > worry about a null object causing a segfault.
> 
> This is one of the little things that makes D shine. It's part of D's
> motto of "the simplest thing to write should default to the safest, most
> correct behaviour".
> 
> It jives with a principle I've always believed in when it comes to
> programming languages (or any computer language): "Simple things should
> be simple, and hard things should be possible." In this, D wins over
> Java by both counts, because Java's verbosity violates "simple things
> should be simple", and Java completely ruling out low-level operations
> (e.g. to write a GC in Java) fails "hard things should be possible".

As much as that may be true, his particular case is just a cut and dried case 
of D learning from Java's mistakes as opposed to the language being different 
due to different design goals. C# managed to improved on Java on a number of 
counts even though it's a very similar language, simply because it was able to 
learn from Java's mistakes. Really, that's one of C++'s biggest problems. It 
was the first to do a lot of stuff, and the languages which followed learned 
from _its_ mistakes. D, being newer than all three of those languages, should 
have been able to improve upon them even if it didn't have all of the new and 
innovative features that it has.

I do agree though that D strikes a much better balance than Java does.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list