What is "Object-oriented" and what other methods?

Asked

Viewed 1,372 times

13

I work a lot in AngularJS (Javascript) and with version 2.0 knocking on the door, which will have as main change the use of ECMAS6 I read a lot about Object-Oriented Programming. If you can keep the answers in that language, already looking forward (or rather, based on ECMAS6), would be better.

First doubt: I’ve heard a lot about "Object Oriented" programming, what other types of programming exist?

Second doubt, and more importantly:

What is Object-Oriented Programming? What is it used for? When should it be used? When should it be avoided?

Many of the other answers treat this subject in a very technical way. I would like a more practical answer, I can learn better if I see the application of the theory. So if someone could answer that with a real application of programming, that would be great. That’s why I’m asking this question, because I didn’t get any practical example.

  • 3
  • 8

    The difficulty of giving a "more practical answer" is that it is possible to program well into any paradigm, so that one can give an example of an extremely well done system using OO, and another person can give such a good or better example without using any OO. This says little about the relative merit of either approach. What I realize is that there are some very specific applications in which the paradigm A or B "fits like a glove" and ends up actually delivering the advantages it promises, but in others it is not as good as the alternatives. It’s hard to list all these cases.

  • I agree with @mgibsonbr, it is not easy to answer this with these requirements. I did my best yet I think it is not ideal. If you orient more, I improve the response.

  • Do you program with a language other than javascritpt? (one that is not OO)

  • Currently I work with Angularjs (and also HTML/CSS for web and webapp) and in conjunction with the back-end staff (which is PHP). If I understand the answers correctly, I don’t actually work.

  • Regardless of work, do you program (even if by hobby) any other language ? Because with examples, or practice of other languages, it’s easier to explain.

  • @No intruder, exclusively those, at least until today, only those. Until I am more connected to UX, web design, anyway.. More for design and front-end part. But why?

  • Why the answer is easier to understand when you can compare modeling or maintenance experiences. Certain aspects, such as object definition, polymorphism, and inheritance (only a few) are easily shown in practice, but sometimes, when one uses another language, one wonders what difference this makes to other similarities in other languages, And the purpose of it gets very fuzzy. I’ll try to come up with an answer, but since your area is more front-end, some things may seem strange... at first.

Show 3 more comments

3 answers

19


I’ve heard a lot about "Object Oriented" programming, what other types of programming exist?

Imperative, Declarative, Functional, Logical, Dataflow, Function-level, Competitor, based on Automata, based on Arrays,... The list is huge, see the box on the right of that Wikipedia article (in English) to get an idea.

What is object-oriented programming?

It consists of dividing the system design into small modules - called "objects" - that unite state and demeanor (i.e. data and code acting on such data). Each object should ideally possess limited responsibility ("does only one thing and does well") and need not (ideally nor should) be aware of the rest of the objects that make up the system (i.e. its dependency to other objects must be limited). Finally, an object may have a life cycle, but the exact sequence in which its various methods will be called is not necessarily defined a priori - in particular, when an object is designed one need not yet have a view of the whole.

A program can utilise objects sporadically, but if the objects are a central aspect of either the specific system or the language/platform used, then it is said that it is "object-oriented" (Object oriented; or in the popular, "oriented to object"). An object-oriented system consists essentially of a set of exchanging objects messages among themselves. A message is the call of a method, basically: if it invokes a specific function of that object, passing arguments, this function acts both in those arguments and in the internal state of the object, and finally returns a response to who invoked the function. In the course of this, this method can send messages in turn to other objects, which will also act accordingly.

The object’s idea is that it be designed without a view of the whole, and can be included in different systems without change (i.e. reused). A good object is designed separately from any system, and a good system has a minimum of logic of its own besides "instantiating a bunch of objects" and "making them exchange messages among themselves". At least the theory is this (in practice, it is difficult to see a system that follows this protocol to the letter).

For what purpose it is used?

As techniques of OO have specific purposes: the objects themselves serve to reduce coupling and make the system very modular; the inheritance and composition serve to reuse ready-made objects in different circumstances without modification; polymorphism serves to create "generic" functions which act in similar but not identical data, etc. I cannot say whether orientation by objects as a whole has an end, except as a proposal of logical organization of the code (which is by no means the only possible, as already seen at the beginning of the answer).

When should it be used? When it should be avoided?

When the advantages it promises are actually realized. When the problem domain does not "fit" well into the OO model, or when another model brings better advantages.

Seriously, you can’t answer that in a generic way. Object orientation is a broad concept, which encompasses a number of techniques, each with its advantages and disadvantages. Fortunately, there is nothing that obliges us to follow a single iron and fire paradigm, and modern languages have incorporated more and more aspects of distinct paradigms (increasing the tooling that the programmer has at his disposal to choose). Thus, it is up to the programmer to analyze case by case if a particular technique is necessary/desirable or if it can be left aside if the benefit does not justify the cost.

So if someone could answer that with a real programming application, it would be great.

Imagine the following situation: "take a number, and create a function from that number, that each time it is invoked returns that same number incremented in N".

An object-oriented solution would be:

class Incremento {
    constructor(x) {
        this.x = x;
    }
    incrementar(n) {
        this.x += n;
        return this.x;
    }
}

// Uso

var inc = new Incremento(10);
inc.incrementar(2); // 12
inc.incrementar(3); // 15
inc.incrementar(1); // 16 

An object-oriented solution could be (using closures and first class functions):

function incremento(x) {
    return function(n) {
        x += n;
        return x;
    }
}

// Uso

var inc = incremento(10);
inc(2); // 12
inc(3); // 15
inc(1); // 16 
  • Ela consiste em dividir o design do sistema em pequenos módulos - chamados 'objetos' . Simple and clear. Perfect answer! I have found other good answers, but with many technical terms that had not been clear to me. Let’s say, roughly speaking, that OO is more a "facilitator", creating small tasks to later assemble the "Todo" (or in this case, a system).

  • 4

    That’s right! A professor of mine once said that ideally there should be two types of OO programmers: those who create generic objects without a specific system in mind, and those who simply use objects ready to "assemble" a system (i.e. take a collection of ready-made objects, instantiate them and put them to exchange messages among themselves). In practice, however, this rarely happens - objects are already designed with the final system in mind, and often have implicit or explicit dependencies to other parts of it that prevent them from being reused in other situations.

  • Yes, perfect. I was able to understand the logic behind it. I had a certain concern because I read that in ecmas6 (or at least Angularjs 2.0) OO would be used a lot, and as I did not know the purpose well, I did not know how the scenario would be.

  • 2

    @Celsomtrindade I gave an answer, because I don’t think this definition you quoted was very good (Ela consiste em dividir o design do sistema em pequenos módulos). I understand that some people cling to it. But it can be applied to other paradigms, maybe to all of them. The response of mgibsonbr as a whole is very good. Of course I will look at the context, not just the loose phrase.

  • @bigown for sure, within the context of his explanation, that phrase summed up very well. But I’m reading your answer yes, and from what little I’ve seen, I already have other horizons open.. The problem in all this will be in which answer accept, just coming top thing! hahaha

  • 1

    @Bigown It’s really a simplistic definition, but the second part - not cited - is what I consider the "breaking point" between traditional and object-based imperative programming: linking the state to behavior. Although the concept of "type" preceded that of "object", data types were normally dissociated from the operations that acted on this data. This cohesion (not necessarily good, by the way) for me is one of the central points (although by my age I have never actually experienced structured programming, so my point of view is limited).

  • @mgibsonbr I agree. Even not having much space, I took care not to pass the idea that there is error there and that the whole makes clearer. If there wasn’t the comment Up there with the phrase loose, it would go unnoticed. And I agree even more that the cohesion and the coupling of the state with behavior can be quite harmful and defeat the most basic purpose of modernizing programming styles. You do structured programming all the time. Do you know what this is? Just structured, with nothing else maybe you’ve never actually done. I’ve already done :D

  • @bigown " You do structured programming all the time. You know what this is?" yes, I do mean "only structured". I had a little bit of unstructured programming too, but only in college, studying basic software (Assembly). And I remember playing a little C game as a teenager, but as I learned on my own, I have no idea if my practices were good or not (probably horrible rsrs). But I never had contact with a professional system that was not OO, so my difficulty to understand how different they are.

  • I laugh so hard at my old code. '84, '94. 2004 and 2014 :D You should imagine that I think it’s a shame how OOP got into the heads of people the way it did. And you know I’m not hater of the paradigm (perhaps of excessive use of it :) ), but some people read mine posts and thinks I am. It must be my fault, but doing what, is my way... : D

  • @mgibsonbr very good answer, congratulations! But just to see if I understood well, in his last example I could say that is using the functional paradigm?

  • 1

    @Jedaiasrodrigues No, because in the [purely] functional paradigm there are no state variables - so you can’t implement the function incremento without using any "tricks" (such as monads). A function in the functional paradigm will always return the same value given the same arguments (in other words, it cannot have side effects). Here, if I do inc(1), inc(1), inc(1) he will return 11, 12 and 13 - different values for the same argument. Because this function depends on the state variable x, that changes value whenever the function is invoked. That is, it is not functional.

  • Thank you for the reply @mgibsonbr , then this last example could be classified in which paradigm?

  • 1

    @Jedaiasrodrigues There is no single answer, because the paradigms are not mutually exclusive. I would say that this example is imperative, procedural, structured and value-level, but there may be other unquoted paradigms in which it also fits... But it is certainly not declarative (includes functional and logical) nor object-oriented.

Show 8 more comments

10

Paradigm

In the Wikipedia has an article that explains well what the paradigms are, which is the correct name of what you are calling "method". There are many, just see the table on the right side of the article. Triggered the most used is the imperative. Virtually all languages mainstrain use it intensively. I talk about it in more detail in that reply.

A programming paradigm provides and determines the programmer’s view on the structuring and execution of the program. For example, in object-oriented programming, programmers can abstract a program as a collection of objects that interact with each other, while in functional programming programmers abstract the program as a sequence of functions executed in stacked mode.

Just as different groups in software engineering propose different methodologies, different programming languages propose different programming paradigms. Some languages have been developed to support a specific paradigm (Smalltalk supports the object orientation paradigm while Haskell supports the functional paradigm), while other languages support multiple paradigms (such as LISP, Perl, Python, C++ and Oz).

Programming paradigms are often differentiated by programming techniques that prohibit or allow. For example, structured programming does not allow the use of goto. This is one of the reasons why new paradigms are considered more rigid than traditional styles. Despite this, avoiding certain types of techniques can facilitate proof of concept of a system, and can even facilitate the development of algorithms.

Examples of better known paradigms

The paradigm of object orientation is what’s most in fad. Most languages natively accept it in addition to imperative and others, such as the functional which is another that is also widely adopted in modern languages, and in some less used is the main or single paradigm.

More useful and more general languages are more pragmatic and multi-paradigm. Lately the general, reflectivity or meta-programming gain strength.

To aspect-oriented or the events and competition gained strength too, though to a lesser degree.

To declarative form of programming is also strong. It is often used to assist programming, as is the case for SQL, XML and derivatives.

The paradigm may eventually determine the dynamism of language (not to be confused with dynamic typing, which is usually present in this type of language, too). This is another paradigm. And it can be a substitute for meta-programming in many cases, although they are not direct "competitors", their goals are different.

I’ve always wanted to learn logic programming, but "never had time". It seems something very interesting that should be more mainstream.

I could go on quoting others, but I’m hardly going to talk about something that is widely used. It is a fact that we always use some less known paradigm in various parts of the code. Some paradigms are very simple, requiring something well contained, so virtually any language that implements a more general paradigm, must implement these secondary paradigms.

Classification of language by paradigms

Some paradigms are very similar to others, some have a sub-division. OOP, for example, has two "flavors": class-based or prototyping.

Note that in the Wikipedia article there is a hierarchy of paradigms. I don’t know how formal a classification this is, but it gives you an idea of how dependent some of them are. I think there is more dependence than shows there. To tell you the truth I find that article very flawed.

Some paradigms are very archaic and should no longer be used under any circumstances. Still others are not at the point that can bring good results without great harm in most cases. The most malicious will say that is the case of OO :)

But just because language has such a resource does not mean that it is of this paradigm. The analysis is a little more complex than just looking at one aspect.

These definitions are not always very clear.

Only one example of what defines whether a language is of a paradigm, in this case the functional:

Not everyone agrees with all these definitions, but it is rare to run away from this, one or the other may be more debatable. There are languages that the discussion is much larger. Let’s talk about one of them, which is the focus of the question.

Style X paradigm

Using the paradigm might look like it, but it’s not the same as using the paradigm style. PHP, for example, usually has a lot of things that can be expressed with procedural style and OOP style. This is not to say that you are following the paradigm in your code. And possibly you don’t even notice when you are using the style or the paradigm. What is troubling.

In the early 1990s many languages defined themselves as OOP, even though they did not even allow creating a class or other form of defining objects. The style was OOP, the paradigm was not. I wouldn’t sell if I didn’t say it was OOP. Then they evolved, but even today we force the use of OOP to "sell".

Procedural:

$conn= mysqli_connect(...);
$res = mysqli_query($conn, $query);
$results = array();
while ($row = mysqli_fetch_assoc($res)) {
    $results[] = $row;
}

Procedural with OOP style:

$conn = new MySQLi(...);
$res = $conn->query($query);
$results = array();
while ($row = $conn->fetch_assoc($res)) {
    $results[] = $row;
}

Modular with OOP-like classes:

class GetResults { //poderia ter outras coisas aqui
    public function getResults() {
        $conn = new MySQLi(...);
        $res = $conn->query($query);
        $results = array();
        while ($row = $conn->fetch_assoc($res)) {
            $results[] = $row;
        }
        return $results;
    }
}

A little more OOP:

class GetResults extends Results { //tem um monte de coisa pronta em Results
    public function getResults() { //Results já tem um getResults pronto, este substituiu
        $res = $conn->query($query); //notou que conn existe em outro escopo?
        $results = array();
        while ($row = $conn->fetch_assoc($res)) {
            $results[] = $row;
        }
        return $results;
    }
}

I put in the Github for future reference.

It’s a little slutty to ask this, but which one do you think is simpler? : ) Of course, the last examples are adding functionality that the first ones didn’t have. Note that the latter try to abstract more of what is being done. This can be good or bad. I see a lot of people abstracting what they don’t need, what doesn’t give gain.

In a certain way we can say that the PHP code to deal with the results of Mysql are a little functional style, mainly as the fetch_assoc() opera.

Object orientation.

I do not know if I can add much more than I have already posted in other questions:

When to use

It is difficult to state categorically when to use OOP or not. Of course it is obvious that if the language does not give support, it should be avoided. And if OOP force language helps if it follows it. There is a question trying to come to a conclusion about this in PHP.

The type of problem should be what drives the choice. But looking only at the problem, it is not always possible to determine whether or not to opt for OOP. There are "political" aspects to consider.

If you are going to program alone, if you are going to do something small, if it will not be very durable and will have relatively little maintenance, OOP is not very suitable. For example, web sites are not often complex, it is common for a single person or a very small team of programmers to provide maintenance. It is common to have little relationship between the various components of the application, the execution is usually fragmented. Of course this depends a little on the language used as well, if you are using any framework complex to "help".

It is common to be easy and simple to use a more paradigm procedural and/or modular or component-oriented. The latter has a mental model closer to what the human being understands and reproduces much better the real world (another definition used in OOP), and in fact some languages that sell as OOP are much more COP :P. But the marketing of this paradigm was not so good. And of course he has his faults. And of course if abused it becomes difficult to manipulate it.

OOP can be a burden in many cases. It’s like using a Ferrari in a Brazilian city, there’s a street that you just can’t pass with a car like that. Is it bad to use a truck to deliver a single letter (remember that paper that goes inside an envelope to communicate with other people? : ) ), but people will use when they only own the truck. How it works, they think it’s good like this.

OOP is good when you have object hierarchies, such as the GUI case, the killer application of OOP. No need for hierarchies, that is, no need for inheritance help, so you will need OOP?

Some will give other reasons, but then start talking about another paradigm and call it OOP. I see some definitions so generic about OOP that they can be applied to "half" of existing paradigms. Then it seems that he really is a panacea and everyone can pull the paradigm to the side they think best. Typical thing of marketers. I prefer decisions based on engineering.

I see a lot of OOP resources being used to adopt modularization. That’s good. But people do it with no awareness of what they’re actually wearing.

OOP may give more readability to the code in certain cases, but it may get worse in others. OOP can do the same as other paradigms do, otherwise. OOP can please some people more than others.

I see a lot of big cases frameworks benefit from it, but I don’t think it’s the only way to that kind of application. Consumers of these frameworks benefit much less from OOP, but may also in some cases more than others.

I think OOP shouldn’t be the choice default as many people do. To decide for its adoption there should be a good justification, even if more political than technical.

I find it quite curious that many proponents of OOP have passed, indirectly, to discourage its use in what is unique to it.

Choosing a paradigm has to do with the fact that the team knows how to use it better. It does not mean that it will be the best technical decision, but it will be the best policy. It is common if you choose OOP because you think it is the most adapted to the team, even if it is not the best for the problem. Interestingly, I see the opposite happening, the team doesn’t know how to use it but thinks it knows and adopts it for it. It could do better in another paradigm, not only because the problem would be better expressed in it, but also because the team dominates the other better.

Definition

I won’t keep repeating the definitions adopted, because in the questions linked above have enough stuff.

The fact that there is little agreement about what is OOP gives an idea of what is something much less scientific than some people think. Note that some paradigms have a clearer and universal definition.

Some will say that it is already OOP if the object is the center of the programming, that it is from it that everything happens. I find this simplistic. If so, I think it fits well almost always, but I can also say the same to use otherwise. That definition doesn’t give me something that makes me want to use it for something. And knowing that to give this feeling of the object to be king it is necessary to do extra things and overcharge.

I prefer the simplest, most procedural/modular way. Many people prefer OOP for this because the existing material of this paradigm encourages modularize well. Material from other paradigms does not do it so well. The legacy of Macaroni codes of certain paradigms hurt them a lot. The fact of no language mainstream implement some paradigm that solved the problems of older paradigms, helped to give gas to OOP. This paradigm went up for a good reason, then they thought it was to use in everything.

I see people saying it’s about reuse. Sure, it is, but a specific form of reuse. The creation of functions is the strongest form of reuse that exists, and this is in almost all paradigms, especially the procedural (contrary to what some believe, procedural is not the paradigm that has procedures and functional is the one that has functions, at least not in such a simplistic and mutually exclusive way, as they think).

Obviously, some of the "tools" used to get the one from OO can be applied separately, but you cannot say that you are programming object-oriented just because you are using a language that supports this and/or that uses one of the fundamental ideas of the paradigm alone.

OOP is a Lego toy, other paradigms are too. OOP lays down rules that help avoid building very weird things, but also make it difficult to assemble certain forms.

The definition of the mgibsonbr response is good, I agree with it, but I think much of what is there serves for other paradigms. I agree even more that it is difficult to define when to use. People expect a magical and definitive answer. but this does not exist.

Misuse

OOP sells well, but sells its real idea very badly. So much so that most of the OOP codes you see around are true atrocities. As one does not understand the paradigm but wants to use because it is fashionable she does worse than if she used something she can understand better.

Javascript

Javascript was originally conceived and remains an imperative language, with procedural, functional characteristics and is object-oriented by prototypes. I don’t remember if it adopts some other paradigm in a clear and substantial way (perhaps we can call dynamic language, which can allow, by table, several other paradigms, although this may not be the most recommended - the eval(), especially, operates "miracles" and the use of events is very strong in it). Now the class-based OO has also been adopted and it seems that it will adopt new functionalities that will facilitate other paradigms. And if it evolves to what the Typescript (the language of Angularjs 2) is adopting so will adopt other paradigms, as the generality, which has become fundamental in static languages (this can happen with JS, there is a lot of advantage in this and JS, today, needs it more than PHP, for example).

As far as I know, Angular embraces all these paradigms that language provides. Which doesn’t necessarily mean you have to do the same thing every time. Consuming a paradigm is not the same as producing code that implements the paradigm. Unfortunately my knowledge about this technology does not allow me to speak much more than this :P.

  • +1 very good answer, in particular the first part that describes the paradigms. And arrange a little time to learn programming in logic! I think Prolog is fantastic (I/O is a disgrace, but the rest is show), if you asked me what would be a single feature that I would add in a language that I already consider excellent (Python type) I would certainly answer programming in logic. :)

  • I couldn’t even learn Haskell even though it’s a priority (functional as a whole I still need to really learn)

  • 1

    For me, the worst thing with Lisp was to change his mind so he wouldn’t use variables. The functional paradigm is very practical in relation to a mathematical modeling of the thing, but, the habit is a terrible thing :).

  • 1

    @mgibsonbr I don’t even think it’s that good. I’ve improved it now. But I don’t think it deserves negative either. But now every day I get several negatives. Apparently it’s normal since it’s not serial, but it’s weird to have times when I get negative for a good part of what I answer. Soon the person tires and see does not touch my reputation. Pity that the content is damaged.

2

Object orientation is a programming paradigm, which is a way of thinking about how to model and organize software, in addition to the resources already known as herence, polymorphism and encapsulation or 'advantage' that they sell is that the software created with this approach is easier to understand as objects must simulate their behaviors and relationships in almost the same way that occurs in the real world (abstraction).

Other paradigms that exist are: functional, procedural, aspect-oriented, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.