I have a baseball player super class
I have a left field, center field, right field, 3b, ss, 2b, 1b, catcher, pitcher that inherits from player.
So, let's take the pitchers for example. Would a pitcher class be a super class inheriting from baseball player too? with starter, reliever, setup, closer being classes that inherits from pitcher AND baseball player class?
Would my pitchers arsenal be an interface? for example, fast ball, curveball, slider, changeup?
let's say we have a new instance of pitcher called nolan, would nolan's fast ball be a 'composition' since nolan's fast ball relies on nolan, or in other words or doesn't exist without him?
I'm stuck on composition..can someone shed some light following the baseball analogy..
To put this is simple terms, inheritance is an is-a relationship, while composition is a has-a relatiohship.
A pitcher is a baseball player, so a pitcher would inherit from a baseball player. Also, a pitcher has an arsenal of pitches, so that could be defined as composition, although aggregation may be more appropriate if pitchers have varying pitches that they use, as aggregation includes lists.
Related
In object oriented programming we have uses, has-a, is-a relationships. I wonder what would be the relation between earth and the sun, Earth revolves around the sun?
What is the best way of learning object oriented analysis, design and programming?
Objects, classes and is-a relationships
In your object oriented domain model there are two main objects:
an object Earth of class Planet (instantiation, is-a)
an object Sun of class Star (instantiation, is-a)
Planet and Star are special kinds of CelestialObject (specialization, is-a)
Association of classes and objects
There is an association between Sun and Earth: Earth rotates around the Sun, captured by its gravity.
If we think in more general terms, any Star could have several Planet that rotate around. It may as well have no Planet at all. Conversely, most of the Planet rotate around one single Star. Let's keep it simple for now, despite recent discoveries, which have confirmed that in very rare cases a Planet could be associated with several Star.
Such association has two point of view: from the Planet we can say has-a-Star and from the Star side, we could say has-a-Planet.
How to represent associations in a world of objects ?
A simple way to represent a has-a association is to keep a reference to the associated object. This works only for singular association, e.g. the object Earth would keep a reference to Sun.
Another way to represent a has-a association is to keep a list (more generally, a container) of reference to the associated objects. Sun would then have a list of associated Planet composed of Venus, Earth, Mars, etc...
Sometimes an association could be more complex and bear some data that is unique to the link it represents. For example, Earth is associated with the Sun and it turns around it in 365,25 days. To keep things simple, you could just consider that it's an attribute of the Planet in the solar system. But if we'd take this seriously, this duration is in reality not a property of the Earth, because the Earth also turns around the center of the galaxy but with a different duration. It's not a property of the Sun either, because Mars turns also around the Sun, but in 686,96 days.
In such cases, you can consider that the association is itself a class. An instantiation if it would be an object with a orbit duration of 365,25 days, and has-a first extremity Sun and a second extremity Earth
More about these core concepts
To learn more about these core concepts, and in a language independent fashion, you could have a look at the UML class diagram. It's purpose is to represent exactly these kind concepts. You may also have a look at this blog, which gives a nice object of classes for celestial objects, although it doesn't address the associations.
How to use the model in a simulation ?
You need to choose an OO language to implement your model. Keep a container of celestial objects. Each of this object should have some coordinates, a rotation speed, and a method that updates the coordinates based on its rotation speed and the elapsed time. Your simulation would then consist of a loop (representing the elapsed time), and at each iteration, you'd go through your list of celestial objects and for each one update the coordinates, and display the result.
its very simple and basic question.
I have a query regarding abstraction:
Abstraction is defined as Showing what is necessary from user's perspective! its filtering un-necessary info from users perspective.
its right.
example:
Implementation of Abstraction
To implement abstraction let's take an example of a car. We knows a car, Car is made of name of car, color of car, steering, gear, rear view mirror, brakes, silencer, exhaust system, diesel engine, car battery, car engine and other internal machine details etc.
Now lets think in terms of Car rider or a person who is riding a car. So to drive a car what a car rider should know from above category before he starts a car driving.
Necessary things means compulsory to know before starting a car
Name of Car
Color of Car
Steering
Rear View Mirror
Brakes
Gear
Unnecessary things means not that compulsory to know for a Car rider
Internal Details of a Car
Car Engine
Diesel Engine
Exhaust System
Silencer
In Driver perspective. That is okay. Its classic implementation of the Abstraction.
Now, what if I am different user of the class, say Mechanic??? it will be very weird to define same class for me with different access modifiers.
Right?
Please let know.
So you want to provide multiple simplified interfaces for a complex class or set of classes.
The standard way to do this is by implementing the facade design pattern. This will also encourage you to put each of the different aspects of the car into its own class and aggregate these classes only when the full functionality is required.
Interview question:
1) There is a "Paint" class and a "Car" class, with several subclasses like Red, Blue etc colors. Explain how do you separate Colors from Car class? and how is it important?
2) Using an object oriented approach, if you have a class "Car", how would "Paint" class relate to "Car"?
Both are pretty much same questions, just wanna know different perspectives-
Car "has" Paints, I'd guess the interviewer wants you to explain Inheritance and Composition. Example, Red, Blue inherit from Paint since they have "is a" relationship, while Car has paints and it is example of composition. Then some common follow-up questions would be when to use composition over inheritance, is it better to use composition over inheritance, if so why, etc.
Let us say I have a car class and paint class(which consists of different colors). Now In terms of Object oriented design what can be the relation between these two classes is it composition or aggregation. First I thought it would be composition and then I thought it would be aggregation since even if car class is destroyed paint can exist independently. Am I thinking right over here?
I would say it depends on the context of your model. What does your Paint class specifically represent? Is it "a paint job specific to that car"? If so, it is part-of that car and would be considered composition. If it is paint as an independent concept, and an instance can be applied to multiple cars, then a car has-a Paint instance, and it would be considered aggregation.
Your example is a bit awkward but the question you're asking is exactly what you must answer in order to have the answer. No one but you can answer what is correct for your system.
For example, it will be composition if you're actually talking about an applied paint since it can't reuse/reapply/have paint without a recipient (e.g., a car). It should also be a composition if in your system there is no use for independent paint object.
On the other hand, if a paint is a spray container, it can very much exist without the car concept and can be applied to different cars.
It depends on the circumstance, it would be aggregation IMO as there is no strong relationship between a car and its paint, if the paint is removed it does not actually affects the functioning of the car,
But if you think of a relationship between car and engine and if you remove the engine the car cannot move. So this will be composition.
Even thought I think I understand Single Responsibility Principle and high/low cohesion principle, the following questions are still causing me some confusion
1) Assume Planet and Bird properties are put arbitrarily / at random in Car class ( ie. no code within Car needs or operates on the two objects returned by these two properties ) - in other words, Planet and Bird properties don't belong in Car class
a)
SRP states that object should have only one reason to change.
public class Car
{
public void StartEngine()
{ ... }
private Planet Planet
{
get { ... }
}
private Bird Bird
{
get { ... }
}
}
Is Car class violating SRP? I would say it doesn't break SRP, since any changes to Planet or Bird instances don't propagate to the Car class?
b)
Cohesion refers to how closely related methods and class level
variables are in a class. In highly cohesive class all the methods
and class level variables are used together to accomplish a specific
task. In a class with low cohesion functions are randomly inserted
into a class and used to accomplish a variety of different tasks
Assume that even though Car class contains these two random properties, it still accomplishes just a single specific task ( or several closely related task ):
Would we say that Car has low cohesion, even though it still performs a specific task ( or several closely related tasks )?
2) Assume that Planet and Bird properties are used by methods of a Car instance to accomplish a specific task, would then Car have high cohesion, even though conceptually the two properties don't belong to Car ( and thus it would be better if instead Planet and Bird instances were passed as arguments to a methods of a Car which operate on them )
thank you
HELTONBIKER:
1)
as you encapsulated Bird and Planet inside Car (worse yet if they are
private), so now Car class has THREE reasons to change:
I fail to see how Car has three reasons to change since in my first question Car's methods don't even operate on the two properties and thus any changes to Planet's and Bird's public API won't affect Car class?
2)
The problem here has two components:
1. Bird and Planet are contained (as opposed to aggregated) in Car class;
2. Bird and Planet are not conceptually related to Car, much less by some containment relationship.
a) This is confusing: aren't the chances ( at least with my first question ) of Car having to be modified due to modification of Planet or Bird instances exactly the same regardless of whether Planet and Bird instances are contained or aggregated?
b) In second question methods of Car do operate on the two properties in order to perform a single specific task, so aren't they conceptually at least somewhat related? Would you say that even in second question class has low cohesion, even though it performs only a single task ( and is using the two properties to accomplish the task )?
The car class does have low cohesion, as it refers to classes wholly dissimilar to it's set of responsibilities. It also has a higher coupling surface, because since Planet and Bird are public, you've provided access to consumers to these properties, meaning that you're now adding two more "reasons for change" to any consumer, regardless of whether or not Car uses these internally.
At any rate, SRP has been violated if only because Car now has the responsibility of "a way to get planets or birds", disregarding any coupling/cohesion arguments.
1)
I would say that Car cannot hold Planet and Bird. That way Car has two different responsibilities: car functionality and holding some strange objects.
There should be some other object/class that would hold objects in world: eg: class WorldContainer
2)
I would say that both of your examples have low cohesion. Managing car and some different objects should be done using some other interface. Interface that would glue them together.
SRP means that a class should have only one reason to change.
So, a modification in Car class should mean that the Car conceptual model changed.
BUT, as you encapsulated Bird and Planet inside Car (worse yet if they are private), so now Car class has THREE reasons to change:
Modifying the Car conceptual model and/or behaviour;
Modifying the Bird conceptual model and/or behaviour;
Modifying the Planet conceptual model and/or behaviour;
The problem here has two components:
Bird and Planet are contained (as opposed to aggregated) in Car class;
Bird and Planet are not conceptually related to Car, much less by some containment relationship.
Or, plainly speaking (and I hope you did so as a didactic exercise), the architecture shown simply doesn't make sense.
Example with aggregation (in Python). The non-cohesive classes are defined outside the Car class definition, which references them. Car depends from Bird and Planet, but now Bird and Planet exist on their own.
class Bird():
hasWings = True
class Planet():
isFlat = False
class Car():
owner = Bird()
substrate = Planet()
Example with parameter-passing (just the car class, suppose the other classes are similar as above). Now the Car constructor (the __init__ method in python) takes instances as parameters. This might or might not be prefered. The dependency and coupling remains, but perhaps more concrete now.
class Car():
def __init__(bird, planet)
owner = bird
substrate = planet
In the end this whole issue of cohesion and coupling doesn't have so much to do with the software itself, but with the developers. Compilers won't mind if your namespaces, project folders and file distribution is messy, as long as it "compiles". But it wouldn't make ANY SENSE to do as you did (put a Bird and a Planet class inside a Car class). Just to begin, your versioning of each class would be very messed.
So, the purity you shouldn't violate is not that written in books for the sake of it. This purity is (or should have been) derived of human beings struggling with machine instructions. Object-Orientation, and Software Architecture in general, is not intended for the machine, but for the developer's (piece of) mind.