Jump to content

Real-world abstract / interface examples


nloding

Recommended Posts

I've been searching high and low for some decent (actually, they can be crap, just be REAL) real-world examples of uses of abstract classes and interfaces.  I've seen many design patterns, and I get the concept, but now I need to put them into practice.

 

And I gotta say, I'm absolutely sick of class Animal, class Dog extends Animal, class Vehicle, class Van extends Vehicle examples.  Those are CRAP for illustrating real uses of the functionality given to us by OOP.  It's one thing to teach a concept, and it's another to put into use within a real application.  I can only find the former and the not the latter.

 

Does anyone have any links to, or can they post their own examples of, abstract classes and interfaces in use?

Link to comment
Share on other sites

Imagine you need to write some classes which parse various types of configuration files. You could have Config_Ini and Config_Xml for instance. Both of these classes may have some common functionality, so you could put that in a class called Config. Config in itself doesn't work though, so it's an abstract class.

 

abstract class Config
{
protected $data = array();

public function __construct($path)
{
	if (file_exists($path)) {
		$this->parse(file_get_contents($path));
	}
	else {
		throw new Exception("File {$path} could not be loaded");
	}
}

public function __get($name)
{
	return $this->data[$name];
}

public function __set($name, $value)
{
	$this->data[$name];
}

public funtion __isset($name)
{
	return isset($this->data[$name]);
}

public function __unset($name)
{
	unset($this->data[$name]);
}

abstract protected function parse($data);
}

 

Then you can implement the type specific classes:

 

class Config_Xml extends Config
{
protected function parse($data)
{
	// do stuff here
}
}

class Config_Ini extends Config
{
protected function parse($data)
{
	// do stuff here
}
}

 

This would be an example of how you could use abstract classes.

 

As an example for using an interface you could imagine you have an interface called Iterator:

 

interface Iterator
{
/**
 * Returns the value of the current item.
 */
public function current();

/**
 * Returns the key of the current item.
 */
public function key();

/**
 * Goes forward...
 */
public function next();

/**
 * Goes to the first item...
 */
public function rewind();

/**
 * Checks if the current position holds a valid value.
 */
public function valid();
}

 

So by implementing this interface into a class, your code can be certain that it has implemented the methods specified in the interface. You could then have a function or method like this:

 

function doStuff(Iterator $obj)
{
while ($obj->valid()) {
	echo "{$obj->key()} => {$obj->value()}<br />";

	$obj->next();
}
$obj->rewind();
}

 

The function doesn't care what kind of object it is, it just needs to be iteratable (I don't know if that's a word).

 

Note: PHP does actually have an interface called Iterator. If an object implements that interface then it'll be able to be used in a foreach loop (if I remember correctly).

Link to comment
Share on other sites

in general, the unwritten rule is to read source code of widely deployed web applications.

 

I'd be careful with that. Some applications are written poorly and beginner programmers will most likely not realize that when reading its code.

Link to comment
Share on other sites

The Dog/Animal thing just doesn't cut it.  Never has, really.

 

I disagree (naturally). Abstract examples are great for explaining the underlying principles. Real world examples are not that useful without understanding of them.

Link to comment
Share on other sites

The Dog/Animal thing just doesn't cut it.  Never has, really.

 

I disagree (naturally). Abstract examples are great for explaining the underlying principles. Real world examples are not that useful without understanding of them.

 

Ultimately, I'd have to agree with you.  The dog/animal, vehicle/car examples do illustrate the general principal, idea, and technique, which everyone needs at a beginning level.  My complaint is that they don't cut it as any meaningful example of those principals in the field, and there is a distinct lack of examples that are meaningful.

Link to comment
Share on other sites

  • 2 weeks later...

nloding; Let's say you are working with a language like C++ that has arrays, but they can not be resized easily.  For example in C++ when you create an array you need to know how many items will be in it.  If you create it with storage for 10 items but later need room for 20, you have to allocate more memory and do some data shuffling in memory.  Now I won't go into the different ways of doing this, all I'll say is we want to design our dynamic array class so that I can use code like this:

 

  MyArray arr = new MyArray( 10 ); // grow the array in chunks of 10
  for( int i = 0; i < 10; i++ ) {
    arr[i] = lookUpValue( i );
  }

  // Later in the code we have cause to use indexes 10 through 19.
  // Our array class is smart enough to resize itself automatically, so our
  // client code (i.e. the code below) just uses the indexes as if
  // they were there.
  for( int i = 10; i < 20; i++ ) {
    arr[i] = lookUpValue( i );
  }

 

Now let's say we'd our class MyArray to be able to sort its data.  We'd write a function the client can call like so:

  // Assuming this is a continuation of the code above...
  arr->sort();

 

Let's suppose that MyArray was written as a template, meaning it can hold any type of data: ints, floats, doubles, strings, Employees, Vehicles, LotteryNumbers, etc.

 

How can MyArray have a sort() method?

 

Given two pieces of data A and B, in order to sort them you have to be able to determine if: A < B, A == B, or A > B.  So the sort() method has to know something about the data it holds, which is bad.

 

(Side note, I haven't programmed C++ in a long time so maybe C# or another language would be better for what follows.)

 

So how can we design a generic array class that knows just enough about the data it contains in order to sort it?  By using an interface.  We create an interface ISortable and every object that implements this interface must support the basic equality operators.  We place a restriction on our array class that sort() can only be called on data elements that  implement the ISortable interface.

 

 

Link to comment
Share on other sites

My favourite is when using database extraction. All databases have the same basic methods.

 

We can

-add to them

-delete from them

-browse them

In each of these we can do the same for tables, fields and data etc.

 

So we can make our abstract class one which holds information for each of these, and some common methods.

 

We can then extend this for as many databases as we want. For example in my latest project the default is to use sqllite for the database, but I want to allow the user to use mysql, postgre or virtually any other sql based system out there (and any others, if requested) either with a class I've made by extending the database abstract class, or with their own 10 years down the line when a new system is the norm.

 

Another possible real world version is one of the most common... the user.

class user

class moderator extends user

class admin extends moderator

 

A mod can do everything a user can, and more...An admin can do everything a moderator can, and what a user can, and more. The perfect opportunity to expand on each other!

 

It gets better when you have different types of user, the above isn't so much an abstract useage.

 

How about

abstract user

extended by

-tutor

-classroom assistant

-student

-admin

 

In this case, they dont just extend each other down the line, because although a tutor can do all the user functions they do not do the same things. A tutor can't access the areas a student can, nor can a student access the areas a tutor can... but they share some functionality.

 

I hope one, other or both of those helped!

Link to comment
Share on other sites

  • 3 years later...

Hi all,

 

I'd like to bring this topic back up since it's 2011 and I still have the problem of finding real world examples. I have looked with google and I have tons of php ebooks that barely mention this part of OOP. Daniel10's example is much better than the whole dog/cat or car/van and definitely much better than the foo/bar examples. Daniel10's example is real world and can be explained in the same way as the dog/cat examples but it's easier to understand in my opinion.

 

 

 

I think it would be great for all beginners in the PHP community if we accept that there are tons of dog/cat/car/van/foo/bar examples so understanding the concept at a beginner level is not in question any more.

 

Now truly understanding the concept by seeing how it works in a real world example is what is needed.

 

For example, I tried to understand extending exceptions at php.net http://php.net/manual/en/language.exceptions.extending.php (example 2). I started asking around on forums and was being advised by many people to make an abstract class because it apparently is bad practice to directly extend a core class. I never did find out why this is bad. But anyway, when I asked about how to do this I kept getting the foo/bar and cat/dog responses which made no sense to me at all in the context of creating an abstract class to extend exception and then how to use that class in a real program. It's silly that some people seemed to go so far out of the way to make sure they didn't write the code for me that their examples were just ridiculous. I don't want someone to write an application for me. But for a few real world examples it would be nice to see complete code and an explanation of it.

 

That's the kind of example I would love to see with a explanation of why and how it works. Would anyone like to share abstract classes they use in their own applications and a brief tutorial of the why's and how's? I hope you don't actually have a program for tracking cat/dog inventory or monkey's, giraffes, and tigers at your imaginary zoo. :-)

 

Thank you to anyone who wants share your knowledge and skill so beginners can learn something real.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.