Naming: Composite vs compound for entities that delegate function calls to array of entities (vs something else?) - naming-conventions

Imagine you have some Entity class and want another class that groups multiple instances of Entity.
How do you name it?
CompoundEntity?
CompositeEntity?
something else?
This is a common thing I do, and my colleagues use different naming convention. I have no idea what is better and also I'm not a native English speaker.
Concrete example:
public final class CompoundSetUpAction: SetUpAction {
private let setUpActions: [SetUpAction]
public init(
setUpActions: [SetUpAction])
{
self.setUpActions = setUpActions
}
public func setUp() -> TearDownAction {
return CompoundTearDownAction(
tearDownActions: Array(setUpActions.map { $0.setUp() }.reversed())
)
}
}

Related

How to Solve Parallel Inheritance Hierarchies when we try to reuse code through inheritance

Recently in a job interview, they ask me "how to solve Parallel Inheritance Hierarchies when we try to reuse code through inheritance". I thought on Aggregation or Composition, but i was a little confused on making an example based on that.
So I decided to leave it pending to deepen concepts later, but after investigating it did not end up forming a precise answer to that question, could someone explain me a solution or an example to this?
Parallel Inheritance Hierarchies makes many unnecessary classes and makes code very fragile and tightly coupled.
For example, we have class Sportsman and its Goal's.
public abstract class Sportsman
{
public string Name { get; set; }
public abstract string ShowGoal();
}
and concrete class Footballer:
public class Footballer : Sportsman
{
public override string ShowGoal()
{
return new FootballerGoal().Get();
}
}
and Runner:
public class Runner : Sportsman
{
public override string ShowGoal()
{
return new RunnerGoal().Get();
}
}
Then we have their goals:
public abstract class Goal
{
public abstract string Get();
}
and its concrete classes:
public class FootballerGoal : Goal
{
public override string Get()
{
return "Score 1 goal";
}
}
And runner goal:
public class RunnerGoal : Goal
{
public override string Get()
{
return "Run 1 km";
}
}
Now, it can be seen that if we add new type of sportsman, then we need add a new class to hierarchy of Goal.
We can try to avoid of creation of that hierarchy tree by using dependency injection and extracting method to interface.
At first, we create interface:
public interface IGoal
{
string Visit(Sportsman sportsman);
}
and then just implement it:
public class FootballerGoal : IGoal
{
public string Visit(Sportsman sportsman)
{
return "Score 1 goal";
}
}
and use it in Footballer class:
public class Footballer : Sportsman
{
public string ShowGoal(IGoal goal)
{
return goal.Visit(this);
}
}
Now we do not have hierarchy tree and we can call it like this:
new Footballer().GetGoal(new FootballerGoal())
UPDATE:
There is a good article about Parallel Inheritance Hierarchies.. It proposes some ways to solve this task. Let me show the third way.
Solution 3 Collapse a hierarchy.
Pros:
Only maintain One hierarchy
Easy to maintain
Cons
Breaks SRP fairly often.
So Footballer class would like this:
public class Footballer : Sportsman
{
public override string ShowGoal()
{
return new FootballerGoal().Get();
}
public string GetGoal()
{
return "Score 1 goal";
}
}
And Runner class would like this:
public class Runner : Sportsman
{
public override string ShowGoal()
{
return new RunnerGoal().Get();
}
public string GetGoal()
{
return "Run 1 km";
}
}
The c2 wiki has a page on parallel inheritance hierarchies where ChaoKuoLin lists four possible solutions. I paraphrase them here, along with some context for each. See the original page for a full explanation including advantages, disadvantages, and examples.
Keep the parallel hierarchies.
When the hierarchies have separate responsibilities and each contains many methods.
When maximum flexibility is required.
Keep one of the hierarchies and collapse the other into a class.
When one of the hierarchies can be reduced to a single class, for example by moving some methods to the other hierarchy.
When one of the hierarchies contains few methods.
Collapse the two hierarchies into one.
When the hierarchies have similar responsibilities and each contains few methods.
Keep a partial parallel hierarchy with the rest collapsed.
When you want a middle ground among the previous solutions.
Another solution suggested in the wiki is Mix In and it is also suggested in How to solve parallel Inheritance in UI case?

How to simply introduce a new method on a large subset of classes implementing an interface?

I have an interface, say IVehicle, which is implemented in 100s of classes, some of them are variety of 4 wheeler and some are two wheeler dervied types.
I need to introduce a new method for all the 4 wheeler classes, lets say there are 50 of them. My challenge is to reduce the effort as much as I can.
I suggested, to introduce a new interface / abstract class with a method definition. But this require to change every 4 wheeler class declaration and extend with an extra parent.
Is there any possible way?
If you really want to avoid changing all those classes and want a solution that can be considered to be OO, one thing you can do is decorate those classes where they are used and need this extra behaviour.
I'll use C# for example code as you mentioned you're looking for C#/Java solution.
interface IVehicle
{
void DoThisNormalThing();
// ...
}
interface IBetterVehicle : IVehicle
{
void DoThisNeatThing();
}
class FourWheelVehicle : IVehicle
{
public void DoThisNormalThing()
{
// ...
}
// ...
}
class BetterFourWheelVehicle : IBetterVehicle
{
private readonly _vehicle;
public BetterFourWheelVehicle(IVehicle vehicle)
{
_vehicle = vehicle;
}
public void DoThisNormalThing()
{
_vehicle.DoThisNormalThing();
}
public void DoThisNeatThing()
{
// ...
}
// ...
}
Then usage:
var vehicle = new FourWheelVehicle();
var betterVehicle = new BetterFourWheelVehicle(vehicle);
betterVehicle.DoThisNeatThing();
This can be done using extension methods as well (and would result in a little less code and fewer allocated objects), but as this question is tagged with [oop] I wouldn't say extension methods are an OO construct. They're much more aligned with procedural style as they turn your objects into bags of procedures.

Design a Furniture class with classes like WoodChair, WoodTable etc

This is an OOD based interview question:
There is a Furniture class and has derived classes like WoodChair, WoodTable, SteelChair, SteelTable. Interviewer wanted to add more number of classes like ironchair,irontable etc; How should we do that. The design is not yet published and we are free to modify the entire sutff given.
I thought that since we're basically building types of furniture we should use a builder pattern here with Furniture class with properties like type (chair/table) and make(iron/wood) etc. Then we'd have an interface Builder with functions like: buildLegs(..), buildSurface(..) and sub-classes like ChairBuilder, TableBuilder and a Director class to instantiate all of them. We could add as many new types of Furniture of any make and construct a builder class for them without affecting existing design.
After reading Builder Vs Decorator pattern I was sure that I'm not supposed to use Decorator pattern here. But is Builder also ok? Is it an overkill?
Also, I'm not sure how to deal with the make of the furniture. Would adding a feature of type enum for the make be enough? [steel, iron, wood] The make doesn't really add any new behavior to the furniture items.
It looks like something needs to be refactored in the existing classes, which may also help avoiding creating a new class for every one of the need that arise in the future. This depends entirely on the context though: an inventory application needs a radically different model of a chair than a software that needs to display a chair in 3d. How do you know? Ask the interviewer, then you will know where they want you to go.
Boring case: a Chair has some common behavior/data that can be refactored out in a different class, same thing for Table. Now how do you choose to represent the material? Again, it depends on the domain, ask the interviewer. It is also a matter of the language you are using: does your language of choice support multiple inheritance? Do you need (or want) to use multiple inheritance at all? It may make sense to favor composition over inheritance. Why would you go one way or the other? Do you even need a class to represent this piece of information?
How should we do that.
Ask the interviewer, they will guide you to the solution. There is no single correct answer to a problem so broadly formulated, they want you to ask questions and see how you think. That said, as broad as the question is, the way it is formulated may be a hint that you should refactor something in order to avoid having to create a class for every new combination of furniture and material.
Possible solutions:
No need for Table/Chair/Bed to inherit from Furniture: a class Furniture with a property for the piece of furniture and a property for the material.
Classes for Table, Chair, Bed, whatever with a property for the material. The complexity of how the material is represented depends on how this information have to be modeled: it could be a string, or a Class (Wood, Iron, Steel) implementing an IMaterial interface.
Probably, i was use Abstract Factory: WoodFurntiture, SteelFurniture, IronFurniture.
Each Factory know How to make chair, table.
Inside you can use (if you need) other DP, but for a now, i do not see any needs for it
Code:
namespace Furniture
{
class Program
{
static void Main(string[] args)
{
IFurnitureFactory factory = new WoodFurnitureFactory();
IFurniture chair = factory.GetChair();
}
}
public interface IFurniture { }
public class WoodChair : IFurniture { }
public class WoodTable : IFurniture { }
public class SteelChair : IFurniture { }
public class SteelTable : IFurniture { }
public class IronChair : IFurniture { }
public class IronTable : IFurniture { }
public interface IFurnitureFactory
{
IFurniture GetChair();
IFurniture GetTable();
}
public class WoodFurnitureFactory : IFurnitureFactory
{
public IFurniture GetChair()
{
return new WoodChair();
}
public IFurniture GetTable()
{
return new WoodTable();
}
}
public class IronFurnitureFactory : IFurnitureFactory
{
public IFurniture GetChair()
{
return new IronChair();
}
public IFurniture GetTable()
{
return new IronTable();
}
}
public class SteeFurniturelFactory : IFurnitureFactory
{
public IFurniture GetChair()
{
return new SteelChair();
}
public IFurniture GetTable()
{
return new SteelTable();
}
}
}

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

When is an "interface" useful?

OOP interfaces.
In my own experience I find interfaces very useful when it comes to design and implement multiple inter-operating modules with multiple developers. For example, if there are two developers, one working on backend and other on frontend (UI) then they can start working in parallel once they have interfaces finalized. Thus, if everyone follows the defined contract then the integration later becomes painless. And thats what interfaces precisely do - define the contract!
Basically it avoids this situation :
Interfaces are very useful when you need a class to operate on generic methods implemented by subclasses.
public class Person
{
public void Eat(IFruit fruit)
{
Console.WriteLine("The {0} is delicious!",fruit.Name);
}
}
public interface IFruit
{
string Name { get; }
}
public class Apple : IFruit
{
public string Name
{
get { return "Apple"; }
}
}
public class Strawberry : IFruit
{
public string Name
{
get { return "Strawberry"; }
}
}
Interfaces are very useful, in case of multiple inheritance.
An Interface totally abstracts away the implementation knowledge from the client.
It allows us to change their behavior dynamically. This means how it will act depends on dynamic specialization (or substitution).
It prevents the client from being broken if the developer made some changes
to implementation or added new specialization/implementation.
It gives an open way to extend an implementation.
Programming language (C#, java )
These languages do not support multiple inheritance from classes, however, they do support multiple inheritance from interfaces; this is yet another advantage of an interface.
Basically Interfaces allow a Program to change the Implementation without having to tell all clients that they now need a "Bar" Object instead of a "Foo" Object. It tells the users of this class what it does, not what it is.
Example:
A Method you wrote wants to loop through the values given to it. Now there are several things you can iterate over, like Lists, Arrays and Collections.
Without Interfaces you would have to write:
public class Foo<T>
{
public void DoSomething(T items[])
{
}
public void DoSomething(List<T> items)
{
}
public void DoSomething(SomeCollectionType<T> items)
{
}
}
And for every new iteratable type you'd have to add another method or the user of your class would have to cast his data. For example with this solution if he has a Collection of FooCollectionType he has to cast it to an Array, List or SomeOtherCollectionType.
With interfaces you only need:
public class Foo<T>
{
public void DoSomething(IEnumerable<T> items)
{
}
}
This means your class only has to know that, whatever the user passes to it can be iterated over. If the user changes his SomeCollectionType to AnotherCollectionType he neither has to cast nor change your class.
Take note that abstract base classes allow for the same sort of abstraction but have some slight differences in usage.