8.1. Public Interfaces

One common way of codifying a contract that is used in many programming environments is the interface. There are many ways of defining an interface, depending on what language you are using, but the concept is common among many. An interface serves to group together a set of methods with specific signatures as a unit that can be implemented by different concrete pieces of code. For example:

public interface IHtmlFormatable
{
    void FormatAsHtml(HtmlTextWriter writer);
}

In this case, any object that implements the IHtmlFormatable interface must provide a FormatAsHtml method. The object agrees to abide by the contract that the interface establishes. The interface definition doesn't make any requirements for how the method is implemented as long as it fulfills the contract. The following code demonstrates a BankTransfer class that can implement IHtmlFormattable for display purposes:

public class BankTransfer : IHtmlFormatable { private string toAccount; private string fromAccount; private decimal amount; public string ToAccount { get { return toAccount; } set { toAccount = value; } } public string FromAccount { ... } public decimal Amount { ... } #region IHtmlFormatable Members public void FormatAsHtml(HtmlTextWriter writer) { writer.RenderBeginTag('table'); writer.RenderBeginTag('tr'); writer.RenderBeginTag('td'); writer.Write("Account to transfer from: {0}", fromAccount); writer.RenderEndTag();//td writer.RenderBeginTag('td'); writer.Write("Account to transfer ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.