开发者

How can I get better at OOP? [closed]

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.

This might come as a strange question to many of you, and I don't actually know if it is correct to say OOP in this context, because OOP (object-oriented programming) is usually associated with programming languages like C++ and Java, and not lightweight programming languages, or scripting languages. My question, however, is in the category of JavaScript, which is also object oriented. I do know about objects, properties, methods, prototypes and constructors, I just can't seem to get into my mind when to use objects.

When I am writing my web-applications, I, for some reason, never use objects. This annoys me, because when I read about objects in a variety of books and online articles, objects make everything so much simpler and, just to put it out there, I HATE repeating myself, and this is why I wish I knew when to use o开发者_高级运维bjects.

I really want to become better at using objects and when to use objects.

Can you please mention a few situations objects would be good? It would be really nice to have written down something you know you can go back and look at when you get confused about when to use these darn objects :)

I would love simple answers explaining why and when objects are to prefer.

I would also like if you could tell me if I am to use objects when I am in some special situations generally suitable for objects i.e. every time you want to _________ then you use an object...


I really hope you understand my question and you will consider that I'm somewhat new to this site and new to JavaScript

Thanks!


You probably use objects without even realizing it.

If you're writing Javascript that interacts with the DOM, you're using objects.

If you're using any of the Javascript frameworks out there (jQuery, MooTools, etc.), you're using objects.

Using objects will be useful when you need to encapsulate some commonly used code so that it can be easily re-used (within a single application or across multiple applications like jQuery plugins...which are objects in and of themselves).

And to answer the question in the title of your post...the only way to really get better at OOP is to practice! Reading and studying the subject can only get you so far.


First, you don't need to use objects to avoid repeating yourself. If you need to do the same thing at two points in your code, you can write a plain vanilla non-OOP function to do that and call it twice.

To summarize the advantages of OOP without writing a book here, OOP basically does three things for you:

  1. Group related data together. Non-OOP programs often have a whole bunch of variables floating around in the main program that are only loosely related. With OOP, you put related variables into an object.

  2. Associate functions with data. By putting functions in an object with the data they operate on (purists will say they are then "members" rather than "functions"), you make it clear to the reader that these go together.

Combining #1 and #2 lets you hide implementation details from other objects. You create the "public interface" for a class, the set of functions that other objects should call and that represent the logical things that this class does, and then any other functions you need can be hidden. (More explicitly in some languages than in others, but that's not the point here.)

  1. Classes can inherit and mutate. If you have two similar classes A and B that should be mostly the same but with some minor differences, you can make a superclass C with all the common stuff and then A and B inherit from that and each adds in its own unique stuff. This is what is usually advertised as the power of OOP. Frankly, yes, it's way cool, and in some situations can be very handy, but I only use its true power occasionally, and I suspect the same is true of most programmers. (OOP enthusiasts feel free to jump in with how and why you use inheritance all the time.)

When to OOP it? Any time you have several pieces of data that logically go together, it makes sense to create a class to hold them. Like X and Y coordinates; or customer name, address, and zip code; or phaser range and phaser power consumption; or whatever.

Any time you have functions that logically operate on this related data, put them in the the class with the data. Like "capitalize customer name", "compute distance of this point from the origin", etc.

How and when to use inheritance is more complicated. I'll leave that for another time.


The first thing to remember, is that a lot of simple Javascript code really doesn't need to define objects (using them is inevitable, as all the stuff the DOM gives you are objects). Don't panic too much.

One of the good things about Javascript is that it supports a lot of different styles; OOP, imperative and functional.

One of the bad things about using Javascript is that because it supports a lot of different styles, it's hard to learn another style, at least until you are forced to an "a-ha" moment by something else.

Spending time in languages that are more inclined to force you into OOP (even when some would argue they shouldn't) is helpful here. C# and Java force one along OOP lines, though C++ does not (with the same strength and weakness here as with Javascript).

Try to think about the "things" in your program. Some of these things will already be modelled by objects (those the DOM gives you). Some really will just be numbers and strings and not worth composing beyond that (though learning how to add functionality to those types through prototype is a good idea too). Some will be "things" more complicated than a simple type and naturally suited to modelling as an object.

Do also look at functional programming in Javascript (e.g. passing a function as a parameter to another function is about the simplest example), as the interaction between this and OOP is one of the strongest elements in Javascript, and essential in defining methods on objects given the prototype-based OOP model it has.


My personal experience with OOP in JavaScript is a positive one, once I figured out to get it to do what I wanted of course, I usually use it in combination with jQuery so the resulting code can seem a bit.... odd.

function BlogPost(id,title,content)
{
    this.id = id;
    this.title = title;
    this.content = content;

    function display()
    {
        var post = $('<div class="blogpost"></div>');
        $(post).append('<h2>' + this.title + '</h2>');
        $(post).append('<p>' + this.content + '</p>');
        var deleteButton = $('<span class="deletePost">delete</span>')
        $(post).append(deleteButton);
        $(deleteButton).click(this.delete)

        $('#postcontainer').append(post);
    }


    function delete()
    {
        $.post('some/xhr/handeler',{id:this.id});
    }
}

This is a quick (untested) class that can be used to dynamically add blogposts to a div with id postcontainer' and handles clicks on a delete button.


Think about how you can use objects to organize and simplify your application. I have found two metaphors useful:

  • A mechanical watch is made up of a number of gears, each of which serves a single purpose in the overall operation of the machine. If you think of your application as a watch, then objects are its gears.

  • A workgroup is made up of a number of people, each of whom performs a specific job. The people communicate with each other in performing their jobs, and the jobs fall along two lines--those that perform tasks (workers), and those that organize and direct the work of other people (managers).

You can use these metaphors to organize the work your application does. Start by dividing the app into functional layers; UI, business layer, and persistence, for example. Take each of your use cases, and distribute the work it does among these layers. That should give you a starting point for the classes you will need.

Make each class as self-contained a possible. you want to seal it off when it is done, like a .NET control. Classes should communicate with each other only through their interfaces, which are made up of properties and methods. These interfaces should have the smallest footprint (fewest public properties and methods) you can come up with. The idea is to isolate the side effects of a change to any class to that class alone.

If you do these things, you will be ahead of 80% of all programmers. You will find it much easier to develop and maintain even large applications, because you will be able to break complex problems down to simple components.


Javascript is just a terrible language to learn OOP in. I would recommend learning OOP in another language (like Java or C++) and then learn Object Oriented syntax in Javascript. At that moment you have all the ingredients.

That's when you can decide whether or not you want to be using an object for a task in Javascript or if it is enough to use just functions.

Personally, I mostly write non-object javascript and leave objects for when a task feels object oriented to me. For example, I used an object oriented design for a drag and drop script, in which you simply made a DragNDrop object with the correct parameters and the items in your page would be dragable from that moment on, or when I wanted to simplify some javascript xml handling functions, I wrote an object that wrapped the normal xml objects.


Justin Niessner said it and I can only add to his answer...

In addition to practice, I find reading other people's code very instructive. You need to be cautious because not all code is exemplary (to say the least) but developing critical skills is part of getting better.


In my opinion I think it's better to think about OOP in the context of a particular domain or business problem. For example, JavaScript uses objects to model browser behavior and attributes, e.g., Window, Frame, History...

A domain model of a business problem will contain objects that will be reflected in the programming code written OOP. For example, a university student application will have objects for students, professors, courses, curriculums, rooms and so on. Consequently, begin with your business problem and model the domain. Your OOP code should have objects modeled from your domain.

How can I get better at OOP? [closed]

Source:http://csci.csusb.edu/dick/samples/uml0.html


You might be interested in design patterns (Book, Wikipedia), which tell you, how to solve common problems using OOP. Many classical design patterns may not be so relevant for JavaScript, since in JavaScript there are other non OOP elements (e.g. functions), which can solve some problems even more elegant.

Some simple design patterns I can recommend to start with:

  • Abstract factory: Defer the instantiation of objects. In JavaScript in most cases a function will do the job.
  • Decorator: Transparently add functionality to an object at runtime. Can also be nested. Usage example: Logging
  • Composite: Treat a tree/graph of object like a single object.


I think that using classes in general and OOP principles, makes your code neater, more readable and makes you more productive .


Recently I worked on a web application that would require heavy client side Javascript.

Coming from C#/Java background I realized that Javascript would require a change of thinking, however I still wanted to apply good OO principles if possible, in particular to control the likely complexity of the application.

After a bit of searching I found a great book called Object Oriented Javascript by Stoyan Stefanov. It truly opened my eyes to power of this often called "toy language". Some sections on functional programming concepts, variable scoping and closures may even be a bit more advanced than you want.

However reading and applying many of these concepts from this book (closures, anonymous functions etc) in Javascript, has actually even helped me back in C# land where these concepts are only now becoming more mainstream.

Given your stated situation and goal I can highly recommend this book as one of the best ways to learn about doing OO in Javascript.


Javascript is much, much less object oriented than C# or Java; don't worry if your Javascript doesn't look object oriented.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜