Refactor: Visual Studio Extract Interface

I recently learned about a very cool option in Visual Studio, the ability to extract an Interface from an existing class. This has made me much more comfortable in trying to adhere to a principle of not creating unnecessary code. I often found myself thinking I should create an interface first before creating the concrete implementation even for objects that I didn't have any current plans for extending.

This post will show you step by step how to extract an interface from an existing class, so keeping with open closed principle we can still extend the code base with our modifying the current object.

First lets consider the the Attendee class.

namespace Attendee
{
public class Attendee
{
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
private string _firstname;
public string FirstName
{
get { return _firstname; }
set { _firstname = value; }
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}

public bool
Save()
{
return true;
}
}
}
 

This is a very simple class implementation of an Attendee, a class I use in my Model-View-Controller presentation. Note this is a very simple domain object with no logic. To extract an interface place your cursor in the class name, Attendee in this case, select Extract Interface... on the Refactor menu.

 

ExtractInterface_01

This will launch the Extract Interface wizard. We can now modify the name, file name and the members to include in the interface.

ExtractInterface_02

Clicking OK after making your selection will generate the interface below.

using System;
namespace Attendee
{
interface IAttendee
{
int Age { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
bool Save();
}
}

Now you are free to create a new implementation of the Attendee class with out having to change any of the code in the old Attendee class. This has really reduced the fear of not creating an interface for everything first. Of course I still do for most of my objects but if there is no reason to create it right now, this give me the confidence that I can defer creating the interface and extension point until it is necessary.

Calendar

<<  April 2024  >>
MonTueWedThuFriSatSun
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

View posts in large calendar

Widget Category list not found.

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))X

Tag cloud

    Widget Month List not found.

    Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))X

    Widget AuthorList not found.

    Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))X

    Widget TextBox not found.

    Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))X