How to transform JavaScript OOP into functional - javascript

I'm curious how my game would look like in functional style instead of OOP.
Here are core lines of code in Node.js:
if (!player.owns(flag) && player.near(flag) && flag.isUnlocked()) {
player.capture(flag);
}
My guess was, it could look like this:
var canCapture = [not(owns), isNear, canUnlock].every(function(cond) {
return cond(playerData, flagData);
});
if(canCapture) {
// how to capture?
}
But not sure, as not experienced functional coder. I'm interested in every answer close to the subject (it can be even in other programming style).

It could look somewhat like this:
if (!player.owns(flag) && player.near(flag) && flag.isUnlocked()) {
capturingPlayer = player.capture(flag);
}
where capturingPlayer is a new object, whose difference to player is that is has captured a flag. player is unmodified by the call to capture.
If you prefer a "non-OO" syntax (whatever that could mean)
if (!owns(player, flag) && near(player, flag) && isUnlocked(flag)) {
capturingPlayer = capture(player, flag);
}
To expand and hopefully clarify a bit:
Functional programming, in the sense employed by the functional programming community, does not just mean "functions/procedures are first-class objects".
What it does mean is that functions are functions in the mathematical sense, i.e.
All functions return a value.
Every function returns the same value every time it's passed the same arguments.
A function has no side-effects whatsoever - there are no mutable objects or assignment.
So, as long as none of your object's methods mutate the object, you don't really need to change much to program in a "functional style".
Edit:
Unfortunately both "functional" and "object-oriented" (in particular) are pretty ill-defined concepts.
Try and find a definition of "object-oriented" - there are at least as many definitions as there are people attempting to define it.
To get an understanding of functional programming, read Why functional programming matters by John Hughes, at least twice.

Related

Javascript - Dependency Injection without implementation-contract (interface)

New to javascript. Let's say I have a constructor like this:
function Dependent(dependency) {
this.doSomething = function(x) {
dependency.doSomethingReal(x);
}
}
var impl = new SomeImplementation();
var dependent = new Dependent(impl);
console.log(dependent.doSomething(3));
My understanding is that there is nothing in the language that can help to ensure that impl can in fact fulfill its responsibilities (actually has a method called doSomethingReal that takes an argument).
A few questions come up:
In the constructor-function should I manually check the dependency argument to ensure that it has all the things Dependent requires?
Should I just not worry about it?
How do the other libraries deal with this situation? For example, I know there are a couple DI projects...or MVC projects that for example require their view objects to implement certain well-known-methods.
I realize that I can just pass a function into the constructor. In other words, if dependency was a function then we'd just invoke it. Is that the safest way to do it? I don't think that's what the MVC projects do...also there are times that it makes sense to pass in an object.
You can use instanceof to check if an object is an instance of another one.
For example, within your code:
function Dependent(dependency) {
// here we could check that dependency is an instance of SomeImplementation
if (!(dependency instanceof SomeImplementation))
throw "dependency must be an instance of SomeImplementation";
this.doSomething = function(x) {
dependency.doSomethingReal(x);
}
}
var impl = new SomeImplementation();
var dependent = new Dependent(impl);
console.log(dependent.doSomething(3));
In javascript it's also common to use the 'duck typing' method to validate an object. For example:
console.log (
'isABird' in duck &&
'walks' in duck &&
'swims' in duck &&
'quacks' in duck ?
"juhm... I'm pretty sure we're dealing with a duck" :
"meh... since I a expect a duck to be a bird, walks, swims and quacks, then this buddy is definitely not a duck"
);
Well, as far as I have understood it, Duck Typing would be the natural way to deal with this problem in JavaScript since JavaScript is not a strict typed language.
In consequence this would mean that you indeed just accept, that JavaScript is loosely typed and that you will have to deal with runtime-errors when you try to access a method on an object that does not have this method. (Your option 2)
Apart from that, you could use a pattern that tries to simulate interfaces or abstract classes in JavaScript which works like you have suggested in option 1 and which is described here in detail:
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#decoratorpatternjavascript
(Chapter "Pseudo-classical Decorators")
But this would also just lead to runtime-errors. The exceptions might just rise up a little earlier but not at "compile time". So in both designs you will need to test your application in order to find type-related-errors.
So I tent to accept that Duck Typing.

Prototype-binding on re-evaluated anonymous constructor retroactive to original instantiated objects

This is more of a theory question than a how-to question. I was working on a project in which objects can "differentiate" into several different types, so I decided to explore some of Javascript's dynamic features, but there's one thing that has me really confused:
OriginalConstructor = function() {this.value = 42;}
originalInstance = new OriginalConstructor();
ModifiedConstructor = eval(originalInstance.constructor);
ModifiedConstructor.prototype.addedFunction = function(x) {return this.value + x;}
modifiedInstance = new ModifiedConstructor();
document.write("modified: " + modifiedInstance.addedFunction(10));
document.write("<br>original: " + originalInstance.addedFunction(20));
Why is addedFunction bound to originalInstance, even though ModifiedConstructor was copied through eval()? Surely these two constructors can't have the same reference, can they?
Is there a way to modify an object (or future instances) without affecting other objects already instantiated from the same constructor? I know there are other ways to approach this, but I want to understand Javascript at a deeper level. Thanks for any insights you can offer.
#Felix Kling:
Thanks for the quick, clear and complete answer. For some reason, I thought the constructor property was a string that could be parsed by eval(), so now I understand why this didn't work. I still don't fully understand prototypal inheritance, but at least now I know what I need to study. Thank you!
EDIT:
I get it now. Prototypal inheritance seems pretty weird if you're coming from a background in classical OOP, but it's conceptually simpler and easier to understand, AND it's actually more powerful in some ways. If you want to learn more about Javascript's prototypal inheritance, I highly recommend these articles:
http://javascript.crockford.com/prototypal.html
http://www.laktek.com/2011/02/02/understanding-prototypical-inheritance-in-javascript/
http://blog.vjeux.com/2011/javascript/how-prototypal-inheritance-really-works.html
http://howtonode.org/prototypical-inheritance
Also, if you need this kind of flexibility, you may want to consider using an "entity system", which would offer several advantages as an alternative to a complex hierarchy of inheritance. Most articles about entity systems focus on game development, but I think this architecture could be useful for other applications as well. It's a very foreign concept to OOP programmers, so set aside everything you know about OOP and think more in terms of relational database design. Check it out:
http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/
http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/
ModifiedConstructor is not a copy of OriginalConstructor, it is one and the same function.
The first instruction in eval's algorithm is:
If Type(x) is not String, return x.
i.e. you simply get back what you pass in. OriginalConstructor === ModifiedConstructor yields true.
Is there a way to modify an object (or future instances) without affecting other objects already instantiated from the same constructor?
You can, through prototypal inheritance:
ModifiedConstructor = function() {
OriginalConstructor.apply(this, arguments);
};
ModifiedConstructor.prototype = Object.create(OriginalConstructor.prototype);
ModifiedConstructor.prototype.constructor = ModifiedConstructor;
Now you can add functions to ModifiedConstructor.prototype without affecting instances created by OriginalConstructor.
If you only want to prevent already created instances from being extended, you could just overwrite OriginalConstructor.prototype, but is not a clean solution and will also break instanceOf for the existing instances.

custom methods and the usefulness of constructors and prototype in web-dev

ok so i know that prototype is used for inheritance and when coupled with a constructor function can be used to make custom methods. so my question here is two fold: how do i make methods for pre-built JavaScript objects like integers,strings,arrays,etc...
the other question is besides making my own methods what is the usefulness of constructors/prototype in everyday web development(i.e. creating websites) or is this more so for high-end development like making a web app or developing with new tech(i.e. html5 canvas or three.js) i haven't seen an example anywhere on the web of this being used in an everyday situation.
To create a Javascript method to an already existing object, you can simple add it to its constructor's prototype:
String.prototype.firstLetter = function() { return this.charAt(0); }
var myStr = "Cool str!";
alert(myStr.firstLetter()); // 'C'
As for how useful it will be, depends on what you do with Javascript. If you write client-side code and you need to modify an existing component, monkey-patching a function may be useful there. If you need some structure on your code (and you do), creating an object to represent the interface state may be useful.
Also, knowing how to use a tool usually avoids self-harm. =)
If you are interested, you may want to take a look into Crockford's page or buy his Javascript: The Good Parts book.
There is a lot of confusion you can avoid if you get to know the language, and you may even get to like it and find out you can do a lot of useful stuff in it.
Here's an example that extends Number:
Number.prototype.between = function(a, b) {
return this >= a && this <= b
}
var num = 0;
if (num.between(0,0)) alert('is between')
else alert('not');
Although I often use the prototype, I have not yet run across a good reason to use the constuctor property, which returns the type of an Object. W3schools.com has a good illustration of this property at http://www.w3schools.com/jsref/jsref_constructor_math.asp
You can add functions into a class's prototype:
String.prototype.report_fish = function() { alert("a fish!"); };
"".report_fish();
You can do this with numbers as well, although the syntax to invoke is slightly different:
Number.prototype.report_fish = function() { alert("a fish!"); };
(0).report_fish();
As to why you'd do this, I personally believe that you should avoid doing this to built-in objects where possible. (A persistent problem to work around when building re-usable Javascript libraries used to be and probably still is people's tendency to override and extend the Object prototype.)

Keeping your javascript structured and tidy (as an OO programmer)

I've recently been playing with javascript, HTML5, chrome extensions, jQuery, and all that good stuff. I'm pretty impressed so far with the possibilities of javascript, the only thing I struggle with is structuring my code and keeping it tidy. Before I know it, functions are scattered all over the place. I've always done my programming in an object oriented manner (C++ and C#), and I find myself not being able to keep things tidy. It feels like I always end up with a bunch of static util functions, were I to 'think' in C#.
I've been looking for some information on objects in javascript, but it seems to come down to wrapping functions in functions. Is this a good way of structuring your codebase? On the surface it seems a bit hackish. Or are there other ways of keeping things tidy for an OO mindset?
One important aspect to remember about Javascript is that it is a prototypical language. Functions can be objects, and anything can be put on the object, often affecting related objects in the process. There's no official way to 'extend' an object because of this. It's a concept that I still have a hard time understanding.
Javascript 'acts' like any other OOP language for the most part, with some exceptions, namely extending objects (http://jsweeneydev.net84.net/blog/Javascript_Prototype.html).
After extensive research, I did find a very, very light-weight way to simulate expanding objects (I'm using using it in my GameAPI). The first field is the parent object, the second is the object that expands.
extend : function(SuperFunction, SubFunction) {
//'Extends' an object
SubFunction.prototype = new SuperFunction();
SubFunction.prototype.constructor = SubFunction;
},
This link might clear up some problems and misconceptions:
http://www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html
Personally, I tend to be anti-framework, and I haven't seen a framework yet that doesn't force the programmer to significantly change their programming style in this regard anyway. More power to you if you find one, but chances are you won't really need one.
My best advise is to try to adapt to Javascript's prototypical style, rather than force old methodologies on it. I know it's tricky; I'm still trying to myself.
Best of luck diggingforfire.
I generally follow the make-an-anonymous-function-then-call-it pattern. Basically, you create an inner scope and return a single object containing your interface. Nothing else escapes, because it's all trapped within the function scope. Here's an example using jQuery:
var FancyWidget = (function($) {
// jQuery is passed as an argument, not referred to directly
// So it can work with other frameworks that also use $
// Utility functions, constants etc can be written here
// they won't escape the enclosing scope unless you say so
function message(thing) {
alert("Fancy widget says: " + thing);
}
// Make a simple class encapsulating your widget
function FancyWidget(container) {
container = $(container); // Wrap the container in a jQuery object
this.container = container; // Store it as an attribute
var thisObj = this;
container.find("#clickme").click(function() {
// Inside the event handler, "this" refers to the element
// being clicked, not your FancyWidget -- so we need to
// refer to thisObj instead
thisObj.handleClick();
});
}
// Add methods to your widget
FancyWidget.prototype.handleClick = function() {
this.container.find("#textbox").text("You clicked me!");
message("Hello!");
};
return FancyWidget; // Return your widget class
// Note that this is the only thing that escapes;
// Everything else is inaccessible
})(jQuery);
Now, after all this code executes, you end up with one class, FancyWidget, which you can then instantiate.
You can define multiple classes this way too; instead of using return FancyWidget, you can return an object literal instead:
return {
FancyWidget: FancyWidget,
Frobnicator: Frobnicator,
// Nested namespaces!
extra: {
thing: thing,
blah: blah
}
};
One of the best OOP javascript libraries out there is Google's Closure library http://closure-library.googlecode.com/svn/docs/index.html
It's structured in a way that OOP programmers will be familiar with especially if you come from a java/C# background. Have a look at the source code of any file and it should feel right at home as an OOP programmer. http://closure-library.googlecode.com/svn/docs/closure_goog_graphics_canvasgraphics.js.source.html
I have never used this personally, but have seen backbone.js referenced many times to this question. See at: http://documentcloud.github.com/backbone/
Using some framework designed to meet similar requirements may be a good idea.
But there are some things you should really follow to be efficient:
remember about closures in JavaScript and do not forget about var keyword,
use callbacks where possible and reasonable, JavaScript is asynchronous by nature,

Is John Resig's OO JavaScript implementation production safe?

For a long time I have been throwing around the idea of making my JavaScript more object oriented. I have looked at a few different implementations of this as well but I just cannot decide if it is necessary or not.
What I am trying to answer are the following questions
Is John Resig's simple inheritance structure safe to use for production?
Is there any way to be able to tell how well it has been tested?
Besides Joose what other choices do I have for this purpose? I need one that is easy to use, fast, and robust. It also needs to be compatible with jQuery.
Huh. It looks much more complicated than it needs to be, to me.
Actually looking more closely I really take exception to what it is doing with providing this._super() whilst in a method, to call the superclass method.
The code introduces a reliance on typeof==='function' (unreliable for some objects), Function#toString (argh, function decomposition is also unreliable), and deciding whether to wrap based on whether you've used the sequence of bytes _super in the function body (even if you've only used it in a string. and if you try eg. this['_'+'super'] it'll fail).
And if you're storing properties on your function objects (eg MyClass.myFunction.SOME_PRIVATE_CONSTANT, which you might do to keep namespaces clean) the wrapping will stop you from getting at those properties. And if an exception is thrown in a method and caught in another method of the same object, _super will end up pointing at the wrong thing.
All this is just to make calling your superclass's method-of-the-same name easier. But I don't think that's especially hard to do in JS anyway. It's too clever for its own good, and in the process making the whole less reliable. (Oh, and arguments.callee isn't valid in Strict Mode, though that's not really his fault since that occurred after he posted it.)
Here's what I'm using for classes at the moment. I don't claim that this is the “best” JS class system, because there are loads of different ways of doing it and a bunch of different features you might want to add or not add. But it's very lightweight and aims at being ‘JavaScriptic’, if that's a word. (It isn't.)
Function.prototype.makeSubclass= function() {
function Class() {
if (!(this instanceof Class))
throw 'Constructor function requires new operator';
if ('_init' in this)
this._init.apply(this, arguments);
}
if (this!==Object) {
Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype;
Class.prototype= new Function.prototype.makeSubclass.nonconstructor();
}
return Class;
};
Function.prototype.makeSubclass.nonconstructor= function() {};
It provides:
protection against accidental missing new. The alternative is to silently redirect X() to new X() so missing new works. It's a toss-up which is best; I went for explicit error so that one doesn't get used to writing without new and causing problems on other objects not defined like that. Either way is better than the unacceptable JS default of letting this. properties fall onto window and mysteriously going wrong later.
an inheritable _init method, so you don't have to write a constructor-function that does nothing but call the superclass constructor function.
and that's really all.
Here's how you might use it to implement Resig's example:
var Person= Object.makeSubclass();
Person.prototype._init= function(isDancing) {
this.dancing= isDancing;
};
Person.prototype.dance= function() {
return this.dancing;
};
var Ninja = Person.makeSubclass();
Ninja.prototype._init= function() {
Person.prototype._init.call(this, false);
};
Ninja.prototype.swingSword= function() {
return true;
};
var p= new Person(true);
p.dance(); // => true
var n = new Ninja();
n.dance(); // => false
n.swingSword(); // => true
// Should all be true
p instanceof Person &&
n instanceof Ninja && n instanceof Person
Superclass-calling is done by specifically naming the method you want and calling it, a bit like in Python. You could add a _super member to the constructor function if you wanted to avoid naming Person again (so you'd say Ninja._super.prototype._init.call, or perhaps Ninja._base._init.call).
JavaScript is prototype based and not class based. My recommendation is not to fight it and declare subtypes the JS way:
MyDerivedObj.prototype = new MySuperObj();
MyDerivedObj.prototype.constructor = MyDerivedObj;
See how far you can get without using inheritance at all. Treat it as a performance hack (to be applied reluctantly where genuinely necessary) rather than a design principle.
In an a highly dynamic language like JS, it is rarely necessary to know whether an object is a Person. You just need to know if it has a firstName property or an eatFood method. You don't often need to know if an object is an array; if it has a length property and some other properties named after integers, that's usually good enough (e.g. the Arguments object). "If it walks like a duck and quacks like a duck, it's a duck."
// give back a duck
return {
walk: function() { ... },
quack: function() { ... }
};
Yes, if you're making very large numbers of small objects, each with dozens of methods, then by all means assign those methods to the prototype to avoid the overhead of creating dozens of slots in every instance. But treat that as a way of reducing memory overhead - a mere optimisation. And do your users a favour by hiding your use of new behind some kind of factory function, so they don't even need to know how the object is created. They just need to know it has method foo or property bar.
(And note that you won't really be modelling classical inheritance in that scenario. It's merely the equivalent of defining a single class to get the efficiency of a shared vtable.)

Categories

Resources