Page 1 of 1

objects that interact with each other

Posted: Tue Oct 26, 2010 5:48 am
by s.dot
Consider the following example:

Code: Select all

<?php

class people
{
	private $people
	
	function doSomething()
	{
		foreach ($this->$people AS $person)
		{
			//
		}
	}
	
	function addPerson($person)
	{
		$this->people[] = $person;
	}
}

class person
{
	private $name;
	private $age;
	private $etc;
	
	function setName($name){}
	function setAge($age){}
	function setEtc($etc){}
}

$people = new people();

$bob = new person();
$bob->setName('bob');
$bob->setAge(33);
$bob->setEtc('etc');

$people->addPerson($bob);
Should person class extends people class and perhaps have a method called add()? which adds it to the people property? Or should it be two separate classes like I have it above?

EDIT| This is pseudo-code.. it's just the concept I'm after.

Re: objects that interact with each other

Posted: Tue Oct 26, 2010 8:00 am
by Jenk
"Does X extend or override the behaviour of Y?" is the only question need asking here. :) If yes to either, it's a subclass.

Could also try Composition instead of inheritance. A bit more tricky, but usually more elegant.

Re: objects that interact with each other

Posted: Tue Oct 26, 2010 8:11 am
by s.dot
That is a good question, lol.
It does not extend or override - but it provides information to

Maybe I don't need an additional class?

Re: objects that interact with each other

Posted: Tue Oct 26, 2010 8:23 am
by Eran
Notice what Jenk mentioned - composition. If your People class is a collection of Person classes, then its probably best to use composition instead of inheritance. Of course, when dealing with pseudo code it's rather meaningless - those decisions need to be based on the relationships in the actual application.

Re: objects that interact with each other

Posted: Tue Oct 26, 2010 8:31 am
by s.dot
OK.

The "people" object uses the collection of "person" objects to manipulate data supplied to the "people" class.

I'll just do what I think is best and post it in the critique forum.

Re: objects that interact with each other

Posted: Tue Oct 26, 2010 2:31 pm
by josh
what you are doing is fine, unless you have too much of 'feature envy' code smell http://c2.com/cgi/wiki?FeatureEnvySmell