Refactoring


Refactoring is a mechanism used in object-oriented programming when working with classes and interfaces. It means that if you have two classes that have similar purposes, and these classes have code in common, it may be better to create one base class out of the common code, then write subclasses from this base class. The subclasses would only have the code that differs between the classes.

To refactor classes using interfaces:

  1. If multiple classes implement the same interface in similar fashion (the implementation code is the same for all of them), create a base class.

  2. Implement the interface in the base class.

  3. Add implementation code for each method in the interface to the base class.

  4. Derive child classes from the base class.

  5. Use the derived classes through the interface ( Figure 8.28 ).

    Figure 8.28 You can use a Checking object through the IAccount interface because Checking derives from AccountImpl and AccountImpl implements the IAccount interface. In other words, if any class in the parent hierarchy implements the interface then the derived class also supports the interface.
     interface IAccount {    void MakeDeposit(int Amount);    void MakeWithdrawal(int Amount); }  class AccountImpl : IAccount  {    public void MakeDeposit(int Amount)    {    }    public void MakeWithdrawal(int Amount)    {    } } class Checking :  AccountImp  l { } class Savings :  AccountImpl  { } class Bank {    void OpenAccount()    {      IAccount acct = new Checking();      acct.MakeDeposit(100);    } } 

graphics/tick.gif Tips

  • If a base class implements the interface, the child classes are also compatible with the interface.

  • In designing your classes, define your interfaces first, then create a base class to implement the interfaces. Then create sub-classes that inherit from the base class. Use the derived classes through the interface. This is the mechanism that experienced developers often use when writing applications.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net