OOP Principles Flashcards

1
Q

A design pattern consists of how many parts, and what are they?

A
Four parts:
The name
The problem
The solution
The consequences
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why would a design pattern like “Front Controller” possibly be unsuitable for PHP?

A

PHP scripts run every time a request is made of them - Front Controller can require some heavy startup time (unlike say Java) NOTE: It can be used, if PHP’s limitations or operating environment is considered in the design process

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Favour ‘what’ over inheritance?

A

Composition

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the Strategy pattern used for?

A

Strategy is used to move a set of algorithms into it’s own type. That way the implementation of an algorithm is separate from the implementation of a specific set of objects, reducing duplication of code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is delegation?

A

It is where an object assigns a task to another object (the delegate).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is composition?

A

It is combining simple objects or data types into more complex ones.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why could composition make code more flexible?

A

Objects can be combined to handle tasks dynamically and in many more ways than can be anticipated in the class hierarchy alone.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Is tight coupling good or bad?

A

Bad - it describes when there is a lot of interdependency between objects, which makes changes difficult later

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Code to an ….. not an ……?

A

Code to an INTERFACE not an IMPLEMENTATION.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

In OOP design, to what does the phrase “Encapsulate that which varies” refer to?

A

If there is a varying concept (for example, a costing algorithm is selected based on conditions) - this is a candidate for polymorphism. Each alternative in a suspect conditional may be extracted to form a class extending a common abstract parent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is YAGNI?

A

“You Aren’t Going to Need It” - referring to application features, but also used when describing patterns. Based on XP principles, i.e. don’t overuse patterns!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Name some patterns involved in object creation?

A

Singleton Pattern
Factory Method Pattern
Abstract Factory Pattern
The Prototype Pattern

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is meant by “delegate object instantiation”?

A

In good OOP design, it’s not appropriate to create specific objects within another class (tight coupling). It’s better if the object can be passed a concrete class, preferably using polymorphism (method with an abstract base class as an argument).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Why are global variables bad in OOP?

A

They tie objects into their context, and break the principle of encapsulation. Also - because PHP wont warn you when globals collide, an important value may be overridden unknowingly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a DSN and what does it do?

A

Data Source Name - holds information about a database and it’s tables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a consequence of the Singleton pattern?

A

It’s better than using global variables, as the value can never be written unwittingly by another variable - BUT it does have to be used sparingly. It can create dependancies, and because it bypasses the method interface, it’s use can be hidden inside functions - making relationships hard to spot.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Conditionals can be a sign that code is ‘not right’ - when is it usually fine however?

A

Object creation in factory methods often requires a lot of conditionals.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

If I have a factory method in an imaginary ‘CommsManager’ class - and I notice I’m starting to use conditionals in code to provide services as CommsManager starts to support new protocols - what should I do?

A

Look into inheritance. You can use polymorphism to encapsulate the creation of concrete objects. I would subclass CommsManager for each protocol, and it should implement it’s own factory method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is one of the negatives of factory method patterns?

A

In can encourage unnecessary subclassing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Factory pattern is often used in conjunction with what other pattern?

A

Abstract Factory Pattern

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

When is an Abstract Factory Pattern useful?

A

Factory patterns are excellent for horizontal extension (i.e. adding more encoding types) - but fail when it comes to dealing with a related set of classes (i.e. vertical growth).
i.e. I have appointments, and I want to encode for text, and xml. Perfect for Factory pattern - but what If I want to add to do lists, contact lists, but still want to handle text and xml?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

In C++ and Java, you generally have to have a factory function for each return type, because they enforce return types - how can PHP’s flexibility be used to benefit here?

A

You can use a single make function that makes use of constants (similar to enums) to choose which object to create, and return that type. Even though you can do this - it’s probably not desirable, as you are now ensuring you have to implement this switch statement in every concrete creators. Client classes also, cannot be certain that all concrete generators all the same products, as the interals of the make() function are a matter of choice.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Does the prototype pattern primarily make use of inheritance or composition?

A

Composition (although there is inheritance to allow for polymorphism)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the defining feature of the Prototype pattern?

A

It’s a type of factory pattern, that makes use of PHP’s clone feature. Essentially, you create a ‘factory’ class that takes as a parameter a group of objects that are linked in concept, but different types (i.e. sea, plains, forest terrain). Then you cache an instance of these. When a user requests one, you clone the original object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

If you implement a prototype pattern, and your objects that are passed into a factory also reference objects, what must you do?

A

Implement the __clone method on those objects, so it does a deep copy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is one other benefit of using the prototype pattern in relation to the data stored in each of the cached objects?

A

This is copied and handed down to the cloned objects, which means you can initialise them with information that is important to their operation once - and all objects created by the factory get that data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

By providing implementations for addUnit and removeUnit in the abstract base class for a Composite pattern, what is one of the risks you run in a large project?

A

There is no compile time enforcement to ensure someone implementing a Composite implements the addUnit and removeUnit methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Why are composite patterns useful?

A

Flexible (because everything in the composite pattern shares a common supertype, it’s very easy to add new composite or leafe objects to the design without changing the wider context.

It’s simple, the client using the composite structure has a straightforward interface.

Objects in the composite pattern are organised in a tree, so manipulating one can have a large affect on many objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

If a subclass extends an abstract class, and does not implement all of the abstract methods, what must the subclass be declared as?

A

Abstract

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What is the decorator pattern useful for?

A

It can be used to extend the functionality of an object at run time (decorate it).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is the main characteristic of the decorator pattern?

A

It uses inheritance, composition and delegation. Decorator objects are typically derived from the same parent as the objects you are trying to decorate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the facade pattern useful for?

A

Providing a simple, clear interface to complex systems.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the facade pattern?

A

It’s about simplifying the interface. Creating a single point of entry for a tier or subsystem.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

In PHP a facade pattern can also be used to…

A

encapsulate blocks of procedural code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What pattern is useful if we want the client to be as divorced as possible from a class, but still want to know when events occur so we can react to it?

A

The observer pattern

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is the key element of the observer pattern?

A

The observer (client) registers itself to a central class that we wish to observe (the subject). To this end, the subject will implement an interface “Observable” that exposes the methods, attach, detach, notify.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Which object is responsible for providing the methods that an observer can use to query the state?

A

The subject object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is a registry?

A

An object / class that provides access to data, either via static methods, or a singleton object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

The registry pattern may also be known as…

A

whiteboard or blackboard (because it’s like someone leaving a sticky note on a whiteboard for the next person to come along and get the information)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is dependency injection?

A

In poorly designed OO code, a client may have a hard coded dependency to a service - this creates tight coupling. By making the client receive the service via a parameter (i.e. through the constructor) and ideally through an interface, the dependency is now reduced - you have injected the dependency into the client, rather than tightly coupling it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What are the three types of dependency injection?

A

Constructor injection
Setter injection
Interface injection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is one test to see if you have tight coupling?

A

If you can examine only the client code and determine what framework is being used, the client has a hard coded dependency on the framework

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is the most common way to write the prototype pattern (modern Javascript)?

A

To overwrite the prototype of a function using an object literal.

function Person() { }
Person.prototype = {
  name: "Foobar",
  age: 23
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What is one caveat of overwriting a functions prototype using an object literal (and how do you get around it)?

A

You cannot use the functions constructor to determine the type - you should use instanceof.

friend instanceof Person; // true (do it this way)
friend.constructor == Person; // false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

If, when using the object literal to overwrite the default prototype - you need the constructor to be available - how would make this happen?

A
function Person() { }
Person.prototype = {
  constructor: Person,
  // Other stuff
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

If you create an object at runtime, then add a new member to the prototype - will this be reflected on the already created object?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

If you create an object at runtime, then overwrite the prototype that the object has a reference to - can you access members on the original prototype?

A

No - if the prototype itself is overwritten, then any pre-existing objects will not point to the new prototype - and therefore not have access to it’s methods

48
Q

To avoid the issues inherent with the prototype patterns, what is the most common - accepted method of writing custom types?

A

Mix of constructor / prototype method:

function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
  this.friends = ["Shelby", "Colby"];
}
Person.prototype = {
  constructor: Person,
  sayName : function() {
    alert(this.name);
  }
}
49
Q

What is an ORM framework?

A

ORM stands for Object Relational Mapping - maps classes to database tables such that each object represents a table row.

50
Q

What is SOLID?

A
An acronym that stands for:
Single Responsibility
Open Closed
Liskov substitution
Interface segregation
Dependency Inversion
51
Q

What does ‘Single Responsibility’ in SOLID mean?

A

A class should only have one responsibility or one focus.

52
Q

What does ‘Open/Closed’ mean with regards to SOLID?

A

Software entities should be open for extension, but closed to modification.

53
Q

What is ‘Liskov substitution’ mean with regards to SOLID?

A

Objects in a program should be replacable with instances of their subtypes without altering the correctness of the program.

54
Q

What is the ‘Interface segregation principle’ with regards to SOLID?

A

Many client specific interfaces are better than one general purpose interface.

55
Q

What is ‘dependency inversion’ with regards to SOLID?

A

One should depend upon abstractions, not concretions.

56
Q

Is ‘var’ a valid property type in a class?

A

Yes.

57
Q

How do you declare a constant value in a PHP object?

A

const MY_CONST = ‘a constant’;

58
Q

To what does the ‘T_PAAMAYIM_NEKUDOTAYIM’ error refer to?

A

To the double colon, ‘::’, scope operator.

59
Q

If I am going to refer to a static property ‘myProperty’ in a class, what is the syntax?

A

MyClass::$myProperty;

NOTE: the $ sign

60
Q

If I am going to refer to a static method ‘myMethod’ in a class, what is the syntax?

A

MyClass::myMethod();

NOTE: The lack of $ sign

61
Q

If I am going to refer to a static property ‘myProperty’ within the same class, what would the syntax be?

A

self::$myProperty;

62
Q

If I am going to refer to a static method ‘myMethod’ within the same class, what would the syntax be?

A

self::myMethod();

63
Q

If I am in an instantiated class, and I want to refer to the overridden parent function ‘chickenLicken’, what is the syntax?

A

parent::chickenLicken();

64
Q

How are constants accessed?

A

self::MY_CONSTANT; (from within class)
myClass::MY_CONSTANT; (from outside)

65
Q

Can constants be private or protected?

A

No

66
Q

If MY_VALUE is a constant, is $this->MY_VALUE; a valid call?

A

No, constants are not able to accessed via the this operator.

67
Q

A final method is not…

A

extensible - i.e. a child class cannot override it.

68
Q

Can PHP traits be typehinted?

A

No

69
Q

If a PHP trait contains an abstract method, does it have to be declared abstract?

A

No - since traits cannot be instantiated directly anyway, it’s not relevant.

70
Q

Can traits specify properties?

A

Yes - of any type (private, protected etc)

71
Q

If trait A and trait B are used by a class, and there is a function conflict (i.e. two with the same name) how do you resolve this?

A

You must specify how to resolve the conflict.

// A and B are traits
class Test {
   use A, B {
       A::testFunction instead of B;
       B::testFunction as world;
   }
}
72
Q

What is the best practice for the __construct method?

A

Just use it for configuration - do not do any actual work (makes testing hard)

73
Q

What is one use for the __destruct method?

A

Cacheing - storing the data that was in the object at the point of destruction, or closing database connections.

74
Q

What is the best use of the __call and __callStatic magic methods?

A

Accessing dynamic methods that may not be defined in code (however, these methods are probably best used sparingly).

75
Q

What is the single responsibility principle?

A

An object should have one and only responsibility and additional responsibilities should be handed out to other objects.

76
Q

Assuming DBDriver is a class - is the following code tightly coupled?

class MyClass
{
   protected $pdo_object;
   public function \_\_construct(DBDriver $db)
   {
      $this->pdo_object = $db;
   }
}
A

Yes.

This is because DBDriver (class) would always need to be present for this code to work - in order to create loose coupling, the same code, but using an interface rather than a specific class to pass the driver would decouple MyClass from the database driver.

77
Q

How does using an interface assist with unit testing?

A

If the class required a specific object, you would be bound by it’s implementation. However, given an interface, unit tests can be written that provide the correct interface without requiring change to the object being tested.

78
Q

A unit test method would normally do what?

A

Return data that pretends (but isn’t) similar to live data.

79
Q

In an MVC architecture, which element does the user interact with?

A

The view

80
Q

In an MVC architecture, which element would be responsible for instantiating the majority of objects (for dependency injection)?

A

The Controller - passing them onto the model or view (most likely the model).

81
Q

Which element of an MVC architecture should hold the business logic?

A

The model.

82
Q

What is the ‘domain model’?

A

A conceptual model of a system, which describes the various entities within that system and their relationships.

83
Q

Exceptions should be handled…

A

in the layer that raised them.

84
Q

What is one important consideration when creating a ‘fluent interface’ (i.e. chaining method calls by returning $this)

A

They should only be implemented if each method returns the same object, not a new object - as it can cause confusion when reading the code.

85
Q

What is a ‘service’ in OO programming?

A

Any object that performs a global service, such as a Database abstraction object, or dependency injection container.

86
Q

What is the difference between aggregation and composition?

A

In composition, when the containing object is destroyed, all of the objects that make up the composition are destroyed - there is implied ownership.

This is not necessarily the case with aggregation, where the objects may have a life of their own outside of the aggregation. So in aggregation - it typically only holds a reference or pointer to the object, and doesn’t maintain lifetime responsibility for the object.

Aggregation may be referred to composition if the distinction is unimportant.

87
Q

In terms of PHP, what is the difference between implementation and inheritance.

A

Implementation refers to a class implementing an interface, and inheritance usually refers to a class inheriting from an Abstract (or other type) of class. Since in inheriting from an Abstract class requires implementation, the terms can be used interchangeably in practise.

88
Q

What is the difference between Service Locator and Dependency Injection Container?

A

They are very similar, but the differences lay mainly in the wiring - a Service locator will typically be used within the class, resulting in tight coupling between the service locator and the class. Whereas the DI Container will be practically invisible to the application, only appear at the top level (bootstrap code) and injecting the dependencies (usually through the constructor or setters) into the underlying app.

As a result, the Service Locator (while being very similar in structure to a DIC) will probably have static methods, so that it can be accessed globally.

89
Q

What is Fowler’s definition of a component?

A

A ‘glob’ of software that is intended to be used without change (i.e. modification to the software), and is out of the control of the writers of the component. The application writers only change the behaviour of the component through extending it’s behaviour in ways allowed by the original authors of the component.

90
Q

What is Fowler’s definition of a service?

A

A service is similar to a component, in that it is used by a foreign application. A service is usually used through some kind of remote interface, RPC, web service, socket etc. Database layer would be an example of a service.

91
Q

Is Inversion of Control specific to Direct Injection Containers?

A

No - as a term it references any programming paradigm where the traditional control has been inverted. For instance - in a UI, the old days - you would right the main loop that drove the user input collection. Later, that was hidden in a framework, and you just added hooks (events). This ‘inverted the control’ to the framework. DI - is the same idea - creation of the object is no longer best handled inside the object (the object doesn’t create the instance) it is handled elsewhere (via a DIC for instance).

92
Q

What is the goal of Inversion of Control with regards to DI Containers?

A

We want the components we inject into a class to be ‘plugins’. So they can be swapped, or mocked easily. By letting the class instantiate the requested object itself, it is no longer a plugin, and is tightly coupled, and prevents easy replacement (for mocking / testing / re-use).

93
Q

What are the three main types of dependency injection?

A

Constructor, Setter and Interface injection.

94
Q

What is a DSL (Domain Specific Language)?

A

A language that is written specifically for use in a single domain (for example, Game Maker Pro script) - this is in contrast to a GPL - or general purpose language such as C or C++.

95
Q

What is the fundamental difference between a service locator and dependency injection container?

A

The service locator must send a request to the locator to receive the service. However, with DIC, there is no request, the service just appears in the class (hence, inversion of control).

96
Q

What is the major benefit of using a service locator vs a dependancy injection container?

A

The service locator is very easy to understand. IoC (via dependency injection container) can be difficult to debug.

97
Q

What is the major disadvantage of a service locator vs dependency injection container?

A

Using a service locator creates a dependency between every client that uses it, and the locator.

98
Q

Which is better for testing, Dependency Injection Container, or Service Locator?

A

Many will say DIC, however, they should be both be fine for stubbing. (Since you configure, in both scenarios how the object is constructed via a registry interface - you can just swap out the object for a stub at this point, and whether it is Direct Injected, or located by the service locator, you should end up with the same object).

99
Q

Why might you consider using Direct Injection Containers over Service Locators?

A

If you are providing code as a component to an outside customer, without knowing how their service locators work, it may be best to use a DI container - that way they only have to worry about passing the fully constructed object to the class - rather than having to make their Service Locator work with your Service Locator (adapter pattern?).

100
Q

What an advantage of setter / constructor injection over interface injection?

A

Interface Injection can be more invasive, since you require more Interfaces to be written, wired up to the components for it to work.

101
Q

The law of Demeter states that a method on an object is allowed to interact with what?

A
  1. Other methods on it’s object
  2. Methods on properties of its object
  3. Methods on arguments passed into the method
  4. Methods on instances of new objects created inside of the method
102
Q

What is a dependency graph?

A

From an OO Programming point of view (in a simple case) - it describes when an object has required references to other objects, i.e. A depends on B depends on C. This can be seen when calling code like this:

$obj = new User(‘username’, new Profile(new Photo(‘image.gif’))));

User depends on Profile depends on Photo - the dependency graph.

103
Q

Given an object that has a dependency graph such as User -> Profile -> Photo. What is wrong with the following code?

$photo = $user->getProfile()->getPhoto();

A

Profile and Photo are encapsulated within the User class. By asking the consumer of the code to know about the dependency graph, and understand the requirements of getting the photo in this way, we are creating a poor OO interface.

104
Q

Is method chaining valid under the law of demeter?

A

Yes, but it is best not to reach too far down the dependency graph. Keep it simple. Use the law of Demeter to influence how you expose the internal objects through the top level object (i.e. write interfaces that return the requested information - letting the top level object handle all of the checks) - make sure that object will return something useful. Makes for cleaner code.

105
Q

The law of Demeter is also known as…? Why?

A

Tell / Don’t Ask

Because we tell the object what information we want, rather than asking whether it has the information before requesting it.

106
Q

What is the trade off of using type hinting (rather than ducktyping) to ensure a method is present on an object?

A

In PHP - if you type hint on an interface, you would be precluded from using decorator objects.

107
Q

If your decorator object could just implement the interface, it could then work in a type hinted function - but why is this a bad idea?

A

The decorator object may have to implement many methods that are not used, just so you can use the decorator object - better to just use duck typing.

108
Q

Inheritance is designed for…

A

Specialisation - so the child classes will often only do the things that make them different to the parent. (Although, this is not always the case)

109
Q

I have a Project base class, and an ArchivedProject, and OpenProject subclass. How do I stop someone from instantiating the base class instead of the subclasses?

A

Declare it as abstract.

110
Q

What is a ‘higher order function’?

A

A function that takes in functions as input, or returns another function as output.

111
Q

What is a ‘first class function’?

A

A language is said to support first class functions if they can be treated as a ‘first class citizen’ - as in, similar to other data types - basically if they can be passed as arguments to to other functions.

112
Q

A lot of examples of the factory pattern use switch statements to demonstrate how to call a class that is to be created - this inflexible - how should you do it?

A

You can use ‘class_exists’ to determine dynamically if a class (based on a string) exists (this can even be used to autoload the class if it doesn’t) - or you can use reflection. ReflectionClass method.

113
Q

What does the concept of command / query separation mean?

A

Any command should do something, but not reply, or any query should do nothing, but return something.

114
Q

What is the major difference between the adapter and facade patterns?

A

The adapter creates a common interface for similar objects - the facade pattern creates an interface for unrelated objects.

115
Q

PHP doesn’t use true MVC, what design pattern is it actually very similar too?

A

The mediator pattern.

116
Q

What is the Service / Mapper / Model pattern?

A

It’s not a ‘pattern’ per se - but is an enterprise method for modelling / getting data, it makes sure the model is not bound to a datasource.

The client interacts with service. The service knows about the mapper and the model. The client creates a new user. Uses the mapper to get the data. Then updates the model, returning it to the client.

The model should only know about itself.
Mapper should connect to MySql, retrieve data and apply it to the model.
Service is initialised in the controller and should return the model for the requested object (based on data i.e. id).