OOP relationships between two classes - class

I have been struggling with the abstraction that lies between two classes when it comes to the issue of Inheritance or Composition...the IS-A vs HAS-A relationship between classes like LoginManager and AuthenticateManager.
The way I see it LoginManager can be either and can sit comfortably in a IS-A place with AuthenticateManager, inheriting it as a superclass (ie Class LoginManager extends AuthenticateManager) OR just declare AuthenticateManager's objects as members of its own class which would imply Composition, so i guess it just comes down to a thing of experience and the proper knowledge of the OOP paradigm. So please, can anyone help explain what a proper relationship would be between these classes?
PS: Please moderator don't close this topic as being inconsistent with the sites question asking principles.
Thanks.

It depends on your needs. Inheritance provides you with access to protected members of a superclass whereas composition does not. If there are class members that should be available only to a derived class then it does not make sense to make them properties and access them with composition because every other object could access them as well. Otherwise it is about what you and your team prefer.
EDIT:
No rules are so strict as you think they are. Design patterns, for instance, are just templates and you don't need to strictly follow them. You can't blindly follow rules, no one will credit you for this. It's much better to have OOP in mind but write your code so that you can clearly explain what have you done and why.
Since I don't know design of your two classes, I can't really tell you what are your needs. This statement (already mentioned) should be enough to point you in the right direction.
Inheritance provides you with access to protected members of a superclass whereas composition does not.

Why not consider something that is easier to grasp?
I have a father - I inherit his genes (some good some bad?) But hey.
He had a kidney. His own and that made his composition.
I have my own kidney - my own and that makes my composition.
So
IS-A - I IS-A child of my father
HAve-A - I hAVE-A kidney
My Kidney works differently to my fathers
But I have blue eyes that I have inherited from my father

Related

Is it better to implement two classes or one class in the following case?

I have a class "Vertex" with 4 attributes and a class "Vertex_" with one attribute. The one attribute in Vertex_ is also in Vertex. Is it a good design to keep the two classes or is it better to program just the class Vertex, although there will be 3 variables, which are not used, when I instantiate an object which needs just the one attribute?
Class Vertex_ is actually somewhat a duplicate of Class Vertex.
I would suggest using inheritance and having Class Vertex inherit the attribute from the parent Class Vertex_ while having the 3 other attributes Class Vertex_ does not have.
TL;DR
This is a question that deserves a very long answer.There are two reasons for inheritance and the reason for doing it can depend on the language being used. One reason is for code reuse. Without knowing anything else about your situation, it would seem you are inheriting simply to reuse an attribute (but I suspect there could be more you will be reusing). But, there are other ways of getting code reuse without inheritance, for example containment, which is often a better way.
A powerful feature of object-oriented programming is the ability to substitute one type of object for another. When a message is sent to that object, the correct method implementation is invoked according the actual type of object receiving the message. This is one type of polymorphism. But in some languages the ability to substitute one object for another is constrained. In Java I can only substitute an instance of class B for an instance of class A if B is a descendant of A. So inheritance becomes important in Java to support polymorphism.
But what does it mean to be able to substitute a B instance for an A instance? Will it work? Class A has established a contract stating what each of its methods requires before you can successfully call it and at the same time states what each method promises to deliver. Will the methods of class B live up to that contract? If not, you really cannot substitute a B for an A and expect the program to run correctly. B may be a subclass of A but it is not a subtype of A (see Liskov substitution principle]).
In a language such as Python, inheritance is not required for polymorphism and coders are more apt to use it as code-reuse mechanism. Nevertheless, some people feel that subclassing should only be used to express subtyping. So, if Vertex_ is only using one of the four attributes it has inherited, I am doubtful that an instance of Vertex_ could be safely substituted for an instance of Vertex. I would not do the inheritance unless the language were C++ and then I would use private inheritance.

Why use accessors and mutators with simple classes?

For simple classes (and I mean really simple ones), why do we use accessor and mutator methods? Why do not we just make the data members public?
For example, the following class header (in C++) and could have been implemented with much less effort; as it is actually a couple of data members with accessors and mutators that do nothing but access/modify those data members.
I appreciate the advantage of the use of accessors and mutators in more complex classes.
template<class T>
class Node
{
private:
T item; // A data item
Node<T>* next; // Pointer to next node
public:
Node();
Node(const T& anItem);
Node(const T& anItem, Node<T>* nextNodePtr);
void setItem(const T& anItem);
void setNext(Node<T>* nextNodePtr);
T getItem() const;
Node<T>* getNext() const;
}; // end Node
This is a very fundamental, basic, and well-defined design principle in OOP - why to use accessors and mutators, in spite of whether a class is big or small.
I would still say, that implementation-usage of this principle still varies from language to language, but the core principle of Object Oriented Design - Encapsulation - remains always same and mandates, that you should always hide everything that is possible to hidden.
This is kind of duplicate of your question, and it refers to why getters and setters are in the play; however, I'll try to bring some other points as well.
Encapsulation, aspect of which is the topic in questions (mutators/accessors), is a fundamental and probably the most important principle of Object Oriented Programming.
First and foremost:
The main point of the Encapsulation is not(!) to restrict/block the access to the member variable, but rather to constrain the access policy and mandate the reasonable access, and therefore avoid any unintended interference, implicit misuse, or accidental accesses.
Think about it: if the user invokes .setUserName("MyUser") the one really intends to write the data into the member field, and that's explicitly clear! otherwise, it would mean that the client has (1) accidentally provided the "MyUser" data as an argument into setter method, and they (2) accidentally invoked the .setUserName method, which is way less likely to happen accidentally both together, then just publicly accessing that field, which takes only one move to do.
That being said, using the principle of encapsulation and advocating it as a core OOP feature, software developers, a lot of frameworks and libraries very often conventionally agree and make use of data classes, ordinary classes, business classes, service, or any other types, relying on the widespread Conventional Design and best practice of how to use member variables - using mutators to mutate and accessors to access the fields.
Many frameworks explicitly invoke setters and getters when they implement IoC or DI.
So, it's the best practice, conventionally agreed, non-smelling code style, and the most safe design of the class members, to use encapsulation and interact with them through mutators and accessors.

Private nested classes - are they necessary for composition?

This is my naive thought process. I appreciate when anyone points out any discrepancies.
I know that in Java it is possible to create private nested classes. But in PHP (calling itself an "OOL") no such thing is easily possible.
However, there may be an instance where I need to use a helper class within only one other class.
This naturally led me to consider using composition about which I think its supposed to actually solve this kind of a problem, for the following reason:
Wikipedia:
It is only called composite, if the objects it refers to
are really its parts, i.e. have no independent existence.
Aggregation differs from ordinary composition in that it does not imply ownership.
In composition, when the owning object is destroyed, so are the
contained objects. In aggregation, this is not necessarily true.
So since in composition the components aren't supposed to exist without the other composite object, I assume there is basically only one way of accomplishing this by using private nested classes, otherwise I will need to have the Component class visible, making it instantiable also somewhere else, violating the creation/destruction-of-components-within-the-composite-class rule.
Now I came across PHP where it is not possible at all to create nested classes (or maybe with some magic) which may lead to a question why do we need nested classes at all?
Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one
place: If a class is useful to only one other class, then it is
logical to embed it in that class and keep the two together. Nesting
such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B,
where B needs access to members of A that would otherwise be declared
private. By hiding class B within class A, A's members can be declared
private and B can access them. In addition, B itself can be hidden
from the outside world.
It can lead to more readable and maintainable code: Nesting small
classes within top-level classes places the code closer to where it is
used.
So in my opinion, as nested classes increase encapsulation (and thus allowing for implementation of a composite concept) it should be always possible to create a nested class in a proper OOL.
I also looked up the definition of an OOP and it only mentions the support for Encapsulation, Abstraction, Inheritance, Polymorphism concepts.
OOP
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s
definition.
Abstraction is the development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation details. (e.g. instead or creating a single sequence of commands to work with a radius and points we would abstract a concept of a circle. So we define a class Circle and a its attributes/functions in such a way that it reflects this abstract concept.)
Inheritance is supposed to be the is-a relationship between abstractions (allowing for code reuse).
Polymorphism allows for overriding and overloading methods.
A guy asked a question here which actually complies exactly with my understanding of the problem and IMHO received quite inaccurate answer, being told to be really confused and being provided with a code sample which IMO is not a proper composition, as it is not really possible in PHP. In addition someone may argue that composition isn't about inner classes.
So am I understanding something really wrong?
Those concepts like composition are generic and their implementation may vary depending on the programming language.
In the other hand, I wouldn't say that the definition of composition which includes [...] have no independent existence refers to being able to create instances or not from different scopes.
No independent existence is a more conceptual than practical rule. It means that a wheel can never be the composition root because the root is the car. That is, a wheel can't exist independently of a car.
Therefore, the conclusion is nested classes are just an implementation detail and they have nothing to do with composition. Note that objects aren't created from classes in all programming languages but composition and many other features are still possible. Would you say that object composition isn't possible in JavaScript?
var car = { manufacturer: "Ford", model: "Focus" };
// I can create the wheel after the car
var wheel = { color: "black" };
// but it'll be always tied to some car
car.wheel = wheel;
Anyway, practically all systems implement aggregation, which is a flavor of composition. Take a look at this Q&A at Software Engineering.
While a wheel is useless without being part of a car, wheels are still sold apart as one of the many mechanical pieces of which a car is built, hence a wheel can live alone yet it's useless as just a piece.
Generic definition of composition in OOP
The OP is too concerned and focused on the formal definition of composition in terms of UML: composition, association, direct association, aggregation...
BTW, the term composition in OOP has a more simple meaning which is often used, for example, when discussing when to use inheritance or when to avoid it, we talk about composition over inheritance. See for example this Q&A from 2010: What is composition as it relates to object oriented design? on which basically all answerers have a consensus about the definition of composition.
At the end of the day, the term composition is the approach to create an object graph: simple types are associated together to create more complex types.
Thus, as I've already explained in the first part of this answer, nested classes are just a programming language implementation detail and they're not crucial to implement any flavor of composition.
OP said on some comment:
But conceptually in order to implement it properly as a composition,
I'd prefer something like partial classes (as in C#) allowing me to
separate code into multiple files but restricting the instantiability
to the main class only. I know you don't agree with me, I have to
express my view somehow.
This is a wrong example because partial classes are just a syntactic sugar to glue multiple files defining the same class and later everything is the same class.
C# has nested classes:
public class A
{
public class B
{
}
}
But you need to understand that type definitions have nothing to do with objects from a conceptual point of view because an object-oriented language may or may not have a type system and classes, but yet it can support composition and all its flavors.
In wikipedia, there's also the following example of composition without using private nested classes.
class University
{
std::vector<Department> faculty; //this is composition
std::vector<People*> people; //this is aggregation
University() // constructor
{
// Composition: Departments exist as long as the University exists
faculty.push_back(Department("chemistry"));
faculty.push_back(Department("physics"));
faculty.push_back(Department("arts"));
}
};
For a true composition we don't have to make the whole class private as long as we treat instances of departments appropriately, i.e. we need to make sure that all departments will actually get deleted when the university ceases to exist.
An analogous ways of implementing different compositions in JavaScript would be as follows:
/*this is a component's "class"*/
function Text(txt){
this.txt = txt;
}
/*this is a composite's "class"*/
function Hello(begining){
/*public object*/
this.begining = begining;
/*this is like making an instance from a nested function which is a composite*/
var Middle = new (function Middle(txt){
this.txt = txt;
})(" - ");
/*private object - also a composite, even though it's made of the public class Text*/
var Ending = new Text("that's all.");
/*The use of the private property Ending*/
this.Say = function(){
var msg = this.begining.txt + Middle.txt + Ending.txt;
console.log(msg);
}
}
/*
This txt variable will be the "begining" text. It could still be a composite, but
only if it's not used in another composite when purpose is to be
"an untransferable part" and not a "visitor".
*/
var txt = new Text("Dan");
var say1 = new Hello(txt);
var say2 = new Hello(new Text("To be or not to be"));
say1.Say() /*Dan - that's all.*/
say2.Say() /*To be or not to be - that's all.*/
But even the transferability is often a neglected rule when people see "cars" having "wheels" as parts (rather then "visitors")
Instead of perhaps "neural network" and "neurons" or "forest" and "trees". Trees don't get replanted to a different forest so often.
And since the wheels can still be understood as parts of a composite, it doesn't have to differ from aggregation in code.

Should this class inherit from directly from the base class or from the subclass

I have the following class diagram. Just looking for some guidance as to how I approached this exam question as I'm not sure if I was correct. I have no solutions am hoping someone more experienced could give there opinion.
TASK 1: Add a subclass called MonsterEater. Objects of this class are like PieEaters but in addition the MonsterEater has an attribute called numPieEatersEaten of type integer and a method eatPieEater with signature of one argument named aGrid which is of type Grid.
Since MonsterEater has a lot of the same behaviours as PieEater I decided to make that inherit from the PieEater class, while giving it the additional behaviour (attributes and methods)
TASK 2: Add a subclass called MagicPie. Objects of this class are like Pies but in addition the MagicPies have an attribute called visible of type boolean and methods appear and disappear both with signature of no arguments and return nothing
I made MagicPie inherit from Pie. Gave it the attributes and methods.
TASK 3: Override the display method in all the concrete classes in your inheritance hierarchy.
For this I just added the method display() to all the classes which inherit from the base class GameElement.
I was also asked to add an association so that just MonsterEaters may eat MagicPies.(the class i made derive from Pie) so I've done an eats association from MonsterEater to MagicPie
FINAL TASK: List all the features of the MonsterEater and MagicPie classes. Does the UML diagram that you produced allow MonsterEaters to eat Pies. Explain your answer.
I wasnt to sure about this one, MonsterEater inherits from the PieEater class which can eat a pie but I'm not sure if that means MonsterEater can. I'm also not fully sure if my inheritance hierachy that I created is even correct. Any insight/guidance would be greatly appreciated.
Task 1: If MonsterEater is allowed to eat Pie as well, then your inheritance relation seems acceptable. I'd also add an association 0..1 to 0..n from MonsterEater to PieEater. THis makes obvious the implication of this inheritance: a MonsterEater can also eat another MonsterEater because it's also a PieEater.
Task 2: The inheritance makes sense, as intuitively a MagicPie is some special kind of Pie. But the consequence of this inheritance, is that PieEater could also eat MagicPie (see below)
Task 3: ok for the display. ok for the additional association. But there's a trap here. As a MagicPie is a Pie, a PieEater could also eat a MagicPie. So you have to add a constraint to the existing association between PieEater and Pie, for example: { Pie shall not be a MagicPie }
Task 4: For nutrition, see above. The inheritance you've made seem reasonable. The wording of the instructions "are like ... but in addition ..." strongly suggests inheritance. Only if MonsterEater would not be allowed to eat Pie would I seriously question this inheritance. And this is not explicitly prohibited.
I wouldn't let MonsterEater inherit from PieEater if it doesn't eat pies, the fact that they both have eat/walk/turn methods probably means they should implement few new interfaces: IEater, IWalker.
A MagicPie inheriting from a Pie makes more sense as it appears to be an extension of a normal Pie.
Depending on the UML tool you have, you might have to specify display() is an override.
The last question, reconnecting to my first observation, it's a matter of requeirements, you can do it both ways, if it's not specified, I wouldn't assume a MonsterEater can eat a Pie as well.
EDIT: If you are allowed to use multiple inheritance, you may also use classes instead of interfaces for Eater/Walker.

Pseudo-multiple-inheritance with extension methods on interfaces in C#?

Similar question but not quite the same thing
I was thinking that with extension methods in the same namespace as the interface you could get a similar effect to multiple inheritance in that you don't need to have duplicate code implementing the same interface the same way in 10 different classes.
What are some of the downsides of doing this? I think the pros are pretty obvious, it's the cons that usually come back to bite you later on.
One of the cons I see is that the extension methods can't be virtual, so you need to be sure that you actually do want them implemented the same way for every instance.
The problem that I see with building interface capability via extension methods is that you are no longer actually implementing the interface and so can't use the object as the interface type.
Say I have a method that takes an object of type IBar. If I implement the IBar interface on class Foo via extension methods, then Foo doesn't derive from IBar and can't be used interchangeably with it (Liskov Substitution principle). Sure, I get the behavior that I want added to Foo, but I lose the most important aspect of creating interfaces in the first place -- being able to define an abstract contract that can be implemented in a variety of ways by various classes so that dependent classes need not know about concrete implementations.
If I needed multiple inheritance (and so far I've lived without it) badly enough, I think I'd use composition instead to minimize the amount of code duplication.
A decent way to think about this is that instance methods are something done by the object, while extension methods are something done to the object. I am fairly certain the Framework Design Guidelines say you should implement an instance method whenever possible.
An interface declares "I care about using this functionality, but not how it is accomplished." That leaves implementers the freedom to choose the how. It decouples the intent, a public API, from the mechanism, a class with concrete code.
As this is the main benefit of interfaces, implementing them entirely as extension methods seems to defeat their purpose. Even IEnumerable<T> has an instance method.
Edit: Also, objects are meant to act on the data they contain. Extension methods can only see an object's public API (as they are just static methods); you would have to expose all of an object's state to make it work (an OO no-no).