On 07/26/2013 05:13 AM, Dicebot wrote:

> On Friday, 26 July 2013 at 09:12:27 UTC, Land wrote:
>> struct Shader
>> {
>>      // Field
>>      // Field
>>      // Field
>> }
>>
>> // Method
>> // Method
>> // Method
>> // Method
>
> I personally favor this approach whenever possible, it fits nicely with
> UFCS and allows to keep data type signature clean from unrelated stuff.
> My guideline is "If something simply operates on an aggregate, make it a
> free function. If it requires some knowledge about private aggregate
> state and/or is something done by aggregate, make it a method".

+1

I apply the same idea in C++ as well.

Of course, the decision of whether it is a struct or class is based on other factors. (This is not an issue in C++ because structs and classes are semantically same there.)

And yes, UFCS helps with this in D. I had come up with a quick example: Once a Car class provides basic functionality, functions like canTravel() should not be members: [1]

class Car
{
    enum economy = 12.5;          // kilometers per liter (average)
    private double fuelAmount;    // liters

    this(double fuelAmount)
    {
        this.fuelAmount = fuelAmount;
    }

    double fuel() const
    {
        return fuelAmount;
    }

    // ...
}

bool canTravel(Car car, double distance)
{
    return (car.fuel() * car.economy) >= distance;
}

Ali

[1] http://ddili.org/ders/d.en/ufcs.html

Reply via email to