Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependencies inside an object

I have this code

class Duck {
  protected $strVocabulary;
  public function Learn() {
   $this->strVocabulary = 'quack';
  }

  public function Quack() {
   echo $this->strVocabulary;
  }
}

The code is in PHP but the question is not PHP dependent. Before it knows to Quack a duck has to Learn.

My question is: How do I make Quack() invokable only after Learn() has been called?

like image 368
johnlemon Avatar asked Sep 14 '11 20:09

johnlemon


People also ask

What is an object dependency?

An object dependency means that in order to operate on an object, the object that is being operated on must reference metadata for itself or reference metadata for at least one other object.

How are dependencies injected in to an object?

The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.

How do objects get dependencies?

When a new object is required, its dependencies need to be assigned to concrete classes. This task can be delegated to a container. When an instance of a particular type is requested to a container, it will inject the implementations required by that type.

What is dependency in OOP?

In object-oriented programming (OOP) software design, dependency injection (DI) is the process of supplying a resource that a given piece of code requires. The required resource, which is often a component of the application itself, is called a dependency.


1 Answers

No, that does not violate any OOP principle.

A prominent example is an object who's behavior depends on whether a connection is established or not (e.g. function doNetworkStuff() depends on openConnection()).

In Java, there is even a typestate checker, which performs such checks (whether Duck can already Quack()) at compile time. I often have such dependencies as preconditions for interfaces, and use a forwarding class whose sole purpose is protocolling and checking the state of the object it forwards to, i.e. protocol which functions have been called on the object, and throw exceptions (e.g. InvalidStateException) when the preconditions are not met.

A design pattern that handles this is state: It allows an object to alter its behavior when its internal state changes. The object will appear to change its class. The design pattern book from the Gang of Four also uses the example above of a network connection either being established or not.

like image 67
DaveFar Avatar answered Oct 13 '22 00:10

DaveFar