Why are opCall's not implicitely assignable?

Mike Parker aldacron71 at yahoo.com
Tue Sep 26 03:41:54 PDT 2006


Karen Lanrap wrote:
> Hasan Aljudy wrote:
> 
>> What you're trying to do makes code totally unreadable.
> 
> It is already possible to write that way---with some inconsistencies.
> 
> If your argument of inreadability holds at all it also holds for 
> overloading functions---but overloading functions is an accepted 
> technic.

There is nothing inherently unreadable about overloading functions, nor 
is there anything inherently unreadable about property syntax. The 
problem is in how you are using these features. Consider this:

class MyClass
{
    void print(Object o) { writef(o); }
    void print(int i) { writef(i); }
    ...
}

There is no confusion about the following code:

Object o = new Object();
myClass.print(o);
myClass.print(10);

The method is overloaded, but perfectly readable. You can clearly see by 
the name that the method prints the argument passed, regardless of type. 
But that's not going to stop someone from implementing it this way:

class MyClass
{
    void print(Object o) { delete o; }
    void print(int i) { writef(i + 10); }
}

It's not the overloading that makes the code unreadable, but the 
implementation. How many users of MyClass will run into bugs because 
myClass.print(myObj) is deleting their object and not printing it? Or 
when every integer they output is 10 higher than it should be? The code 
is not doing what it appears to be, so it is unreadable.

What you are doing with properties is the same thing:

void main()
   {
     car= new Car;
     car.roof= COLOR.LIGHTBLUE;
     seats[0]= COLOR.DARKBLUE;
     seats[1]= COLOR.RED
     // ...

A Roof is *not* a Color. A Seat is *not* a Color. You are abusing the 
property syntax. The compiler cannot prevent you from such silliness. It 
is the responsibility of the programmer to follow accepted practice and 
to make the code clear and understandable.

The operator overload opAdd should perform an addition and not a 
multiplication, but nothing stops you from implementing a 
multiplication. If you were to do that, myClass + myClass suddenly takes 
on a meaning other than what is expected and the code becomes 
unreadable. The same thing is happening with your Car example. The 
following is how it *should* look:

car.roof.color = COLOR.LIGHTBLUE;
seats[0].color = COLOR.DARKBLUE;

Now the code is clear. Seats have the property of color, and Roofs have 
the property of color, so assigning a color to those properties makes 
sense. But assigning a color to a roof directly does not.

Just because you *can* do something doesn't mean you *should*. The 
syntax of the language can help you write readable code, but the 
compiler isn't a sentient being. It's up to you to stay within the 
bounds of intended use, name your methods clearly and meaningfully, and 
to make your code as readable as possible.



More information about the Digitalmars-d-learn mailing list