partial class

Julio César Carrascal Urquijo jcarrascal at gmail.com
Fri Oct 31 08:44:54 PDT 2008


Hello Ary,

> Conclusion: the motivation is coming from the UI, and to make life
> easier for them. (Maybe there are other reasons? I've been programming
> a lot in C# lately, and I never needed a partial class)
> 
> Since D doesn't have a UI designer or nothing is integrated that
> much... what would you use partial classes for?
> 
> If it's not for that reason, I think it makes it harder to know where
> is defined the code you are looking for.

One place I've used them is when calling web-services. Most web-services 
calls need to generate a very specific XML document and building this manually 
means that methods grow hundreds of lines. I use partial class to separate 
each of this monster methods form connection pooling and other concerns of 
the same class:

ServiceConnection.cs // Connection pooling
ServiceConnection.OTA_AirAvailRQ.cs
ServiceConnection.OTA_AirBookRQ.cs
...

An the usage is like this:

using (var conn = new ServiceConnection(connectionString))
{
    conn.Open();
    var result = conn.OTA_AirAvailRQ(...);
    ...
}

You might say that we could separate things into several objects but that's 
the whole point of the Facade pattern: Making one big call with all the data 
needed to avoid several round trips over a slow network.

Other place where I've used them is generating code from say a diagram or 
a database and still having a way to write custom methods for some classes. 
I (generally) don't need to look at the code generated by a tool but might 
want to add custom code in another file (so that it doesn't get overwritten 
if the tool is run again). For example, I can generate a state machine from 
a diagram and still be able to implement some methods in user-code:

// MyStateMachine.generated.cs
partial class StateA
{
    partial void OnEnter();
    partial void OnLeave();
    // Other code that calls OnEnter() and OnLeave();
}


// MyStateMachine.cs (Editable by the user)
partial class StateA
{
    partial void OnEnter()
    {
        // do something when entering A.
    }
}

This two uses have nothing to do with GUI and a lot to do with separating 
concerns of code in different files. I really wish D 2.0 could get this feature 
before release.






More information about the Digitalmars-d mailing list