When and why use object as a class property - oop

Currently i am learning swift. I need a concept of OOP. Suppose, i have two classes
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
Person class use a object of Residence as a property. Please tell me When and why use object as a class property?

What you are describing here is called composition and it's an important OOP principle. Composition is being described as a has-a relation - in your example a Person has-a residence. As to when use it, it helps if you ask yourself if there is a has-a relation between your objects.
Another very common example of composition would be a car class which has-a (okay has-four) wheel(s) - code is in Java:
class Car {
private Wheel[] wheels;
}

Related

General code design: shared and alternating patterns

The situation
My question applies to all programming languages with classes and inheritance. Im sure the answer is out there somewhere already, but I could not find it as i don’t have the right terminology to use.
Lets take the classic example. We got Dogs and Cats which are both of the type Animal:
abstract class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
Simple enough. Some behavior is shared in the Animal class, anything that differs between Cat and Dog is coded in their respective classes.
Now suppose we got 2 planets. Earth and Mars. Both planets have Cats and Dogs. But, behavior for all animals on Earth differs from all animals on Mars. They, for example, experience a difference in gravity which affects the way they move.
There is no difference between specific animal types between the planets. Thus, all differences between animals on Earth and Mars can be coded at the parent level, that of the Animal class.
Not only that, but some behavior is available for all Animal instances on Mars that does not exist on Earth.
Ideally, in code dealing with these animals, we deal with a MarsAnimal or EarthAnimal class that is implemented by either a Dog or Cat. The implementing code does not need to know if they are Dogs or Cats. It does already know on what planet the Animal lives though.
What I thought about already
One solution would be the following:
abstract class Animal {
}
abstract class Cat extends Animal {
}
abstract class Dog extends Animal {
}
interface MarsAnimal {
}
interface EarthAnimal {
}
class MarsCat extends Cat implements MarsAnimal {
}
class MarsDog extends Dog implements MarsAnimal {
}
class EarthCat extends Cat implements EarthAnimal {
}
class EarthDog extends Dog implements EarthAnimal {
}
Ofc, the obvious problem with this is, that any behavior specific to MarsAnimal would need to be implemented in both the MarsCat and MarsDog classes. That’s ugly code duplication and definitely not what I was looking for.
The only semi-acceptable method I could think of was the following:
abstract class Animal {
private PlanetAnimal planetAnimal;
public function myBehavior() {
this.planetAnimal.myBehavior();
}
}
class Cat extends Animal {
}
class Dog extends Animal {
}
interface PlanetAnimal {
function myBehavior();
}
class MarsAnimal implements PlanetAnimal {
public function myBehavior() {
// marsAnimal- specific behavior here
}
}
class EarthAnimal implements PlanetAnimal {
public function myBehavior() {
// earthAnimal- specific behavior here
}
}
Thus, when creating a Cat or Dog instance, since we know what planet they are from at that point in the code, we give them the needed PlanetAnimal instance in their constructor (either MarsAnimal or EarthAnimal).
This is close. The only problem with this is, like I said, some behavior exists only for all animals on Mars. I’d have to still implement a method in both the Animal and PlanetAnimal classes that is used only for Mars. If this is the only solution then sure, but it feels like there should be some better method out there.
So, any ideas? I’d love to hear!
Edit 1
Based on questions, a small clarification: the main problem here is how to implement shared behavior between many different categories. There is shared behavior:
between all animals on all planets;
between all animals on a specific planet;
between all animals of a specific type (i.e. Cat or Dog), irrespective of what planet they are on
Edit 2
I work mainly in Java and PHP. This question specifically was asked after I encountered this in PHP, though I know I had similar situations in Java too. I know, for PHP, my first proposed solution could work in combination with Traits. That might even be where I end up. But, everywhere online I saw people warning against the use of Traits, saying it is almost always/ always bad code design. That's why I'm searching for the best solution
The solution you are looking for is a design pattern called the Strategy pattern. The pattern is defined as follows:
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
In your case, the Animal class would be the context, and the PlanetAnimal class would be the strategy. The context would be responsible for delegating to the correct strategy for each concrete implementation. In your example, the context would be the Animal class, and the strategy would be the PlanetAnimal class. The context would be responsible for delegating to the correct strategy for each concrete implementation.
Something like this, in Python:
class Animal:
def __init__(self, animalStrategy):
self.animalStrategy = animalStrategy
def walking(self):
raise NotImplementedError()
class Cat(Animal):
def walking(self):
return self.animalStrategy.walking(canJump=True, canFly=False, canSwim=False, speed=10)
class Bird(Animal):
def walking(self):
return self.animalStrategy.walking(canJump=True, canFly=True, canSwim=False, speed=20, walkSpeed=2)
class MarsAnimalStrategy:
def walking(self, canJump, canFly, canSwim, speed):
return f"walking on Mars with speed {speed}"
class EarthAnimalStrategy:
def walking(self, canJump, canFly, canSwim, speed, walkSpeed):
return f"walking on Earth with speed {speed} and walkSpeed {walkSpeed}"
marsCat = Cat(MarsAnimalStrategy())
marsCat.walking()
earthCat = Cat(EarthAnimalStrategy())
earthCat.walking()
In this way, the Animal class is not responsible for knowing how to walk on Mars or Earth, but instead delegates that responsibility to the strategy. The strategy is responsible for knowing how to walk on Mars or Earth. The context/"user" is responsible for delegating to the correct strategy for each concrete instance.
I wouldn't go into details, but consider using a composition of objects instead of class inheritance. In short, each descendant class of Animal would have to be fully tested, including an internal behavior of a parent class, and Animal could easily become a God Object, which is not a good thing. Alternatively:
class IAnimal: # Python have only classes, but consider it as an interface
def walking(self):
raise NotImplementedError()
def eating(self):
raise NotImplementedError()
# etc.
class Cat(IAnimal):
def __init__(self, physicalBody, livingEntity):
self.physicalBody = physicalBody
self.livingEntity = livingEntity
def walking(self):
direction = self.livingEntity.goalDirection()
if self.physicalBody.canMove(direction):
self.physicalBody.move(direction)
return self.livingEntity.movedTo(self.physicalBody.position)
return self.livingEntity.wasFrustrated()
Now Cat is responsible only for its own behavior, and PhysicalBody and LivingEntity are responsible for their own behavior. This way, you can easily test each class separately, and you can easily replace PhysicalBody and LivingEntity with other implementations, without changing Cat class. I would repeat, that now Cat class is highly focused solely on its own behavior and implementation of IAnimal interface/contract. Now, of course, you need to type self.physicalBody.canMove(direction) instead of self.canMove(direction), but it's a small price to pay for a better design. Differences in the behavior of Earth and Mars animals would now be represented by different implementations of LivingEntity classes, that could share some common parts.

Real Life example of Polymorphism from Class Room

Once my teacher asked me to give example of polymorphism from class room.
I told him that you are best example of polymorphism. As in college you are a teacher and in home you are husband or father. So your are one method but in different states you are behaving accordingly. And also you are extending human so you can be treated polymorphically as human.
(Considering in mind definition of polymorphism: Acquiring more than one form)
Can it be consider as good example of polymorphism ?
Thanks.
In your example, you give different behaviours for different states.
In OOP this is expressed through interfaces.
So, it would be modelled something like this:
class Human
{
Date Birthdate;
}
interface ITeacher
{
void Teach();
}
interface IHusband
{
void Pray();
}
interface IFather
{
void Love(); // methods in IFather and IHusband can be interchanged
}
class Person extends Human implements ITeacher, IHusband, IFather
{
// implementations inserted here
}
Now you can use those behaviours and the fact that he is a human in different cases.
Like:
Human yourTeacher = new Human("1970/05/01");
Class class = new Class();
class.Teachers.Add(yourTeacher); // expecting that it is a collection of ITeachers.
Pub pub = new Pub();
pub.DrunkPeople.Add(yourTeacher); // accepting only humans older than 21 here
So, polymorphism is about ONE object that behaves different in different cases... and inheritance.

Factory method and parallel class hierarchy

Dog is-a Animal.
Animal has-a House.
DogHouse is-a House.
A factory method ensures that Dog's House is-a DogHouse, but it's still typed as a House and I need it typed as a DogHouse.
There are lots of ways to solve this, but I'm wondering if there's a standard way. I'm writing in Objective C.
Generics.
For example, in Java:
interface Animal<T extends House> {
T getHouse();
}
class Dog implements Animal<DogHouse> {
private final DogHouse dh = new DogHouse();
#Override
public DogHouse getHouse() {
return dh;
}
}

Multiple Inheritance: What's a good example?

I'm trying to find a good example for the use of multiple inheritance what cannot be done with normal interfaces.
I think it's pretty hard to find such an example which cannot be modeled in another way.
Edit: I mean, can someone name me a good real-world example of when you NEED to use multiple inheritance to implement this example as clean as possible. And it should not make use of multiple interfaces, just the way you can inherit multiple classes in C++.
The following is a classic:
class Animal {
public:
virtual void eat();
};
class Mammal : public Animal {
public:
virtual void breathe();
};
class WingedAnimal : public Animal {
public:
virtual void flap();
};
// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {
};
Source: wiki.
One example where multiple class inheritance makes sense is the Observer pattern. This pattern describes two actors, the observer and the observable, and the former wants to be notified when the latter changes its object state.
A simplified version for notifying clients can look like this in C#:
public abstract class Observable
{
private readonly List<IObserver> _observers = new List<IObserver>();
// Objects that want to be notified when something changes in
// the observable can call this method
public void Subscribe(IObserver observer)
{
_observers.Add(observer);
}
// Subclasses can call this method when something changes
// to notify all observers
protected void Notify()
{
foreach (var observer in _observers)
observer.Notify();
}
}
This basically is the core logic you need to notify all the registered observers. You could make any class observable by deriving from this class, but as C# does only support single class inheritance, you are limited to not derive from another class. Something like this wouldn't work:
public class ImportantBaseClass { /* Members */ }
public class MyObservableSubclass : ImportantBaseClass, Observable { /* Members */ }
In these cases you often have to replicate the code that makes subclasses observable in all of them, basically violating the Don't Repeat Yourself and the Single Point of Truth principles (if you did MVVM in C#, think about it: how often did you implement the INotifyPropertyChanged interface?). A solution with multiple class inheritance would be much cleaner in my opinion. In C++, the above example would compile just fine.
Uncle Bob wrote an interesting article about this, that is where I got the example from. But this problem often applies to all interfaces that are *able (e.g. comparable, equatable, enumerable, etc.): a multiple class inheritance version is often cleaner in these cases, as stated by Bertrand Meyer in his book "Object-Oriented Software Construction".

What is composition as it relates to object oriented design?

I hear (and read on this site) a lot about "favour composition over inheritance".
But what is Compositon? I understand inheritance from the point of Person : Mammal : Animal, but I can't really see the definition of Compostion anywhere.. Can somebody fill me in?
Composition refers to combining simple types to make more complex ones. In your example, composition could be:
Animal:
Skin animalSkin
Organs animalOrgans
Mammal::Animal:
Hair/fur mammalFur
warm-blooded-based_cirulation_system heartAndStuff
Person::Mammal:
string firstName
string lastName
If you wanted to go totally composition (and get rid of all inheritance) it would look like this:
Animal:
Skin animalSkin
Organs animalOrgans
Mammal:
private Animal _animalRef
Hair/fur mammalFur
warm-blooded-based_cirulation_system heartAndStuff
Person:
private Mammal _mammalRef
string firstName
string lastName
The advantage to this approach is that the types Mammal and Person do not have to conform to the interface of their previous parent. This could be a good thing because sometimes a change to the superclass can have serious effects on the subclasses.
They still can have access to the properties and behaviours of these classes through their private instances of these classes, and if they want to expose these former-superclass behaviours, they can simply wrap them in a public method.
I found a good link with good examples here: http://www.artima.com/designtechniques/compoinh.html
Composition is simply the parts that make up the whole. A car has wheels, an engine, and seats. Inheritance is a "is a " relationship. Composition is a "has a" relationship.
There are three ways to give behavior to a class. You can write that behavior into the class; you can inherit from a class that has the desired behavior; or you can incorporate a class with the desired behavior into your class as a field, or member variable. The last two represent forms of code reuse, and the final one - composition - is generally preferred. It doesn't actually give your class the desired behavior - you still need to call the method on the field - but it puts fewer constraints on your class design and results in easier to test and easier to debug code. Inheritance has its place, but composition should be preferred.
class Engine
{
}
class Automobile
{
}
class Car extends Automobile // car "is a" automobile //inheritance here
{
Engine engine; // car "has a" engine //composition here
}
Composition - Functionality of an object is made up of an aggregate of different classes. In practice, this means holding a pointer to another class to which work is deferred.
Inheritance - Functionality of an object is made up of it's own functionality plus functionality from its parent classes.
As to why composition is preferred over inheritance, take a look at the Circle-ellipse problem.
An example of Composition is where you have an instance of a class within another class, instead of inheriting from it
This page has a good article explaining why people say "favour composition over inheritance" with some examples of why.
composition
simply mean using instance variables that are references to other objects.
For an illustration of how inheritance compares to composition in the code reuse department, consider this very simple example:
1- Code via inheritance
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple extends Fruit {
}
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
When you run the Example1 application, it will print out "Peeling is appealing.", because Apple inherits (reuses) Fruit's implementation of peel(). If at some point in the future, however, you wish to change the return value of peel() to type Peel, you will break the code for Example1. Your change to Fruit breaks Example1's code even though Example1 uses Apple directly and never explicitly mentions Fruit.
for more info ref
Here's what that would look like:
class Peel {
private int peelCount;
public Peel(int peelCount) {
this.peelCount = peelCount;
}
public int getPeelCount() {
return peelCount;
}
//...
}
class Fruit {
// Return a Peel object that
// results from the peeling activity.
public Peel peel() {
System.out.println("Peeling is appealing.");
return new Peel(1);
}
}
// Apple still compiles and works fine
class Apple extends Fruit {
}
// This old implementation of Example1
// is broken and won't compile.
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
2- Code via composition
Composition provides an alternative way for Apple to reuse Fruit's implementation of peel(). Instead of extending Fruit, Apple can hold a reference to a Fruit instance and define its own peel() method that simply invokes peel() on the Fruit. Here's the code:
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return fruit.peel();
}
}
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
for more information ref