Posts

Showing posts from February, 2010

C# Quasi-Mixins Example

As an example, I'll adapt one of the mixins found in the book Fundamentals of Object-Oriented Design in UML to use the C# quasi-mixins pattern . Given the following (simplified) domain classes: namespace Domain { public enum Medium { Email, SnailMail, IntergalacticMail } public class Customer { public string Name { get; set; } public string Address { get; set; } public string Email { get; set; } public Medium PreferredMedium { get; set; } } public class Invoice { public string Header { get; set; } public List<string> LineItems { get; set; } public Customer Customer { get; set; } } } We'd like to be able to send an invoice to a customer by using his preferred medium. To keep the code to send the invoice separate from the Invoice domain class, and to abstract it so that it can send any kind of document (not just invoices) that adhere to a certain format, a mixin to send documents is created: namespace ...

C# Quasi-Mixins Pattern

Extension methods are an interesting feature of C#. They allow for behavior to be added to existing classes. For example, a ToXml() method can be added to class Object , effectively making that method available everywhere: public static class XmlSerializableExtension { public static string ToXml(this Object self) { if (self == null) throw new ArgumentNullException(); var serializer = new XmlSerializer(self.GetType()); using (var writer = new StringWriter()) { serializer.Serialize(writer, self); return writer.GetStringBuilder().ToString(); } } // for completeness... public static T FromXml<T>(string xml) { var serializer = new XmlSerializer(typeof(T)); return (T)serializer.Deserialize(new StringReader(xml)); } } So, any instance can be serialized to XML simply like this: var customer = new Customer { Name = "Guybrush Threepwood", Preferred = true }; var xml = customer.ToXml(); Now, certainly all classes ...