Default Implementation For an Interface

Jacob Carlborg doob at me.com
Thu Feb 16 02:11:20 PST 2012


On 2012-02-16 04:01, Kevin wrote:
> I was implementing a framework and I found that I wanted two things.
> - A strong set of interfaces so that I can get what I want from a
> variety of sources.
> - Some basic implementations of these interfaces.
>
> For example, say I was writing a database class. I could either name the
> interface Database and call the class DatabaseImplementation or
> something but that is ugly. If I call the interface IDatabase, the
> Database class looks nice but I need to convince users to write
> functions that take IDatabases not Databases.
>
> I was wondering if there was any way to implement a default
> implementation. This way, I could create my Database interface and
> classes could implement that but if you called `new Database()` you
> would still get a basic database.

You can create an abstract class that implements some parts of the 
interface. Then the user (developer) is free to choose to inherit from 
the interface or the abstract class.

> I thought about doing it in different modules but it just gets messier
> as you have to fully qualify all of the names so both look ugly. I
> though about overloading the new operator for the interface but it would
> have to be final and that would mess everything up. I though about a
> meathod like `Database.newDefault()` but that is messy and has no
> meaning in a derived class.
>
> I couldn't find anything about this so I was wondering what you would
> recommend. Should I just pick a naming scheme?

About the naming scheme I would go for this:

interface Database {}
abstract AbstractDatabase : Database {}

class Implementation : Database {}
class Implementation2 : AbstractDatabase {}

Possibly suffix the implementations with "Database".

class ImplementationDatabase : Database {}
class Implementation2Database : AbstractDatabase {}

But it feels a bit redundant with "Database" in the implementation name.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list