What do you call an object level equivalent of Mixin/Traits system, is there a Pattern name for it? - language-agnostic

I previously asked about what Mixins were, and have begun to get the gist of what the pattern means. But it got me wondering if there is a common pattern name for doing something like Mixins at an Object level as opposed to the Class level.
Pseudo code (in some non existent language):
Class MyClass
{
function foo()
{
print("foo")
}
}
function bar()
{
print("bar")
}
object = MyClass.new()
object.xxxx(bar)
object.bar() #output: bar
I know stuff like this can be done in several languages, in one way or another, but I'm wondering what would be the "standard" name for the functionality xxxx represents, and what is the name for this pattern, if there is one.
Thanks!
Edit: Expanding on finnsson's answer I guess something like this might be another case of this would be:
object.xxxx(OtherClass)
object.otherfoo()
Would concatenate be appropriate?
Quote: "Concatenation: Under pure prototyping, which is also referred to as concatenative prototypes..." -wikipedia

This is common in prototype-based programming languages. I belive it's called "import" in ruby but it's some time since I last programmed ruby so I'm not sure.
In js/ruby you would write
object.bar = bar;
object.bar() // output: bar
and than it's no real pattern, since it's just an assignment (o.bar = bar) making perfect sense in a prototype-based language. I guess xxxx in your example could be called prototype or something similar (see http://en.wikipedia.org/wiki/Prototype-based_programming where a language calles this proto).

Related

Scala Play template vararg HtmlContent

I have a generic template in play 2.6, that I want to pass in a variable amount of HtmlContents. I've defined the template like this (including the implicit parameter I have in case that changes anything):
#(foo: String)(content: Html*)(implicit bar: Bar)
On the template side, this works fine-- I can dissect content with for and render it as I want. However, I haven't been able to figure out a clean way to invoke the variable arguments from the underlying template.
e.g, I have a view named "Baz":
#(something: String)(implicit bar: Bar)
In it, I try to invoke the template with multiple Html arguments. I've tried the following:
#template("fooString"){{123},{abc}}
and
#template("fooString")({123}, {abc})
and
#template("fooString"){{123}, {abc}})
And various other permutations, but inside of an enclosing bracket it seems to interpret everything literally as a single parameter in the HtmlContent vararg.
However, this ended up working as I intended, passing in multiple HtmlContents:
#template("fooString")(Html("123"), Html("abc"))
So that works, and I can use a triple-quoted interpolated string for a large Html block-- but it seems like there should be a cleaner way to do this, and the string interpolation is dangerous as it doesn't do html escaping.
Is there a way to do this using the { enclosed syntax? I'd like to understand more what is actually happening on an underlying level, and how play parses and generates HtmlContent in brackets.
So consider you have below template
// main.scala.html
#(title: String)(contents: Html*)
There are different ways you can call this template
Option #1
This is what you already posted in the question
#main("This is a title")(Html("abc"), Html("123"))
Options #2
#html1 = {
Hello
}
#html2 = {
<div>Tarun</div>
}
#main("This is a title")(html1, html2)
Option #3
#main("This is a title")(Html(<div>Tarun
</div>.toString), Html(<div>
Lalwani
</div>.toString))
Options #4
This is not exactly same option, but needs change in Template signature itself
#(title: String)(contents: List[String])
And then calling it like below
#main("This is a title")(List(
"""<div>
Tarun
</div>
""", """Hello"""))
Option #5
This requires code files and was already answered on another SO thread
Paul Draper's answer on Why doesn't this pass multiple HTML parameters to template

OCaml dynamic function name

I have a list of tags:
let tags = ["div", "h1", "p"]
Can I generate a module which contains functions with those tags as names?
/* don't mind the syntax, it's Facebook's Reason (new interface to ocaml) */
let module DOM = {
let div props children => Js.Unsafe.fun_call
(Js.Unsafe.get dom (Js.string "div")) [|Js.Unsafe.inject props, Js.Unsafe.inject children|];
let h1 props children => Js.Unsafe.fun_call
(Js.Unsafe.get dom (Js.string "h1")) [|Js.Unsafe.inject props, Js.Unsafe.inject children|];
let p props children => Js.Unsafe.fun_call
(Js.Unsafe.get dom (Js.string "p")) [|Js.Unsafe.inject props, Js.Unsafe.inject children|];
}
The tag name should become a function in the module...
Is this possible?
Assuming what you want to do is to build a module with names from a string list while program execution,
Short answer: No, OCaml is a static typed language and you cannot build a new variable name while program execution.
Longer answer: you could use meta-programming: build a source code with names your want then compile it and dynamically link the compiled module. But this is not a regular way of using OCaml at all. In addition, looking at your environment, OCaml (or Reason) to output Js code, you likely need to have an OCaml (or Reason) compiler compiled to Js, which is hard and should be avoided.
Conclusion: No, you cannot.

Assign super to variable in AS3

I have this:
public class Base {
public function whoAmI() {
trace("base");
}
}
public class Extended extends Base {
public function Extended() {
this.whoAmI() //prints extended
super.whoAmI() //prints base
var test = super;
test.whoAmI() //prints extended
}
public override function whoAmI() {
trace("extended");
}
}
The problem is when I do var test = super, it seems like this is assigned to test instead of super.
Is it possible to do the assignment so that test.whoAmI() prints "base"?
Edit: In the comments it is being said that using super in the way I propose would break overriding. I don't think that's the case. The way I am thinking of it, super could be used the same way as this. I understand that is not the way super is implemented, but using it that way would not break overriding as people are claiming. So for example the same way this is possible:
var test = this;
test.whoAmI();
This should be possible:
var test = super;
super.whoAmI();
It is obviously the choice of the language implementer to not do things this way, and I don't understand the reason why. It doesn't break things, but I guess it does make them more complicated.
I am not suggesting type-casting this to the super class. Obviously that wouldn't work.
You are thinking of "this" and "super" as 2 different instances, 2 different things but they in fact point to the same object (obviously) so at the end it's always "this". Using super is just a special keyword that allows the instance to point to the overrided definitions up the inheritance chain, it does not point to a different object. So "super" does correctly its job, it points to the instance and allow you each time you use it to access overrided definitions and that's it. There's of course no point on trying to store that keyword in a variable since in that case it just return correctly the instance it points to which is always "this".
It's simply a case of misunderstood inheritance principle and I've seen it before, super is mistaken for some kind of instance wrapper up the inheriatnce chain around the object "this" while it's in fact and always the same object.
No, this is not possible.
If this were possible, then overriding methods wouldn't be possible!
For example, take this function...
public function test(a:Object):void {
trace(a.toString());
}
You'd only get [object Object] back if your idea was how things worked.
Ok I understand what you mean your question is more about language definition and specification.
Look at this exemple in c# that explain how you can manage more precisely overriding in c# :
http://www.dotnet-tricks.com/Tutorial/csharp/U33Y020413-Understanding-virtual,-override-and-new-keyword-in-C
But
let's explain a litlle how it's work.
when you extend a class, it's like if you create an object composed of all the object in the inheritance tree so if B extends A and C extends B you have two objects like this:
(B+A) and (C+B+A) with hierarchy between each other B->A and C->B->A. Super is just a way to ascend in the hierachy.
When you cast a C in A for example. In memory you always have an object (C+B+A) but interpreted as A. When you override you just say that a method in child has an higher priority than in parent.
You can try downcasting this manually to any of your class's predecessors. The pointer will still be equal to this but the methods called will use the class table of the class used to downcast.
public class Extended extends Base {
public function Extended() {
this.whoAmI() //prints extended
super.whoAmI() //prints base
var test:Base = this;
test.whoAmI() //should print base
}
public override function whoAmI() {
trace("extended");
}
}
Should your Base extend something, which methods are known or the superclass is dynamic, and there is code that adds methods to prototype of a class, you might use such a downcast to call a superclass's method that might not be there at compile time, but make sure you first call hasOwnProperty in case of a dynamic class to determine whether a method or property exists.

How to use contents = to add to a Scala Panel?

Sorry this must be a very silly question.. but everywhere I've been seeing Scala code examples where you just do
contents+= on a BoxPanel or some layout Panel. I figured because they have contents as mutable.buffer so you can just add and remove components.
But how do you add a component to Scala Panel? It accepts a seq so do you have to give it a list or something? I know you can just call peer.add but I want to see how Scala code does it. :)
For example contents = new Button {} isn't working.
Sorry for this simple question I'm very new to Scala..
EDIT:
Thanks for the replies. My question now though becomes.. can you ever just have a class extending Panel? Would you be able to set contents for it at all? Or is it never done and everyone always just uses the Panels associated with a layout manager?
The Panel class itself is abstract, meaning it can't be instantiated directly, and is intended as a "base" for concrete implementations of panels.
It doesn't seem to have a "common" method for adding components probably because each subclass implements its own, sometimes mutually incompatible custom one:
BoxPanel, as you've noted, has a settable Buffer,
FlowPanel seems to mandate adding components as constructor arguments,
GridBagLayout and some others implement addition via the layout Map,
etc.
As you might see from the above examples, it would be hard to specify what a general "add" method would mean in all of those cases.
EDIT in response: of course you can, there's nothing stopping you from subclassing a Panel yourself and override the contents method, e.g.:
val myPanel = new Panel() {
private val myContents = (new Content += new Button())
override def contents = myContents
}
You can also use Panel as a type parameter for your methods that process panels in a general way, etc. It's just that you can't have an instance that's just a Panel, because, again, the class is abstract, so you can't instantiate it.
Note that this is not unique to Scala, if JPanel was abstract in Java (like Component is) the outcome would be the same.
I want to see how Scala code does it.
https://github.com/scala/scala-swing/blob/v1.0.0-RC2/src/main/scala/scala/swing/Container.scala#L35
I, too, practiced on some Swing code when I first learned some Scala.
Here is a Panel component that renders itself as a simple game grid:
https://github.com/som-snytt/House-of-Mirrors-Fork/blob/act/src/main/scala/hom/LightBox.scala#L286
To see how the Scala and Swing pieces fit together, see SuperMixin:
https://github.com/scala/scala-swing/blob/v1.0.0-RC2/src/main/scala/scala/swing/Component.scala#L51
Assembly:
https://github.com/som-snytt/House-of-Mirrors-Fork/blob/act/src/main/scala/hom/HouseOfMirrors.scala#L18
This is what you asked about directly:
https://github.com/som-snytt/House-of-Mirrors-Fork/blob/act/src/main/scala/hom/HouseOfMirrors.scala#L45
If you have a button:
val button=new Button{
text="Click me!"
}
or
val label=new Label{
text="Look, i'm a label!"
}
or
object myField extends TextField{ columns=2 }
then you just use:
contents=new BoxPanel(Orientation.Vertical){
contents+=button
border=Swing.EmptyBorder(10,20,10,20)
}
or in a more simpler form:
contents=new FlowPanel(){
contents+=new Label("This is my button:")
contents+=new Button("Click me!")
border=Swing.EmptyBorder(10,20,10,20)
}

Naming member functions/methods with a single underscore, good style or bad?

In some languages where you cannot override the () operator, I have seen methods with a single underscore, usually for 'helper' classes. Something likes this:
class D10
{
public function _()
{
return rand(1,10);
}
}
Is it better to have the function called Roll()? Is a underscore fine? After all, there is only one function, and it removes the need to look up the name of the class.
Any thoughts?
I would say it is a bad style. You can not infer behaviour from the name of the function if it simply an underscore.
In order to know what it does you need to read the code, or documentation.
(On a side note, I don't think D10 is a good name for a class either).
I guess it's a matter of taste. But I don't like it.
I believe having full self-explanatory names is always a better practice.
You won't save much time using only one keystroke to call your function but you'll likely loose more time remembering what it does afterwards.
But again, it is very subjective.
It may be legal, and whoever you're working with might not mind (even more so if you're working alone) but if it were me it would make me crazy. Spelling out D10.roll() doesn't take up much of your time, and it makes your code that much easier to follow since the name is self-explanatory.
The bottom line, though, is that elegance is in the eye of the beholder; if everyone who's working on your code agrees that that's a simple and clear identifier, nobody is going to stop you.
To me, this is quite obviously bad style.
Method names are names, and are supposed to be descriptive. They're not "proper names" like you have for people*, places and so on, they're names that describe the actions taken by the code contained within.
* Although of course many names for people were almost literally descriptive originally, but that's not generally the indended use nowadays.
I don't think the structure is optimal to begin with. I would simply do this:
class Dice
{
public int D10()
{
return rand(1,10);
}
public int D6()
{
return rand(1,6);
}
// And so on...
}
Then it will be made clear that we're actually taking about dice here and we don't have to create one class for every possible dice.
If you really need to abstract away what dice you're using, I hope that you're using a language that handle functions as first class objects, in which case you would do this:
void RussianRoulette(SOMEFUNCTIONSIGNATURE dice)
{
if (dice() == 1)
print "BANG";
else
print "click";
}
RussionRoulette(Dice.D6); // Regular russian roulette
RussionRoulette(Dice.D100); // For the faint of heart
RussionRoulette(Dice.D1); // Die! :)