Where should properties reside when modeling OOP? Small example included

I'm looking to learn how to use interfaces and base classes effectively. I'm not exactly sure where to put common properties? Do only behaviors belong in an interface? If properties such as: Color and MinSpeed shouldn't go in the interface, where should they live? In an abstract class?

public interface IVehicle
{
    void Speed();
    void Clean();
    void Stop();
}

public class Bmw : IVehicle
{
    // Because these pertain to every vehicle no matter of maker,
    // should these propertes go in the interface? Or in an abstract class?
    public string Color { get; set; }
    public int MinSpeed { get; set; }

    #region IVehicle Members

    public void Speed()
    {

    }

    public void Clean()
    {

    }

    public void Stop()
    {

    }

    #endregion
}

Answers


Interfaces can be thought of as a contract that must be satisfied by any implementing class. Use it if you want to guarentee that all classes do the same thing—satisfy the same API—but you don't care how they do it. If properties are a part of that API, then by all means include them in your interface.

From your example above, if you want all cars to be guaranteed to have a color and minSpeed, then those properties belong in the interface. If those properties are specific to BMWs alone, then they belong in the BMW class. If those properties belong to some classes but not others, you could create a new interface extending the original one:

public interface IVehicleWithColorAndMinSpeed : IVehicle
{
    string Color { get; set; }
    int MinSpeed { get; set; }
}

(just don't get carried away with this)


Abstract classes are similar, but allow you to provide a default implementation for your sub classes.

Abstract classes tend to be easier to version, since you can add something new to your API, and provide a default implementation that your existing subclasses will automatically pick up; adding something to an interface immediately breaks all existing classes which implement that interface.


Need Your Help

Ways to simulate the yet unimplemented <bdi> HTML tag?

php html5 unicode internationalization bidi

The purpose of the &lt;bdi&gt; tag in HTML5 is to isolate bidirectional text from it's context. And that's precisely what I'm looking for.

How do I find x and y gradient in OpenCV?

c++ opencv image-processing

I am trying to implement a custom version of Histogram of Oriented Gradients. My gradient kernel is [-1.2 0 1.2]. This kernel has to be applied in x and y directions (along rows and along columns),...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.