What's Object Oriented Programming? [closed] - oop

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm pretty new to programming with Object Oriented Programming Languages.
So please how do you explain the concept of object oriented programming to a kid?

Some of the key concepts you need to understand are objects and classes for Object Oriented Programming (OOP). This is a very basic explanation, but hope can help you understand other documentation.
Let's compare OOP with chocolate molds. The first thing you have to do to make some chocolates, you need to build its mold. The mold will have some characteristics for the future chocolates like shape, size, etc. depending on how you create the mold the future chocolates will be.
Once the mold is ready you can create the chocolates. All chocolates will take the mold characteristics, will have the same shape and size, but there will be some characteristics on the resultant chocolates that you will be able to modify like i.e. the type of chocolate (black or white), you will also be able to fill in the chocolate with different things like nuts, almonds, peanuts, etc.
So, in this analogy, the mold are classes and they will condition the resultant chocolates. Chocolates are objects created based on a class. Objects are also called instances of a class.
Classes have attributes or variables, on this analogy the attributes would be: chocolate_type: (black/white), chocolate_filler (nuts, almonds, peanuts, nothing, etc), elaboration_date, due_date.
When a new object is created you will have to define each one of their attributes like:
chocolate1: black, filled with nuts, elaborated: 01/01/2016, dd: 03/01/2016
chocolate2: white, filled with almonds, elaborated: 01/01/2016, dd: 03/01/2016
chocolate3: black&white, filled with nuts, elaborated: 01/01/2016, dd: 03/01/2016
Chocolates Analogy
The attributes of a class are defined using variables such as string, boolean, integer, etc.
Also each object can have methods/functions that will define their behavior (what actions each object can perform).
https://en.wikipedia.org/wiki/Object-oriented_programming
Hope, this very basic explanation helped you.

Object Oriented Programming (OOP) is the art of code to some, and a really hostile programming environment to others. OOP is basically when you use constructors/classes to define objects. OOP is beneficial in my profession, because of its developed design patterns such as inheritance and encapsulation. Although OOP does have a few flaws, it's really useful when you want to use one of the 24 design patterns, but can be annoying when dealing with simple functionality. I would recommend it when you would like to create multiple objects with the same methods and values. You should google it for furthermore info & how you can learn it. I recommend author Marijn Haverbeke's book called Eloquent Javascript. The free PDF of the whole book is here. This book helps you master JavaScript and talks a lot about OOP starting from the 6th chapter called "The Life of Objects". I hope this helped you learn more about OOP :)

A design patern to develop an application in a more moduler way, rather than writing a flat coded application & preventing repetition of code.
For example, if i have a bug in the code - i can go and fix the bug in one place, knowing i won't have to edit the same code in different places.
Easlaly organize my code - separetly, to handle different issues in my application.
For example, comunicating with the database - so i'll have specific (class) files that handle my DB.
Customizing my own objects using classes can help define methods, properties and events, that will apply on all created objects later.
For example, if i have a website that singns up users - i can automatically create a new user object that has all the funtionalities that all the other users have.
OOP can help create different settings for different objects without repeating code by creating some kind of a template.
Sooo.. in continue to the previous users example, i can set a general user class that has common general settings, and apply it to all users, extend it with other classes such as admin users, regular users, baned users, ect' - without repeating my code.

Related

How do we decide what should be an object

An object oriented application is made up of several different objects. Before engineers start writing code for the participating objects:
How does one decide what should be an object?
Your question is too open as to admit a concrete answer, so let me provide some thoughts that could help you get started.
Let's assume that we are going to use a pure OO language like Smalltalk where everything is an object.
When working with objects for representing some reality (or fantasy) you usually don't try to identify all of them before you start. Instead, you identify the few that first come to mind as good representatives of your domain. For instance, if you are writing an application for modeling some aspects of Chemistry, you might want to start with Atom and Molecule.
Generally speaking, you should try to focus on concrete an important entities from your domain. Do not think in their interactions yet.
Once you have identified the first few objects, you should focus on the inherent behavior of each of them. For instance, if you are modeling a colony of ants, then your Ant objects will have to know how to move around, how to get back to the nest, how to cut or carry a leaf, etc.
As soon as you add more and more methods to your objects you will discover new objects that are required to enhance the behavior of the ones you have identified. For instance, if you are modeling a chess game, and you have already identified the Pawn object, you will soon realize that you need to model the CheckBoard, the CheckGame and so on.
So, the identification of objects is not something you try to address before you start. Instead, it is something that you will naturally discover by the evolution of your model. As your objects mature, i.e., as they learn more things, they will "reveal" which other objects are still missing.
In the course of your modeling you will likely hit some pieces of knowledge you lack. Here is when you need to ask a domain expert, read or study related material, ask questions in fora such as Stack Overflow, etc. In this regard you will find yourself learning more about the domain so you can "explain" your newly acquired knowledge to your objects. In some regards you will feel that your objects are asking you questions that you would have never conceived yourself and all these activities will fruitfully populate your model with an increasing number of classes (or prototypes) and methods.
I must say this is a very interesting question, how someone identify the object. Based on my knowledge I would like to say that programmer should not worry about object as it is the representation of something. It is good to relate object oriented programming with real world. So programmer should firstly identify the class which can be the real world entity and then to describe that real world entity we need object.
For suppose you are developing a project for the librarian, who informed you below problem
"As a librarian, I want library management system where there are different types of reader for books, magazines, CDs and DVDs" (something like this)
So developer can easily identify the class based on its real world representation
classes should be
Librarian
Book
Magazine
CD
Reader
And object can be Programming C++ book, Advance JAVA book. Hardik is the reader etc.
So, the object is the representation of the real world entity, which has some specific meaning.

Designing "Shirt" Class in Object Oriented Way

I was discussing an exercise design problem with my friend and we came up with different solution. We are learning OOPS concept, so decided to show our solution here to experts and get their opinion.
Problem: Design class for Shirts. Shirts have different features like pattern, size, color etc.
Friend's Solution:
My Solution:
There would be concrete implementations, for example, small, medium, large for Size. Red, Blue, Yellow for Color. Isn't using Interfaces for Pattern, Size, Color is an overkill? Polymorphism should be used to encapsulate behavior, but I am using it in different way.
May some expert please let us know how we should hold different features of Shirt in Object Oriented Way? How to handle new features (e.g., shades) if they come in?
Your friend's idea is simple and I like to start with simple ideas and improve them when needed. On the other hand your solution provides great flexibility and you took OOP to the maximum by using an interface type for each variable instead of native types.
Regarding the last thing you mentioned on handling new features, well in both designs you have to open the class for modification which is not a great thing as it violates the OCP principle (classes should be open extension, closed for modification).
I would solve that by letting the Shirt class hold properties which are common to all shirts like size, color, price or whatever and store the rest of the features that can vary in a HashMap or a PropertyList.
This gives great flexibility as when new features come-in you just call a method like AddFeature(name, value) that stores the feature in the HashMap.
I wanna make one point pretty clear, don't deep dive into design and let it consume your time. Instead start with simple ideas and improve them as you go on. Great design comes from experience and careful analysis of the business domain.

Why use classes instead of functions? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I do know some advantages to classes such as variable and function scopes, but other than that is just seems easier to me to have groups of functions rather than to have many instances and abstractions of classes. So why is the "norm" to group similar functions in a class?
Simple, non-OOP programs may be one
long list of commands. More complex
programs will group lists of commands
into functions or subroutines each of
which might perform a particular task.
With designs of this sort, it is
common for the program's data to be
accessible from any part of the
program. As programs grow in size,
allowing any function to modify any
piece of data means that bugs can have
wide-reaching effects.
In contrast, the object-oriented
approach encourages the programmer to
place data where it is not directly
accessible by the rest of the program.
Instead the data is accessed by
calling specially written functions,
commonly called methods, which are
either bundled in with the data or
inherited from "class objects" and act
as the intermediaries for retrieving
or modifying those data. The
programming construct that combines
data with a set of methods for
accessing and managing those data is
called an object.
Advantages of OOP programming:
MAINTAINABILITY Object-oriented programming methods make code more maintainable. Identifying the source of errors is easier because objects are self-contained.
REUSABILITY Because objects contain both data and methods that act on data, objects can be thought of as self-contained black boxes. This feature makes it easy to reuse code in new systems.Messages provide a predefined interface to an object's data and functionality. With this interface, an object can be used in any context.
SCALABILITY Object-oriented programs are also scalable. As an object's interface provides a road map for reusing the object in new software, and provides all the information needed to replace the object without affecting other code. This way aging code can be replaced with faster algorithms and newer technology.
The point of OOP is not to 'group similar functions in a class'. If this is all you're doing then you're not doing OOP (despite using an OO language). Having classes instead of just a bunch of functions has a side effect of 'variable and function scopes' that you mention, but I see it just as a side effect.
OOP is about such concepts as encapsulation, inheritance, polymorphism, abstraction and many others. It is a specific way of software design, a specific way of mapping a problem to a software solution.
Grouping functions in a class is by no means the norm. Let me share some of the things I have learned through experimentation with different languages and paradigms.
I think the core concept here is that of a namespace. Namespaces are so useful that they are present in almost on any programming language.
Namespaces can help you overcome some common problems and model various patterns that appear in many domains, e.g., avoiding name collisions, hiding details, representing hierarchies, define access control, grouping related symbols (functions or data), define a context or scope ... and I'm sure there are more applications.
Classes are a type of namespace, and the specific properties of classes vary from language to language and sometimes from version to version of the same language, e.g., some provide access modifiers, some do not; some allow inheritance from multiple classes, others do not. People have been trying to find the magic mix of features that will be the most useful and that in part explains the plethora of available options in different programming languages.
So, why use classes, because they help solve certain kinds of problems in a way that seems natural or maybe intuitive. Every time we write a computer program we're trying to capture the essence of the problem and if the problem can be modeled by using some of the patterns mentioned above then it makes perfect sense to use those features of a language that help you do that.
As the problem becomes better understood you might realize that certain parts of the program could be better implemented by using a different paradigm/feature/pattern and then it's time for refactoring. Most programs I have had the chance to work on keep evolving until either the money/resources run out or when we arrive at the point of diminishing returns, many times you have something that's good enough for now and there's little incentive to keep working on it.
It's not the norm, it's just one way of doing it. Classes group methods (functions) AND data together, based on the concept of encapsulation.
For lager projects it often becomes easier to group things this way. Many people find it easier to conceptualizes the problem with objects.
There are many reasons to use classes, not the least of which is encapsulation of logic. Objects more closely match the world we live in, and are thus often more intuitive than other methodologies. Consider a car, a car has properties like body color, interior color, engine horsepower, features, current mileage, etc.. It also has methods, like Start (), TurnRight(.30), ApplyBrakes(.50). It has events like the ding when you open your car door with the keys in the ignition.
Probably the biggest reason is that most applications seem to have a graphical component these days and most of the libraries for graphical user interface are implemented with object models.
Polymorphism is probably a big reason, too. The ability to treat multiple types of objects generically is quite helpful.
If you are a mathematician, a functional style may be more intuitive, ML, F#. If you’re interacting with data in a predictable format, a declarative style would be better like SQL or LINQ.
In simple words, it seems to me that (apart from everything everyone is saying) that classes are best suited for large projects, especially those implemented by more than one programmer to facilitate keeping things tidy; as using functions in such situations can become rather cumbersome.
Otherwise, for simple programs/projects that you would implement yourself to do one thing or another, then functions would do nicely.

When is a class too big or too small? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I recently had my code reviewed by a senior developer in my company. He criticized my design for using too many classes. I am interested to hear your reactions.
I was tasked to create a service which produces an xml file as a result of manipulating 3 other xml files. Let's name these aaa.xml, bbb.xml and ccc.xml. The service works in two phases. In phase one it scrubs aaa.xml against bbb.xml. In the second phase, it merges the product of phase one with ccc.xml to produce a final result.
I chose a design with three classes: an XmlService class which used two other classes, a scrubber class and a merger class. I kept the scrubbing and merging classes separate because the both classes were large and featured distinct logic.
I thought my approach was good because it kept my classes small and cohesive. My approach also helped to control the size of my test class.
The senior developer asserted that the scrubbing and merging classes would only be used by the XmlService class, and should therefore be part of it. He felt this would make the XMLService cohesive and this is what being cohesive means according to him. He also feels that breaking up classes this way makes them loose cohesiveness.
The irony is I tried to break these classes to achieve cohesiveness. What do you think? Who is right or wrong? Are we both right? Thank you for your suggestions.
If you follow the single responsibility principle (and based on the tone of your question, I think you do follow it), then the answer is clear:
A class is too big when it does more than one thing; and
A class is too small when it fails to fulfill its purpose.
That's very broad and indeed subjective -- hence the struggle with your colleague. On your side, you can argue:
There's absolutely no problem in creating additional classes -- It's a non-issue, compile-wise and runtime-wise.
The current implementation of the service may suggest that these classes "belong" to it, but that may change.
You can test each functionality separately.
You can apply dependency injection.
You ease the cognitive load of understanding the inner working of the service, because its code is smaller and better organized.
Furthermore, I think your boss has a misguided understanding of cohesion. Think of it as focus: the narrower the focus of your program, the higher the cohesion. If the code on your satellite classes is merged within the service class, the latter becomes less focused (less cohesive). It's generally accepted that higher cohesion is preferred over lower cohesion. Try to enlighten his/her view about it.
Cohesion is a measure of how strongly related is the functionality within a body of code. That said, if merging and scrubbing aren't strongly related, including them both in the same class reduces cohesion.
The Single Responsibility Principle is also worth mentioning here. Creating a class for the sole purpose of scrubbing and another for the sole purpose of merging follows this principle.
I'd say your approach is the better of the two.
What would you name the classes? ScrubXml and MergeXml are nice names. ProcessXML and ScrubAndMergeXml aren't, the first being too general and the second having a conjunction. As long as none of the classes rely at all on the internals of one or the others (i.e., low coupling), you've got a good design there.
Names are very useful in determining cohesion. A cohesive module does one thing, and therefore has a simple specific name. A module that does more than one thing is less cohesive, and needs a more general or more complicated name.
One problem with merging functionality in X into Y if X is only used by Y is the reductio ad absurdam: if your call graph is acyclic, you'll wind up with all your functionality in one class.
As someone who is coming back from the GodClass building fest of several years in duration, and now trying very hard to avoid that mistake in the future; the error of making a 6000 to 10000 line single source unit with a single class, with over 250 methods, 200 data fields, and some methods over 100 lines, the single responsibility principle looks like something worth defending against the predilections of your unenlightened supervisor.
If however, your supervisor and you are disagreeing over a matter of whether 2000 lines of code belong in one class or three, then I think you're both closer to sane, than I was. Maybe it's a matter of scale and perspective. Some object oriented programming aficionados like a certain "Coefficient of Standalone" per class, in direct violation of the generally understood ideas about how to improve cohesion and minimize coupling.
A set of 3 classes that work well together is, objectively, a more object-oriented system, than a single class that does the same thing. one could argue that if you write an application using only one class, that the application is not really object oriented at all.
If the scrubber and merger are not meaningful outside the context of the main class, then I agree with your reviewer, particularly if you've had to expose any implementation details in order to allow this separation. If you're using a language supporting nested private classes or something similar, that might be a reasonable alternative to maintain the logical separation without exposing implementation details to outside consumers of the main class.
This is a very subjective area, and will be different depending on coding and style guidelines, and who approves your code.
That said, if your defense of your design didn't hold up, and your senior team member still insisted on merging your classes, then you have to compromise:
You've already got the logic separated out. Write the one service class and keep the methods separate like other good design, and then write a glue method. Add some comments above each method explaining how they could easily be partitioned to multiple classes if the need arises in the future.

What is the difference between a software development pattern a methodology(agile, dsdm etc) and a paradigm(specifically object oriented)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
What is the difference between a software development pattern?
A methodology such as agile DSDM etc how is OO classed as a methodology and a paradigm?
How can OO be applied to a methodology such as agile if itself is a methodology?
Whats the difference between a paradigm and a methodology or a development pattern?
Thanks for any replys.
"When I use a word," Humpty Dumpty
said, in a rather scornful tone, "it
means just what I choose it to mean -
neither more nor less." "The question
is," said Alice, "whether you can make
words mean so many different things."
"The question is," said Humpty Dumpty,
"which is to be master - that's all."
Through the Looking Glass.
Well, not my answer, Lewis Carroll's.
Looking at only one of the questions you asked: "...how is OO classed as a methodology and a paradigm?"
That, at least, has a fairly simple answer:
Object Oriented Design is an analysis methodology.
Object Oriented Programming is an implementation paradigm.
OOD involves analyzing a problem in terms of objects and their interactions. OOP involves implementing a solution as a set of interacting objects.
"Agile" (I hate that name -- though I'll admit "eXtreme Programming" is worse) is really about project management. Just for example, you can apply Pair Programming about equally to something like assembly language or C as to a language that explicitly supports object oriented programming (though being a relatively new idea, it's probably used most often in conjunction with relatively new languages).
Edit: How I'd separate "methodology" from "paradigm" is fairly simple (at least in theory).
Paradigm is really just a fancy word for "example". If I'm following that example to a meaningful degree, the source code (for example) to the program should contain direct, (fairly) clearly defined results from having followed that example. Just for the obvious one, a class publicly derived from another would be a pretty obvious indication of OOP.
A methodology, by contrast, doesn't necessarily show a direct, definable result in the source code. Just for example, there's unlikely to be much in the source code to indicate whether it was developed using "Agile" methodology. I might be able to take a guess if (for example) all the source code files contained comments indicating two authors, but (at best) it would a rather indirect indication of one specific piece of the methodology.
I said in theory, because things can get a bit "fuzzy" at times. If I try hard enough, I can probably write pretty close to pure procedural code, even in a language like Smalltalk that favors objects almost exclusively. Likewise, if I try hard enough I can write OO code in something like C that doesn't really support it. In a case like this, the indications of following the paradigm will usually be harder to find or define than in a more straightforward case.
Methodology is about people. Paradigm is about software.
A paradigm is a way of thinking about a problem - so objects, a relational database, lambda calculus are all models for getting a problem into your head
A methodology is a way of actualy building something based on the paradigm.
If you like, the paradigm is the architect, what are building? should it be a suspension bridge or an arch. The methodology is the engineering, how many cables, how thick, which subcontractors.