I have a very common pattern of "given a Foo, return a Bar," for example, given a user_id, return a User.
Is there a conventional naming pattern for these sorts of functions? Following Joel on Software, I've personally used a lot of bar_from_foo(), but I rarely see other people do this and it quickly becomes verbose, e.g.
widgets = user_widgets_from_user(user_from_param_map(params))
Is there a conventional way to name, or namespace (e.g. User.from_map()) in any of the popular languages out there? I am particularly interested in Python but any language you can think of would br useful.
I would take advantage of Clojure's naming flexibility and call it:
(defn foo->bar [] ...)
To me that makes the intent quite clear and it's pretty short.
In Python, and various other OO languages, this should be a constructor on Bar that takes a single Foo as its only argument. Since Python doesn't do method overloading (and attempts to emulate it are usually fragile), if Bar.__init__ already takes a different signature, then the convention is exactly your last one. Importantly, this is usually defined as a class method rather than a static method (for the benefit of subclasses):
class Bar:
#classmethod
def from_foo(cls, f):
'''Create a new Bar from the given Foo'''
ret = cls()
# ...
If you want to convert something into another, for example a string to an integer, the method is to be defined on the receiver, and hence its class is clear, so you should not put the receiver class as part of the method name: String#to_i, not String#string_to_i. This in one of the core ideas of object oriented programming (polymorphism).
If the receiver is too general to be assigned such method, for example if user_id is a mere string, and defining a method on String to convert it to a User does not look right, then you should define a constructor method on the class that you expect the return value to be: User.new or User.from_id.
I think it depends a lot on context and choosing a meaningful metaphor. ActiveRecord for instance uses the class method "find" for finding records in the database, a more meaningful idea than "input a user_id, output a user". For example:
User.find(user_id)
User.find_by_email(user_email)
For conversions, I usually like to write the conversion methods to make it easy to use in higher order functions. For example in ruby, conversions are often done with to_* instance methods, for example to convert a Foo to a Bar it would make sense to have a to_bar method for all foos, so you could write:
foo = Foo.new(...) # make a new Foo
bar = foo.to_bar # convert it to a Bar
And then to convert a bunch of foos, you could simply:
bars = foos.map(&:to_bar)
Ruby also tends to have Foo.parse(str) for converting a string to the object.
For javascript, I like having class methods (which I got from standard ml), for example:
Foo.toBar = function(foo) {
return new Bar(...);
};
And then you can map over it as well (using underscore in this example):
var bars = _.map(foos, Foo.toBar);
the Standard ML convention is structure (class) methods. Example fn types:
Foo.toBar : foo -> bar
Foo.fromBar : bar -> foo
And you'd use it like:
val bar = Foo.toBar foo;
val bars = map Foo.toBar foos;
Why placing the type of the parameter the name of the function? I think it would be clearer something like
a_bar = bar_from(a_foo)
then you can rely on dynamic dispatch or overload in many languages... for example in Python the implementation could try to call x.toBar() if present or it could check for a global registry like Bar_builders[type(x)](x); in Lisp you could rely on methods; in C++ on overloads...
Related
What is the best practice for creating model objects in Angular / TypeScript:
Should I use type annotation with object notation (objects are plain instances of Object)? E.g. let m: MyModel = { name: 'foo' }
Should I use the new operator (objects are instances of the respective prototype)?
Should these two approaches be mixed up and used situationally? (E.g plain objects, when receiving a response from the HttpClient, but new MyModel('foobar') for convenience to create instances by passing properties as constructor arguments)
Background of this question
I'm new to TypeScript and like many other developers I come from popular object oriented languages like Java.
A core concept I understood is that type annotations in TypeScript don't play a role at runtime. They are important for the compiler and for your editor's auto completion. Basically it's ECMAScript with the addition of compile time type checks.
At the time I didn't know this and expected TypeScript to be some kind of "client side Java", I found this Angular bug report:
https://github.com/angular/angular/issues/20770
People (who don't understand TypeScript's type concept) complain about the HttpClient not converting the returned plain object to their model class type. Other people are defending this behavior and point out that there are no runtime types in JavaScript.
And here arises my problem: In fact there ARE runtime types in JavaScript. You can create instances of prototypes with the new operator and even check their constructor with the instanceof operator.
In TypeScript you have two ways for creating an instance:
1) Use the object notation (as they show in the Angular tutorial):
hero: Hero = {
id: 1,
name: 'Windstorm'
};
2) Use the new-operator:
hero: Hero = new Hero();
At the moment I'm working on a project where these two options are mixed up. I.e. model objects of the same type are instances of Object in some cases and instances of Hero in other cases.
I expect this leading to problems later, because the constructor is only called in the latter case.
My idea for a rule / best practice was to define all model instances as plain objects and to use the constructor for services, components etc. that are created by dependency injection. As a result I wouldn't use the new operator at all.
However I'm not sure if this is a good idea and I couldn't find a best practice recommendation about it.
EDIT
Important note for close voters: I'm not looking for your personal opionion here. I'm rather looking for some kind of officially documented Angular best practice, as I think it's a core design decision that has to be made right from the project start and these approaches should not be mixed up randomly without a specific reason. Maybe the answer is just a simple "There is no official recommendation which decision to make".
In my opinion, you should use the new operator to create new objects of your class if you need to perform complex operations on the object itself.
If in case you just need to access the properties only, you may use the object literal to create a new object.
This has got advantages like encapsulation, inheritance, etc. which a developer coming from the Java background could better relate to.
If you directly assign an object like below, then you have to explicitly set functions in it, for example, getName function.
hero: Hero = {
id: 1,
name: 'Windstorm',
getName: function(){ // returns name }
};
However, by defining a class Hero with a function getName and then creating an instance of that class, you would automatically get that function, no matter how many times you create instances.
For a better understanding of Object Oriented Javascript, you may follow the link below:-
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS
Regarding the below issue,
"People (who don't understand TypeScript's type concept) complain
about the HttpClient not converting the returned plain object to their
model class type."
HttpClient simply returns an object which the server sends, it is on JS to convert it into the required form. You can always map the response into the required model instance by using its constructor which could be defined as below:-
constructor(hero){
this.id = hero.id;
this.name = hero.name;
}
and you may map the array returned from the server like below:-
map(hero => new Hero(hero))
In fact there ARE runtime types in JavaScript.
Kind of. A value can have a certain type, however variables and properties don't have types bound to them. That said if you type network requests etc.
fetch("someurl").then(res => res.json()) as Promise<IUser>
and that network request suddenly returns something else than a User, nothing will fail as Typescript types do not exist at runtime. However this behaviour can be added easily with typeguards:
function isUser(user: any) : user is IUser {
return Number.isInteger(user.id) && typeof user.name === "string";
}
which allows you to do typechecks at runtime:
const result = await fetch("someurl");
if(!isUser(result)) throw new Error();
// result is definetly a IUser here
Should I use inheritance or not?
That is a question of preference. I once wrote an application that works with the db heavily, so I had to do a lot of serialization / deserialization, and it really annoyed me to always wrap the response from the db into a class instance. So for my db models I started using the following pattern:
type User = {
name: string;
id: number;
};
const User = {
get(id: number): User { /*...*/ }
changeName(user: User, name: string) { /*..*/ }
};
That allowed me to write:
const admin: User = User.get(123);
And I could simply do typecasts on the db and I both had typesafety and nice APIs.
Wether that is a good pattern for your usecase or not really depends on how much serialization / deserialization you do.
As per the understanding, The main purpose for the existence of prototype property in a function type object is to allow properties/methods sitting under prototype to get inherited by other objects. This enables prototypical inheritance.
Considering window['Number'] function type object,
In general, Idea is to understand the thought process on what comes under prototype. So. I would like to take a specific example i.e., Number, with below questions.
From design perspective, how would I understand,
1)
why parseFloat()/parseInt()/isFinite()/isInteger()/isFinite()/isNaN()/NEGATIVE_INFINITY/NaN
are part of function type object Number?
2)
why methods toExponential()/toFixed()/toPrecision() are part of Number.prototype object?
Note: Have an idea on class based inheritance using java syntax, where both static/instance members can be inherited.
If you understand classic class based inheritance, then Number.parseFloat is a static class method, while Number.prototype.toFixed is an instance method. The "class methods" do not need an instance of Number to work, you simply call them directly as Number.parseFloat(foo). Instance methods on the other hand require an instance first:
var foo = new Number(bar);
foo.toFixed();
Properties declared on the prototype object are visible from all instances. Thus:
var n1 = new Number(1), n2 = new Number(2);
Those are two instances of Number, and via each instance it's possible to call the functions on the Number prototype:
alert( n2.toExponential() ); // "2e+0"
Because of the way that function invocation works in JavaScript, the .toExponential() function in that example will be invoked with this referring to the number instance used to make the function call — n2 in this case.
Now, the .toExponential() function could have been defined as a property of the Number constructor itself, but then the parameter would have to be passed explicitly (like Number.toExponential(2)). That's not how the runtime was designed, however. As with so many "why?" questions about how languages and APIs work, it's ultimately just a design preference on the part of the language designers. It should be clear that something like .parseFloat() would really not make any sense as a prototype method, because the whole point of .parseFloat() is to turn something that's not a number into a number. (It could have been added to one or more other prototype objects, but again the preference of the language designers was to just make it a callable function on the Number constructor itself; that's a recent ES6 addition to the spec of course.)
Finally note that in the particular case of the Number constructor, it's pretty rare that you'd actually explicitly instantiate a number object. Generally that happens implicitly when a number primitive value is used with the . or [ ] operators as if it were an object reference. Primitives are not objects, but the language automatically wraps a primitive value in a Number object in those cases, so the first example above would work the same if it were written like this:
var n2 = 2;
alert(n2.toExponential());
The variable n2 has a plain primitive 2 in it, but that will be wrapped in a Number instance in order to allow the method call.
I do not know whether you mean a program design perspective or a language (core library) design perspective, so I'll try to answer both.
Before we begin, please forget "class" or "instance" or "static".
JavaScript is not class based.
There only object and inheritance.
Now, let's see the object diagram.
Note that new Number does not inherits Number.
Neither prototype nor constructor is an inheriting relationship.
This means number instances inherits toExponential, toFixed, etc. but does not inherits parseFloat, parseInt etc.
So you call them like Number.parseFloat() and new Number(n).toFixed().
This is how JS is designed. If you don't like it you can design your own Number library.
For example, you may create your own Number that has toFixed methods on the Number object rather than on its prototype object, like this:
var SheepyNumber = {
toFixed: ( n ) => Number.toFixed( n )
}
SheepyNumber.toFixed( 3.14159265358979323846 ) // Evaluates to '3'
Do not add toFixed to Number object. It may work for now,
But if later specifications introduces this function with any different in parameter or logic,
then your program may break when you use the standard implementation,
or a third party library may break if you keep your own implementation.
Either way, you lost.
Which leave us the question, why does JS not put toFixed to Number, like we just did, but instead put toFixed to Number.prototype?
The obvious answer is this is more object-oriented.
Since new Number has an internal value property, toFixed can take that value, instead of taking in an extra argument.
The real answer is no one knows.
JavaScript copied Java for its core API - you can find most of these methods in the Java Float class.
Some of these Java methods are instance methods (corresponds to methods on Number.prorotype), some are static (corresponds to methods on Number), but most are both - including a counterpart of toFixed.
Why JavaScript did not put isFinite or isNaN to Number.prototype?
Why did no browsers implement toFixed on Number which can co-exists with the one on Number.prototype, during the first browser war that shaped the JavaScript as we know now?
Language design is an art.
And you may not always know who is responsible or why, because it has been shaped by many hands.
I'm developing a javascript library, composed by a main object, that works as a static Class and contains various objects that do the same thing.
I am having trouble finding the best way to refer to the objects in the documentation, as i am using jGrouse and it refers to them as Classes, like:
public Class myLibrary
None of these objects and it's children will have any primitive type variables nor will have any factory pattern associated so, they are not to be reinstantiated.
I can't show you a live example, but i'll try to put here an analogous one:
var myLibrary = {};
myLibrary.methodOne = function(){ ... };
myLibrary.methodTwo = function(){ ... };
// this is a sub-library that will encapsulate methods for Array type operations
myLibrary.Array = {};
myLibrary.Array.forEach = function(array, function(item));
(...)
// this is a sub-library that will encapsulate methods for Event type operations
myLibrary.Events = {};
(...)
So, i don't think it's correct to refer to myLibrary, myLibrary.Array and myLibrary.Events as Classes, for the obvious reason that they are not meant to be instantiated.
I reject the idea to call them Static Classes as Javascript isn't design to work with static classes per se.
I think Object and Inner Object or Static Object may not be the way to go also.
I'm looking for the best way to identify them in my public documentation, as for not to confuse unexperienced programmers nor insult the more advanced developers.
Any help?
thanx
Your probably looking for the term "namespace".
You really shouldn't worry so much about the correct word. The are all far too vague and have completely separate meaning is several different meanings in JavaScript sub cultures.
The important thing to say in documentation is that "The Event has these methods".
I want to see the method signatures, I want to see a high level description of what they do and I want to see an example.
Javascript uses a prototype-based model for its objects. Nevertheless, the language is very flexible, and it is easy to write in a few lines functions which replace other kind on constructs. For instance, one can make a class function, emulating the standard class behaviour, including inheritance or private members. Or one can mimcìic functional tools by writing, for instance, a curry function which will take a function and some of its arguments and return the partially applied function.
I was wondering whether it is possible to do the reverse and imitate the prototypal method in more classical languages. In particular I have been thinking a bit whether it is possible to imitate prototypes in Python, but the lack of support for anonymous functions (more general than lambdas) leaves me stuck.
Is it possible to write some functions to mimic propotypes in class-based languages, in particular in Python?
EDIT Let me give some example of how one could go implementing such a thing (but I'm not really able to do it all).
First, the thing which most closely resembles Javascript objects is a Python dictionary. So we could have simple objects like
foo = {
'bar': 1,
'foobar': 2
}
Of course we want to add method, and this is not a problem as long as the method fits in a lambda
foo = {
'bar': 1,
'foobar': 2,
'method': lambda x: x**2
}
So now we can call for instance
foo['method'](2)
>>> 4
Now if we had arbitrary functions as methods we could go on like this. First we need the functions inside foo to have access to foo itself; otherwise they are just ordinary functions and not methods.
I guess one could do this by applying a makeObject function to foo, which loops through foo values and, whenever finds a value that is callable, modifies its __call__ attribute to pass foo as its first argument.
At this stage we would have self standing objects, which can be declared without the need of creating classes.
Then we need to be able to give foo a prototype, which can be passed as a second argument of the makeObject function. The function should modify foo.__getattr__ and foo.__setattr__ as follows: whenever the attribute is not found in foo, it should be searched in foo.prototype.
So, I think I would be able to implement this, expect for one thing: I cannot think any ways to declare methods more complicated than lambdas, except for declaring them beforehand and attaching them to my object. The problem is the lack of anonymous functions. I asked here because maybe some Python guru could find some clever way to circumvent this.
It's much easier in Python than in JS. Your JS code could be replaced with this in Python:
>>> class Foo(object):
... pass
>>> foo = Foo()
>>> foo.bar = 1
>>> foo.foobar = 2
Then you can add methods dynamically as well
>>> foo.method = lambda x: x**2
>>> foo.method(2)
4
For methods more complicated than lambdas, you declare them as functions, and they will have access to foo itself, no problems:
>>> def mymethod(self, bar, foobar):
... self.bar = bar
... self.foobar = foobar
>>> foo.mymethod = mymethod
>>> foo.mymethod(1,2)
>>> foo.bar
1
>>> foo.foobar
2
Or for that matter:
>>> mymethod(foo, 3, 4)
>>> foo.bar
3
>>> foo.foobar
4
Same thing.
So as you see, doing what your example is in Python is almost ridiculously simple. The question is why. :) I mean, this would be better:
>>> class Foo(object):
... def __init__(self, bar, foobar):
... self.bar = bar
... self.foobar = foobar
... def method(self, x):
... return x**2
Each time you read some property of Python object, method __getattribute__ is called, so you can overload it and completely control access to object's attributes. Nevertheless, for your task a bit different function - __getattr__ - may be used. In contrast to __getattribute__ it is called only if normal lookup for an attribute failed, i.e. at the same time, as prototype lookup in JavaScript starts. Here's usage:
...
def __getattr__(self, name):
if hasattr(prototype, name)
return getattr(prototype, name)
else:
raise AttributeError
Also pay attention to this question, since it has some notes on old and new style objects.
This implementation contains one important enhancement over otherwise similar implementations in other answers and on the internet: the correct inheritance of methods from the prototype. If a value obtained from the prototype is a a bound instance method -- and to cover weird corner cases the method is also actually bound to that prototype -- then the method's underlying function is extracted and a new method binding that function to the calling object is returned
import types
import inspect
class Proto(object):
def __new__(self, proto, *args, **kw):
return super(Proto, self).__new__(self, *args, **kw)
def __init__(self, proto, *args, **kw):
self.proto = proto
super(Proto, self).__init__(*args, **kw)
def __getattr__(self, name):
try:
attr = getattr(self.proto, name)
# key trick: rebind methods from the prototype to the current object
if (inspect.ismethod(attr) and attr.__self__ is self.proto):
attr = types.MethodType(attr.__func__, self)
return attr
except AttributeError:
return super(Proto, self).__getattr__(name)
This should fully implement prototypal inheritance as I understand it.
One restriction is that classes inheriting from Proto must have Proto first in their MRO because __new__ and __init__ have the prototype as the first parameter, which they drop when they delegate to super.
Here is a use example:
from prototypal import Proto
class A(Proto):
x = "This is X"
def getY(self):
return self._y
class B(Proto):
_y = "This is Y"
class C(object):
def __getattr__(self, name):
return "So you want "+name
class D(B,C):
pass
a = A(None) # a has no proto
b = B(a) # a is the proto for b
print b.x
print b.getY() # this will not work in most implementations
d = D(a) # a is the proto for d
print d.x
print d.getY()
print d.z
Here is the gist
Short version, yes but it's a bit more complicated than JS.
From Metaclass programming in Python :
>>> class ChattyType(type):
... def __new__(cls, name, bases, dct):
... print "Allocating memory for class", name
... return type.__new__(cls, name, bases, dct)
... def __init__(cls, name, bases, dct):
... print "Init'ing (configuring) class", name
... super(ChattyType, cls).__init__(name, bases, dct)
...
>>> X = ChattyType('X',(),{'foo':lambda self:'foo'})
Allocating memory for class X
Init'ing (configuring) class X
>>> X, X().foo()
(<class '__main__.X'>, 'foo')
Also check What is a metaclass in Python.
Edit : Check Prototype based OO, which is the closest thing you will get, but it will always come down to either using a lambda or just defining the function outside and adding a pointer to it to the class object.
I know this is quite old, but I though I'd add my $.02:
https://gist.github.com/4142456
The only problematic thing here is adding methods. JavaScript has a far more elegant syntax with its function literals, and it's truly hard to beat that. Lambda's don't quite cut it. So my solution was to add an awkward method method for adding methods.
Doctests are included in the gist, and it all works.
EDIT:
Updated gist to no longer use method instance method. However, we still need to define the function beforehand.
At any rate, the most important part of prototypal object model is implemented in that gist. Other things are simply syntactic sugar (would be nice to have them, but it doesn't mean prototypal object model cannot be used).
I've been doing a project at work recently focused on an almost entirely client-driven web site. Obviously Javascript is used heavily, and I've been using jQuery on top of it which has turned out to be an absolute pleasure to work with.
One of the things that has surprised me in this is how much I like the JSON object syntax and it's use within javascript (highlighted by jQuery, which uses it everywhere). for those that aren't familiar with it, consider this brief example:
function add(params) {
params.result(params.a, params.b);
}
add({
a: 1,
b: 2,
result: function(value) {
alert(value);
}
});
Of course, this example is extremely contrived but it illustrates the basic usage. The JSON describes an object on the fly, passed in this case as a parameter to the function, and even defines a function within it for use as a callback. I personally find this methodology very easy to use, understand, and produce APIs with (though I know there are those that would disagree with me.)
So my question is, is this type of syntax unique to javascript? I know that many languages have JSON parsers (and have used several) but they don't allow for this sort of inlined declaration. And granted, much of what you can do with this syntax can be duplicated via named parameters in various languages and lambda expressions or function pointers (Python jumps to mind), but I still don't find that quite as elegant.
Just curious, thanks for any replies!
The canonical example is Lisp: in Lisp, the language isn't even defined in terms of text, it is defined in terms of data structures. There really is not difference between code and data: code is just a list whose first element is interpreted as an operation and the rest as operands.
Writing a program is just writing lists.
Lua uses "tables" which are pretty much identical to javascript objects.
Syntax of JSON is very similar to Perl definition of complex structures. And your example would be:
#!/usr/bin/perl
use strict;
use warnings;
use signatures;
sub add($hash) {
$hash->{result}($hash->{a}, $hash->{b});
}
add({
a=> 1,
b=> 2,
result=> sub ($val) {
print "$val\n";
}
});
C# 3.0 has something similar in that you can both instantiate an object using a default constructor and assign properties in the same statement. It's really just a bit of syntactic sugar, but it really make it much easier than declaring multiple constructors just to handle various combinations of parameter settings. It looks like:
var myObject = new MyClass { Property1 = "value", NumericProperty = 1 };
There are also anonymous types in C# 3.0 which have a similar syntax; these are frequently used with LINQ
var query = dataContext.Entity
.Where( e => e.Kind = 1 )
.Select( e => new { e.Name, e.Kind } );
This results in an IEnumerable of a new anonymous type with properties "Name" and "Kind" which, in turn, have the same types as the corresponding entity properties.
Rubists would do:
def add(params) {
params.result(params.a, params.b)
}
add({:a=> 1, :b=> 2}) do |value|
alert(value)
end
The passing of an optional block is kind of a weird idiom in ruby. Or to be more true to your example.
def add(params) {
params.result(params.a, params.b)
}
add({
:a=> 1,
:b=> 2,
:result=> proc do |value|
alert(value)
end
})
But the concept of the inline function originates from lambda calculus and LISP.