Difference between Encapsulation and Abstraction - python

I had an interview today. I had a question from OOP, about the difference between Encapsulation & Abstraction?
I replied to my knowledge that Encapsulation is basically binding data members & member functions into a single unit called Class. Whereas Abstraction is basically to hide implementation complexity & provide ease of access to the users. I thought she would be okay with my answer. But she queried if the purpose of both is to hide information then what the actual difference between these two is? I could not give any answer to her.
Before asking this question, I read other threads on StackOverFlow about the difference between these two OOPs concepts. But I am not finding myself in a position to convince the interviewer.
Can anyone please justify it with the simplest example?

Encapsulation hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.
Abstraction is used to hide something too, but in a higher degree (class, interface). Clients who use an abstract class (or interface) do not care about what it was, they just need to know what it can do.

This image sums pretty well the difference between both:
Source here

Encapsulation: Wrapping code and data together into a single unit. Class is an example of encapsulation, because it wraps the method and property.
Abstraction: Hiding internal details and showing functionality only. Abstraction focus on what the object does instead of how it does. It provides generalized view of classes.
int number = 5;
string aStringNumber = number.ToString();
Here, ToString() is abstraction. And how this mechanism number variable converted to string and initialize into aStringNumber is encapsulation.
Let us take a real world example of calculator. Encapsulation is the internal circuits, battery, etc., that combine to make it a calculator. Abstraction is the different buttons like on-off, clear and other buttons provided to operate it.

Abstraction - is the process (and result of this process) of identifying the common essential characteristics for a set of objects.
One might say that Abstraction is the process of generalization: all objects under consideration are included in a superset of objects, all of which possess given properties (but are different in other respects).
Encapsulation - is the process of enclosing data and functions manipulating this data into a single unit, so that to hide the internal implementation from the outside world.
This is a general answer not related to a specific programming language (as was the question). So the answer is: abstraction and encapsulation have nothing in common. But their implementations might relate to each other (say, in Java: Encapsulation - details are hidden in a class, Abstraction - details are not present at all in a class or interface).

Yes !!!!
If I say Encapsulation is a kind of an advanced specific scope abstraction,
How many of you read/upvote my answer. Let's dig into why I am saying this.
I need to clear two things before my claim.
One is data hiding and, another one is the abstraction
Data hiding
Most of the time, we will not give direct access to our internal data. Our internal data should not go out directly that is an outside person can't access our internal data directly. It's all about security since we need to protect the internal states of a particular object.
Abstraction
For simplicity, hide the internal implementations is called abstraction. In abstraction, we only focus on the necessary things. Basically, We talk about "What to do" and not "How to do" in abstraction.
Security also can be achieved by abstraction since we are not going to highlight "how we are implementing". Maintainability will be increased since we can alter the implementation but it will not affect our end user.
I said, "Encapsulation is a kind of an advanced specific scope abstraction". Why? because we can see encapsulation as data hiding + abstraction
encapsulation = data hiding + abstraction
In encapsulation, we need to hide the data so the outside person can not see the data and we need to provide methods that can be used to access the data. These methods may have validations or other features inside those things also hidden to an outside person. So here, we are hiding the implementation of access methods and it is called abstraction.
This is why I said like above encapsulation is a kind of abstraction.
So Where is the difference?
The difference is the abstraction is a general one if we are hiding something from the user for simplicity, maintainability and security and,
encapsulation is a specific one for which is related to internal states security where we are hiding the internal state (data hiding) and we are providing methods to access the data and those methods implementation also hidden from the outside person(abstraction).
Why we need abstraction
When you do designs, you will not talk about implementations. You say If you give these parameters to this method it will give these output.
We hide the internal implementation of the method and talk about what it will do so this is an abstraction.
Example
public int add(int a, int b);
This method definition tells us that if you give two variables it will do addition and return the result.
here we will not look at the implementation and we ay only what this method does and not how it does.
Method implementations can be differs based on developers.
1.
public int add(int a, int b){
return a + b;
}
public int add(int a, int b){
return b + a;
}
Two methods are doing the same thing what their implementation differs.
Basically,
Abstraction is needed to model the system. Encapsulation is needed to enhance system security.

Abstraction:
Is usually done to provide polymorphic access to a set of classes.
An abstract class cannot be instantiated thus another class will have to derive from it to create a more concrete representation.
A common usage example of an abstract class can be an implementation of a template method design pattern where an abstract injection point is introduces so that the concrete class can implement it in its own "concrete" way.
see: http://en.wikipedia.org/wiki/Abstraction_(computer_science)
Encapsulation:
It is the process of hiding the implementation complexity of a specific class from the client that is going to use it, keep in mind that the "client" may be a program or event the person who wrote the class.
see: http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

There is a great article that touches on differences between Abstraction, Encapsulation and Information hiding in depth: http://www.tonymarston.co.uk/php-mysql/abstraction.txt
Here is the conclusion from the article:
Abstraction, information hiding, and encapsulation are very different,
but highly-related, concepts. One could argue that abstraction is a
technique that helps us identify which specific information should be
visible, and which information should be hidden. Encapsulation is then
the technique for packaging the information in such a way as to hide
what should be hidden, and make visible what is intended to be
visible.

A very practical example is.
let's just say I want to encrypt my password.
I don't want to know the details, I just call
encryptionImpl.encrypt(password) and it returns an encrypted
password.
public interface Encryption{ public String encrypt(String password); }
This is called abstraction. It just shows what should be done.
Now let us assume We have Two types of Encryption Md5 and RSA which
implement Encryption from a third-party encryption jar.
Then those Encryption classes have their own way of implementing
encryption which protects their implementation from outsiders
This is called Encapsulation. Hides how it should be done.
Remember:what should be done vs how it should be done.
Hiding complications vs Protecting implementations

Yes, it is true that Abstraction and Encapsulation are about hiding.
Using only relevant details and hiding unnecessary data at Design Level is called Abstraction. (Like selecting only relevant properties for a class 'Car' to make it more abstract or general.)
Encapsulation is the hiding of data at Implementation Level. Like how to actually hide data from direct/external access. This is done by binding data and methods to a single entity/unit to prevent external access. Thus, encapsulation is also known as data hiding at implementation level.

Encapsulation:
Hiding something, sort of like medicine capsule. We don't know what is in the capsule, we just take it. Same as in programming - we just hide some special code of method or property and it only gives output, same as capsule. In short, encapsulation hides data.
Abstraction:
Abstraction means hiding logic or implementation. For example, we take tablets and see their color and but don't know what is the purpose of this and how it works with the body.

difference in both is just the View Point
Encapsulation word is used for hiding data if our aim is to prevent client seeing inside view of our logic
Abstraction word is used for hiding data if our aim is to show our client a out side view
Outside view means that let suppose
BubbleSort(){
//code
swap(x,y);
}
here we use swap in bubble sort for just showing our client what logic we are applying, If we replace swap(x,y) with whole code here, In a single instance he/she can't understand our logic

Let me explain it in with the same example discussed above. Kindly consider the same TV.
Encapsulation: The adjustments we can make with the remote is a good example - Volume UP/DOWN, Color & Contrast - All we can do is adjust it to the min and max value provided and cannot do anything beyond what is provided in the remote - Imagine the getter and setter here(The setter function will check whether the value provided is valid if Yes, it process the operation if not won't allow us to make changes - like we cannot decrease the volume beyond zero even we press the volume down button a hundred times).
Abstraction: We can take the same example here but with a higher Degree/Context. The volume down button will decrease the volume - and this is the info we provide to the user and the user is not aware of neither the infrared transmitter inside the remote nor the receiver in the TV and the subsequent process of parsing the signal and the microprocessor architecture inside the TV. Simply put it is not needed in the context - Just provide what is necessary. One can easily relate the Text book definition here ie., Hiding the inner implementation and only providing what it will do rather than how it do that!
Hope it clarifies a bit!

Briefly, Abstraction happens at class level by hiding implementation and implementing an interface to be able to interact with the instance of the class. Whereas, Encapsulation is used to hide information; for instance, making the member variables private to ban the direct access and providing getters and setters for them for indicrect access.

Encapsulation is wrapping up of data and methods in a single unit and making the data accessible only through methods(getter/setter) to ensure safety of data.
Abstraction is hiding internal implementation details of how work is done.
Take and example of following stack class:
Class Stack
{
private top;
void push();
int pop();
}
Now encapsulation helps to safeguard internal data as top cannot be accessed directly outside.
And abstraction helps to do push or pop on stack without worrying about what are steps to push or pop

Abstraction
As the name suggests abstract means summary or brief about somtehing. In case of OOP Abstract Classes are the ones which do not contain every information about that object in real world, for eg. you want to book a hotel room, if your object is that room you mainly care about:
its prices, size, beds etc.
but you do not care about
the wiring they have used in the hotel room for electricity.
which cement they have used to build it up
So, you get abstracted information about the room which you care about.
On the other hand, Encapsulation is basically capsulating the related information together, for eg. you booked the hotel room, you go there and switch on a bulb by pressing the switch. Now the switch object has all internal wirings which are required to switch that bulb ON, but you really do not care about those wirings. You care only about bulb is switched ON or not.
Now one can argue that abstraction also applies here:
one can say the internal wiring of the switch is also abstracted to you, so this must be case of abstraction but here are some subtle differences:
Abstraction is more of a contextual thing, it does not have the non abstracted information, like the wiring info which you do not care about, is not present in the context of website for booking hotel room (like your class room do not have information about the wiring grid of it, since this room is delegated for online booking only) , whereas encapsulation is more granular, it means hiding and capsulating the granular things which you do not need to care about, for switching the bulb ON the switch hides the wiring inside the switch board (like private attributes/methods of classes).
Now the switch class has the information but it is hidden to you. On the other hand room class does not have the information about wiring design of a hotel room since it is not even in the context of online booking of the room
Thus, the abstraction is more related to classes and encapsulation is more related to internal of the class objects, attributes and methods.

Abstraction
is the process of hiding the how, and only showing the what
the purpose is to simplify information and hide unnecessary details from the user
Encapsulation
is the process of wrapping data and functionality into a single unit
the purpose is to protect data, by preventing direct access and only providing a safer and indirect way

In simple terms, Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding)

Abstraction
In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.
Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.
Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.
Encapsulation:
Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.
If I have individual package one for wine and another one for chocolate, and if all the classes are declared in the package as default access modifier, we are giving package level encapsulation for all classes.
Within a package, if we declare each class filed (member field) as
private and having a public method to access those fields, this way
giving class level encapsulation to those fields

If I am the one who faced the interview, I would say that as the end-user perspective abstraction and encapsulation are fairly same. It is nothing but information hiding. As a Software Developer perspective, Abstraction solves the problems at the design level and Encapsulation solves the problem in implementation level

Encapsulation is the composition of meaning.
Abstraction is the simplification of meaning.

Just a few more points to make thing clear,
One must not confuse data abstraction and the abstract class. They are different.
Generally we say abstract class or method is to basically hide something. But no.. That is wrong. What is the word abstract means ? Google search says the English word abstraction means
"Existing in thought or as an idea but not having a physical or concrete existence."
And thats right in case of abstract class too. It is not hiding the content of the method but the method's content is already empty (not having a physical or concrete existence) but it determines how a method should be (existing in thought or as an idea) or a method should be in the calss.
So when do you actually use abstract methods ?
When a method from base class will differ in each child class that extends it.
And so you want to make sure the child class have this function implemented.
This also ensures that method, to have compulsory signature like, it must have n number of parameters.
So about abstract class!
- An Abstract class cannot be instantiated only extended! But why ?
A class with abstract method must be prevented from creating its own instance because the abstract methods in it, are not having any meaningful implementation.
You can even make a class abstract, if for some reason you find that it is meaning less to have a instance of your that class.
An Abstract class help us avoid creating new instance of it!
An abstract method in a class forces the child class to implement that function for sure with the provided signature!

Abstraction: what are the minimum functions and variables that should be exposed to the outside of our class.
Encapsulation: how to achieve this requirement, meaning how to implement it.

Related

How can a class, in Python, inherit from 2 possible superclasses?

I'm currently working on platforms in a 2D game in Python. I created 1 superclass: Block. I also created 2 subclasses of Block: Solid (you can't jump through) & Semi_Solid (you can jump through from below). Now I would like to add a class Platform (to allow these blocks to move) that inherits from Solid or Semi_Solid, so its instances could have either the attributes of Solid or Semi_Solid.
So how can I create instances of Platform that can either inherit from Solid or Semi_Solid? Am I obliged to create 2 different classes ?
So I tried:
class Block:
pass
class Solid(Block):
pass
class Semi_Solid(Block):
pass
x = "solid"
class Platform(Solid if x=="solid" else Semi_Solid):
pass
obj1 = Platform()
x = "semi-solid"
obj2 = Platform()
But the change of x is not taken into account. I got 2 solid platforms
I made several others tests, but none of them was successful. Thank you for any help.
Inheritance is probably the most overrated OO feature, and alas usually presented as the one-size-fits-all solution in most introductory OO literature. The truth is that the real main OO features are encapsulation (which is not data hiding per se, but the ability to define self-contained componants that group together state and behaviour and abstract implementation details from client code) and polymorphic dispatch (the ability to use objects from different types / with different implementation in a uniform manner by the use of a common API).
At the semantic level, inheritance describes a "is a" relationship - if B inherits from A, then B is a A (cf the liskov substitution principle). So, is your "Platform" a "Solid" or is it a "SemiSolid" ? (hint: this is of course a rethoretical question).
At the implementation level, inheritance is, mostly, a fixed (static) and somehow restricted form of composition / delegation - whatever is not implemented in the child class is delegated to its parent(s). Good OO design is based on separating responsabilites and separate invariants from variants, delegating the "variant" part to another object. This is examplified by the Strategy pattern and its close cousin the State pattern.
Chances are that the answer to your question is mostly to use the Strategy pattern to handle the behavioral difference between solid and semisolid blocks - in which case you'd only have one single Block class responsible of everything that's common to all kind of blocks, and strategies for the "jump thru" behaviour (and other eventual behavioral differences between blocks). Then your Platform class - which doesn't necessarily have to be Block subclass (might or not be the right design depending on the context) - would take either a "jump through" strategie as argument (if you decide to make it a Block) or a Block instance (created with the appropriate strategie) if you decide to not make it a Block subclass.
This not only solves your current problem, but also allow to add new strategies etc without touching existing code, and avoids combinatorial explosion of classes.
NB: you may want to get yourself a copy of the GOF "design patterns", not that much for the patterns catalog itself (however interesting it is), but mostly for the first (long) introductory part of the book which is so far the very best available text on proper OO design.

What, if any, are the differences between implementing one class as a child of another versus having the child employ an instance of the parent? [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
There are two schools of thought on how to best extend, enhance, and reuse code in an object-oriented system:
Inheritance: extend the functionality of a class by creating a subclass. Override superclass members in the subclasses to provide new functionality. Make methods abstract/virtual to force subclasses to "fill-in-the-blanks" when the superclass wants a particular interface but is agnostic about its implementation.
Aggregation: create new functionality by taking other classes and combining them into a new class. Attach an common interface to this new class for interoperability with other code.
What are the benefits, costs, and consequences of each? Are there other alternatives?
I see this debate come up on a regular basis, but I don't think it's been asked on
Stack Overflow yet (though there is some related discussion). There's also a surprising lack of good Google results for it.
It's not a matter of which is the best, but of when to use what.
In the 'normal' cases a simple question is enough to find out if we need inheritance or aggregation.
If The new class is more or less as the original class. Use inheritance. The new class is now a subclass of the original class.
If the new class must have the original class. Use aggregation. The new class has now the original class as a member.
However, there is a big gray area. So we need several other tricks.
If we have used inheritance (or we plan to use it) but we only use part of the interface, or we are forced to override a lot of functionality to keep the correlation logical. Then we have a big nasty smell that indicates that we had to use aggregation.
If we have used aggregation (or we plan to use it) but we find out we need to copy almost all of the functionality. Then we have a smell that points in the direction of inheritance.
To cut it short. We should use aggregation if part of the interface is not used or has to be changed to avoid an illogical situation. We only need to use inheritance, if we need almost all of the functionality without major changes. And when in doubt, use Aggregation.
An other possibility for, the case that we have an class that needs part of the functionality of the original class, is to split the original class in a root class and a sub class. And let the new class inherit from the root class. But you should take care with this, not to create an illogical separation.
Lets add an example. We have a class 'Dog' with methods: 'Eat', 'Walk', 'Bark', 'Play'.
class Dog
Eat;
Walk;
Bark;
Play;
end;
We now need a class 'Cat', that needs 'Eat', 'Walk', 'Purr', and 'Play'. So first try to extend it from a Dog.
class Cat is Dog
Purr;
end;
Looks, alright, but wait. This cat can Bark (Cat lovers will kill me for that). And a barking cat violates the principles of the universe. So we need to override the Bark method so that it does nothing.
class Cat is Dog
Purr;
Bark = null;
end;
Ok, this works, but it smells bad. So lets try an aggregation:
class Cat
has Dog;
Eat = Dog.Eat;
Walk = Dog.Walk;
Play = Dog.Play;
Purr;
end;
Ok, this is nice. This cat does not bark anymore, not even silent. But still it has an internal dog that wants out. So lets try solution number three:
class Pet
Eat;
Walk;
Play;
end;
class Dog is Pet
Bark;
end;
class Cat is Pet
Purr;
end;
This is much cleaner. No internal dogs. And cats and dogs are at the same level. We can even introduce other pets to extend the model. Unless it is a fish, or something that does not walk. In that case we again need to refactor. But that is something for an other time.
At the beginning of GOF they state
Favor object composition over class inheritance.
This is further discussed here
The difference is typically expressed as the difference between "is a" and "has a". Inheritance, the "is a" relationship, is summed up nicely in the Liskov Substitution Principle. Aggregation, the "has a" relationship, is just that - it shows that the aggregating object has one of the aggregated objects.
Further distinctions exist as well - private inheritance in C++ indicates a "is implemented in terms of" relationship, which can also be modeled by the aggregation of (non-exposed) member objects as well.
Here's my most common argument:
In any object-oriented system, there are two parts to any class:
Its interface: the "public face" of the object. This is the set of capabilities it announces to the rest of the world. In a lot of languages, the set is well defined into a "class". Usually these are the method signatures of the object, though it varies a bit by language.
Its implementation: the "behind the scenes" work that the object does to satisfy its interface and provide functionality. This is typically the code and member data of the object.
One of the fundamental principles of OOP is that the implementation is encapsulated (ie:hidden) within the class; the only thing that outsiders should see is the interface.
When a subclass inherits from a subclass, it typically inherits both the implementation and the interface. This, in turn, means that you're forced to accept both as constraints on your class.
With aggregation, you get to choose either implementation or interface, or both -- but you're not forced into either. The functionality of an object is left up to the object itself. It can defer to other objects as it likes, but it's ultimately responsible for itself. In my experience, this leads to a more flexible system: one that's easier to modify.
So, whenever I'm developing object-oriented software, I almost always prefer aggregation over inheritance.
I gave an answer to "Is a" vs "Has a" : which one is better?.
Basically I agree with other folks: use inheritance only if your derived class truly is the type you're extending, not merely because it contains the same data. Remember that inheritance means the subclass gains the methods as well as the data.
Does it make sense for your derived class to have all the methods of the superclass? Or do you just quietly promise yourself that those methods should be ignored in the derived class? Or do you find yourself overriding methods from the superclass, making them no-ops so no one calls them inadvertently? Or giving hints to your API doc generation tool to omit the method from the doc?
Those are strong clues that aggregation is the better choice in that case.
I see a lot of "is-a vs. has-a; they're conceptually different" responses on this and the related questions.
The one thing I've found in my experience is that trying to determine whether a relationship is "is-a" or "has-a" is bound to fail. Even if you can correctly make that determination for the objects now, changing requirements mean that you'll probably be wrong at some point in the future.
Another thing I've found is that it's very hard to convert from inheritance to aggregation once there's a lot of code written around an inheritance hierarchy. Just switching from a superclass to an interface means changing nearly every subclass in the system.
And, as I mentioned elsewhere in this post, aggregation tends to be less flexible than inheritance.
So, you have a perfect storm of arguments against inheritance whenever you have to choose one or the other:
Your choice will likely be the wrong one at some point
Changing that choice is difficult once you've made it.
Inheritance tends to be a worse choice as it's more constraining.
Thus, I tend to choose aggregation -- even when there appears to be a strong is-a relationship.
The question is normally phrased as Composition vs. Inheritance, and it has been asked here before.
I wanted to make this a comment on the original question, but 300 characters bites [;<).
I think we need to be careful. First, there are more flavors than the two rather specific examples made in the question.
Also, I suggest that it is valuable not to confuse the objective with the instrument. One wants to make sure that the chosen technique or methodology supports achievement of the primary objective, but I don't thing out-of-context which-technique-is-best discussion is very useful. It does help to know the pitfalls of the different approaches along with their clear sweet spots.
For example, what are you out to accomplish, what do you have available to start with, and what are the constraints?
Are you creating a component framework, even a special purpose one? Are interfaces separable from implementations in the programming system or is it accomplished by a practice using a different sort of technology? Can you separate the inheritance structure of interfaces (if any) from the inheritance structure of classes that implement them? Is it important to hide the class structure of an implementation from the code that relies on the interfaces the implementation delivers? Are there multiple implementations to be usable at the same time or is the variation more over-time as a consequence of maintenance and enhancememt? This and more needs to be considered before you fixate on a tool or a methodology.
Finally, is it that important to lock distinctions in the abstraction and how you think of it (as in is-a versus has-a) to different features of the OO technology? Perhaps so, if it keeps the conceptual structure consistent and manageable for you and others. But it is wise not to be enslaved by that and the contortions you might end up making. Maybe it is best to stand back a level and not be so rigid (but leave good narration so others can tell what's up). [I look for what makes a particular portion of a program explainable, but some times I go for elegance when there is a bigger win. Not always the best idea.]
I'm an interface purist, and I am drawn to the kinds of problems and approaches where interface purism is appropriate, whether building a Java framework or organizing some COM implementations. That doesn't make it appropriate for everything, not even close to everything, even though I swear by it. (I have a couple of projects that appear to provide serious counter-examples against interface purism, so it will be interesting to see how I manage to cope.)
I'll cover the where-these-might-apply part. Here's an example of both, in a game scenario. Suppose, there's a game which has different types of soldiers. Each soldier can have a knapsack which can hold different things.
Inheritance here?
There's a marine, green beret & a sniper. These are types of soldiers. So, there's a base class Soldier with Marine, Green Beret & Sniper as derived classes
Aggregation here?
The knapsack can contain grenades, guns (different types), knife, medikit, etc. A soldier can be equipped with any of these at any given point in time, plus he can also have a bulletproof vest which acts as armor when attacked and his injury decreases to a certain percentage. The soldier class contains an object of bulletproof vest class and the knapsack class which contains references to these items.
I think it's not an either/or debate. It's just that:
is-a (inheritance) relationships occur less often than has-a (composition) relationships.
Inheritance is harder to get right, even when it's appropriate to use it, so due diligence has to be taken because it can break encapsulation, encourage tight coupling by exposing implementation and so forth.
Both have their place, but inheritance is riskier.
Although of course it wouldn't make sense to have a class Shape 'having-a' Point and a Square classes. Here inheritance is due.
People tend to think about inheritance first when trying to design something extensible, that is what's wrong.
Favour happens when both candidate qualifies. A and B are options and you favour A. The reason is that composition offers more extension/flexiblity possiblities than generalization. This extension/flexiblity refers mostly to runtime/dynamic flexibility.
The benefit is not immediately visible. To see the benefit you need to wait for the next unexpected change request. So in most cases those sticked to generlalization fails when compared to those who embraced composition(except one obvious case mentioned later). Hence the rule. From a learning point of view if you can implement a dependency injection successfully then you should know which one to favour and when. The rule helps you in making a decision as well; if you are not sure then select composition.
Summary: Composition :The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. Generlization: From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called. (very few occassions when Generalization wins). And never forget that with composition you are using inheritance too, from a interface instead of a big class
Both approaches are used to solve different problems. You don't always need to aggregate over two or more classes when inheriting from one class.
Sometimes you do have to aggregate a single class because that class is sealed or has otherwise non-virtual members you need to intercept so you create a proxy layer that obviously isn't valid in terms of inheritance but so long as the class you are proxying has an interface you can subscribe to this can work out fairly well.

Python encapsulated attributes on real world

I was doing some research about the use of encapsulation in object oriented programming using Python and I have stumbled with this topic that has mixed opinions about how encapsulated attributes work and about the usage of them.
I have programmed this piece of code that only made matters more confuse to me:
class Dog:
def __init__(self,weight):
self.weight = weight
__color =''
def set_color(self,color):
self.__color = color
def get_color(self):
print(self.__color)
rex = Dog(59)
rex.set_color('Black')
rex.get_color()
rex.color = 'White'
rex.__color = rex.color
print(rex.__color)
rex.get_color()
The result is:
>Black
>White
>Black
I understand that the reason behind this is because when we do the assignment rex.__color = rex.color, a new attribute is created that does not point to the real __color of the instanced Dog.
My questions here are:
Is this a common scenario to occur?
Are private attributes a thing used really often?
In a language that does not have properties (eg. java) this is so common that it has become a standard, and all frameworks assume that getters/setters already exist.
However, in python you can have properties, which are essentially getters/setters that can be added later without altering the code that uses the variables. So, no reason to do it in python. Use the fields as public, and add properties if something changes later.
Note: use single instead of double underscore in your "private" variables. Not only it's the common convention, but also, double underscore is handled differently by the interpreter.
Encapsulation is not about data hidding but about keeping state and behaviour together. Data hidding is meant as a way to enforce encapsulation by preventing direct access to internal state, so the client code must use (public) methods instead. The main points here are 1/ to allow the object to maintain a coherent state (check the values, eventually update some other part of the state accordingly etc) and 2/ to allow implementation changes (internal state / private methods) without breaking the client code.
Languages like Java have no support for computed attributes, so the only way to maintain encapsulation in such languages is to make all attributes protected or private and to eventally provide accessors. Alas, some people never got the "eventually" part right and insist on providing read/write accessors for all attributes, which is a complete nonsense.
Python has a strong support for computed attributes thru the descriptor protocol (mostly known via the generic property type but you can of course write your own desciptors instead), so there's no need for explicit getters/setters - if your design dictates that some class should provide a publicly accessible attribute as part of it's API, you can always start with just a public attribute and if at some point you need to change implementation you can just replace it with a computed attribute.
This doesn't mean you should make all your attributes public !!! - most of the time, you will have "implementation attributes" (attributes that support the internal state but are in no way part of the class API), and you definitly want to keep those protected (by prefixing them with a single leading underscore).
Note that Python doesn't try to technically enforce privacy, it's only a naming convention and you can't prevent client code to access internal state. Nothing to be worried about here, very few peoples stupid enough to bypass the official API without good reasons, and then they know their code might break something and assume all consequences.

Functions for adding nested data to model, inside or outside the model?

suppose I have a class/model building that has a relation to the class/model wall and this again to the class/model window in a form that one building can have many surfaces and a surface can have many windows (one to many).
Now when I want to add windows to that building, maybe also only to certain surfaces, should the functions(also search functions/loops) be written inside the model? Or outside in a separate class/script that is either called from the model or called from outside?
I could imagine, when the functionality is part of the model, that it could cause problems when changes are needed in the long run.
What is the cleaner architecture/standard since both could work?
If possible can you give me a source to read more into this certain problem?
In my case I'm using python with sqlalchemy and postgres, but this question could also be legitimate for other programming languages.
(I hope this question is not too broad/ opinion based)
For starters, I think this question might have been better asked in Softwareengineering. However, I might as well give you my few cents on this.
As so often, it depends ...
Generally, encapsulation is one of the core concepts in object-oriented programming.
Any change to the state of an object should be done by the object itself (although potentially triggered externally) and therefore be guaranteed to comply with the terms and conditions you defined for your object. The behavior of your object should be implemented inside your object not outside of it.
You don't want to expose your Window's attribute wall publicly for all the world to access it directly. You want to hide it behind getters and setters. You want the Window to refuse being placed on a Wall that is passed to its wall setter if said Wall happens to be 'interior'. You don't want a Person object to change the Window's state from 'open' to 'close' and vice versa directly, you want the Person to call the Window's open() resp. close() method, e.g. to ensure internally that a closed window is not closed again.
Also, hiding implementation details can help maintaining your interface and making changes to your class transparent. Say, for example, you decide that, in addition to disallow interior walls, you now also want to prevent "normal" windows from being put into exterior walls in the basement. You can implement that check into your existing wall setter in Window and the only visible change for external code would be another potential reason for refusal ("window=normal and wall=basement" in addition to "wall=interior"). Or you want to add an attribute representing the state of cleanliness of your Window and, to make a proper distinction between the new cleanliness_state and the old 'open'/'close' state, you want to rename the old attribute to open_close_state. With your methods open(), close() (and potentially is_open() and is_closed()) reading from and writing to your 'open'/'close' state attribute, this change just affects your class implementation, not every piece of code that uses it.
However!
You might have classes that just work as some sort of collection, i.e. data classes. These implement little to no functionality and publicly expose their attributes to be read and written by the whole world, thus broadly ignoring the concept of encapsulation. One could argue that classes/models implemented in an object-relational mapping layer, such as SQLAlchemy, are more of a data object/data class than an object in the OOP sense, especially when used mainly to persist and retrieve structured data. It is not unusual to have external code change the state of such an object or implement its functionality, like the views in the Django framework that uses its own ORM layer to implement and persist models.
So?
It boils down to your concrete case. You already mentioned that you consider restricting the placement of windows; probably based on properties of the windows and walls involved.
If you consider your SQLAlchemy models more than just a way of persisting your objects, go ahead and implement the behavior and change logic right away in your model. But keep in mind that a) you might end up creating conflicts with methods/properties of your model's base class and b) the attributes of your models must remain publicly exposed to maintain the functionality of your ORM layer (Although SQLAlchemy might be able to work with properties as long as both, getter and setter are defined; I have never tested that).
If you want the models to be a rather convenient method of persisting and retrieving your structured data, keep them clean and go for some utility functions or classes that implement your object's behavior and ensure its contract when being used in the code; e.g. have a function place_window_on_wall(window: Window, wall: Wall) that takes care of validation and restrictions when you try to reference a Wall object on your Window's wall attribute. But keep in mind that changes to your model must be reflected in these functions / classes as well.
I consider both options valid; just whatever you opt for, be consistent with your decision.

Should I still create a class, if it can only have one instance?

I am new to OOP and am writing a small tool in Python that checks Bitcoin prices using a JSON load from the web Bitcoin() class, it monitors the prices Monitor(), notifies the user when thresholds are met Notify() and uses a console-interface Interface() for now to do so.
I have created a Bitcoin() class that can read the prices and volumes from the JSON load. The __init__ definition connects to the web using socket. Since every instance of this class would result in a new socket, I would only need/want one instance of this class running.
Is a class still the best way to approach this?
What is the best way to get other classes and instances to interact with my Bitcoin() instance?
Should I global a Bitcoin() instance? Pass the instance as an argument to every class that needs it?
The first thing which concerns me is the SRP violation, your Bitcoin class probably shouldn't be responsible for:
opening socket,
parsing results,
rendering output.
I don't know the details but from my point of view you should split that functionality to smaller classes/functions (in case of using only modules), and one of them will be responsible for retrieving data from web. Please also keep in mind that global state is evil (singletons in some contexts could be described as global state).
Another thing which is a smell from my point of view is opening a socket inside the constructor. This isn't testable, of course you could mock/stub socket, but from my point of view it's better when class requires all it's dependencies as a constructor parameter. By doing it that way you could also notice some classes with to wide responsibility (if your constructor requires more that 3,4 parameters it definitely could be simplified).
http://www.youtube.com/watch?v=o9pEzgHorH0
I'm not sure how relevant this video is for your project (no code to actually read). But maybe you'll pick up the answer to your question. At least you'll learn something new and that's what were here for.
If I were you my code would be something like:
( a class for every set of jobs, which is not what you are doing )
class Interface:
''' Handle UI '''
...
class Connect:
''' Handle web interface '''
...
class Bitcoin:
''' Handle the calculations '''
...
class Notify:
''' Notifier '''
...
In short, split your classes into smaller simpler classes.
Now for your question:
Yes, because you have a "complex-ish" problem at hand and you're using Python, so it's definitely easier to create a OOP version than a non-OOP one. So, unless you have a good reason not to, Stick to OOP.
In your case, it might as well be passing the instance as an argument.
This is a good idea. This eliminates the problems caused by scopes if you don't have a very good understanding of them.
But remember you pass the reference, not the value, so manipulating the instance, can and will affect other classes the instance is passed to.
Note: Opening a socket in the constructor of the class is not a good idea. It might be better if you have it in a method.
The answer is maybe. Depends upon you whole architecture,
You should look at the singleton pattern, because you description yells Singleton all over.
http://de.wikipedia.org/wiki/Singleton_%28Entwurfsmuster%29
If you don't find any good reason against creating a class in your given architecture, then just go for it.
OOP is a tool, not a goal, you can make a decision whether to use it or not. If you use a Python module, you can achieve encapsulation without ever writing "class".
Sure, you can use python classes for this purpose. You can use module-level instances as well(no global keyword or explicit passing as arguments needed). It is a matter of taste IMHO.
Basically you're asking about Singleton pattern python-specific implementation, it has been answered here:
Python and the Singleton Pattern
Description of pattern itself can be found here: http://en.wikipedia.org/wiki/Singleton_pattern

Categories