How does Raku deal with the diamond problem (multiple inheritance)? - multiple-inheritance

So it's no secret that Raku has multiple inheritance, so that got me wondering: "how does Raku deal with that in any reasonable manner?"
Some preliminary testing reveals that default behaviour is inherited from the first class in the inheritance list, that's fine, many other languages do it like that too
class A {
has $.foo = 0;
method speak {...}
}
class B is A {
has $.foo = 1;
method speak {
say 'moo';
}
}
class C is A {
has $.foo = 2;
method speak {
say 'baa';
}
}
class D is B is C {}
class E is C is B {}
say D.new.foo; # prints 1 (from B)
say E.new.foo; # prints 2 (from C)
But that got me wondering, what if I want D to use C's speak?
Due to the inheritance order I get B's by default.
I understand that roles exist to solve this exact issue by facilitating a disambiguation mechanism, but suppose hypothetically I find myself in a situation where I don't have roles at my disposal (boss hates them, inherited a library that doesn't have them, pick your excuse) and really need to disambiguate the inherited classes.
What's the mechanism for dealing with that in Raku?

Generally you would need to provide a tie-breaker method in the class that has the (potential) ambiguity. Fortunately, you do not have to create separate methods, as you can call specific versions of methods in a call.
So the answer to your question: Add a method speak to class D, and have that call the speak method from class C:
class D {
...
method speak { self.C::speak }
}
And for methods taking parameters, take a Capture of all parameters, and pass that on:
class D {
...
method foo(|c) { self.C::foo(|c) }
}
Note that the "c" in |c is just an identifier, it could be any identifier. But it is sorta customary, at least with Raku core developers, to just use |c, with the "c" standing for "capture".
Now, this will cause some overhead, as you would have an extra level of indirection. Should this turn out to be a performance issue, there's some meta-programming you can do to alias the speak method in D to the speak method in C:
class D {
...
BEGIN D.^add_method("speak",C.^find_method("speak"));
}
This will, at compile time because of the BEGIN, add a Method object to the D class called speak that is defined by the speak method of class C. Since this is an alias, you don't have to worry about any parameters being passed.

Related

How to analyze a complex class axiom using OWL API

I read the OWL API documentation, most of the examples are about create class axioms and add them to the ontology. Now, I need to retrieve the restriction of a class, and extract the elements in the restriction.
For example, in the pizza.owl, ChessePizza class is defined by the restriction: "Pizza and (hasTopping some CheeseTopping)". I can use the "getEquivalentClassesAxioms" function to get the whole axiom. But I want to know the details of this axiom, such as the object properties (hasTopping) and classes (CheeseTopping) used in this axiom. Is there any method to extract the elements of a axiom?
The best approach to, for example, extract the property for all existential restrictions, is to write an OWLObjectVisitor.
In a visitor, you implement a visit(OWL... o) for each class that the visitor knows about. For an axiom that defines A equivalentTo p some Q, the visitor would look something like:
OWLObjectVisitor v = new OWLObjectVisitor() {
public void visit(OWLEquivalentClassesAxiom ax) {
// this is an example of recursive visit
ax.classExpressions().forEach(c->c.accept(v));
}
public void visit(OWLObjectSomeValuesFrom ce) {
OWLObjectPropertyExpression p = ce.getProperty();
// here you can do what you need with the property.
}
};
axiom.accept(v);

Swift - Array with specific class type

How can i create array which will hold objects belonging a specific class.
class BaseObject {}
class Derived1: BaseObject {}
class Derived2: BaseObject {}
class Derived2: BaseObject {}
I need to create array in which will hold only Object derived from BaseObject
Something like - var array : [BaseObject.Type] = []
Is there a way to specify this ?
Also, I should be able to use it something like this
if let derived1 = object as? [Derived1] {
}
else if let derived2 = object as? [Derived2] {
}
You can obviously define your array as an array of BaseObject:
var objects: [BaseObject] = [] // or `var objects = [BaseObject]()`
But it's going to let you create a heterogenous collection (of either BaseObject or Derived1 or Derived2 or of any other subclass). That's a core OO design concept (the Liskov substitution principle) that any subclass of BaseObject should (and will) be permitted.
If all you want is to say that you can only have an array of one of the subtypes, you can obviously just define your array as such, e.g.:
var objects: [Derived1] = []
That will obviously allow only Derived1 objects (and any subclasses of Derived1.
90% of the time, the above is sufficient. But in some cases, you might needs some collection with methods that require some inherited base behavior, but for which you don't want to allow heterogenous collections. In this case, I might consider a more protocol-oriented pattern:
Bottom line, should we be subclassing, or should we be using a protocol-oriented approach? I.e. is BaseObject actually something you'll instantiate for its own purposes, or is it there merely to define some common behavior of the subclasses. If the latter, a protocol might be a better pattern, e.g.:
protocol Fooable {
func foo()
}
// if you want, provide some default implementation for `foo` in an
// protocol extension
extension Fooable {
func foo() {
// does something unique to objects that conform to this protocol
}
}
struct Object1: Fooable {}
struct Object2: Fooable {}
struct Object3: Fooable {}
This yields the sort of behavior that you may have been using in your more OO approach, but using protocols. Specifically, you write one foo method that all of the types that conform to this protocol, e.g., Object1, Object2, etc., can use without having to implement foo themselves (unless, of course, you want to because they need special behavior for some reason).
Because this eliminates the subclassing, this then opens the door for the use of generics and protocols that dictate some generalized behavior while dictating the homogenous nature of the members. For example:
struct FooCollection<T: Fooable> {
private var array = [T]()
mutating func append(_ object: T) {
array.append(object)
}
// and let's assume you need some method for your collection that
// performs some `Fooable` task for each instance
func fooAll() {
array.forEach { $0.foo() }
}
}
This is a generic which is a homogenous collection of objects that conform to your protocol. For example, when you go to use it, you'd declare a particular type of Fooable type to use:
var foo = FooCollection<Object1>()
foo.append(Object1()) // permitted
foo.append(Object2()) // not permitted
foo.fooAll()
Now, I only went down this road because in comments elsewhere, you were inquiring about generics. I'd personally only go down this road if the (a) collection really needed to be homogenous; and (b) the collection also wanted to implement some shared logic common to the protocol. Otherwise, I'd probably just stick with a simple [Derived1] (or [Object1]). The above can be powerful when needed, but is overkill for simpler situations.
For more discussion about protocol oriented programming, the homogenous vs heterogenous behavior, traditional stumbling blocks when you're coming from a traditional OO mindset, I'd refer you to the WWDC 2015 video, Protocol-Oriented Programming in Swift, or it's 2016 companion video that builds upon the 2015 video.
Finally, if you have any additional questions, I'd suggest you edit your question providing details on a practical problem that you're trying to solve with this pattern. Discussions in the abstract are often not fruitful. But if you tell us what the actual problem you're trying to solve with the pattern in your question, it will be a far more constructive conversation.

Qi4J Concerns partial implementation

is is possible to do end up with something like this:
ServiceChild (class) extends (or only partial implements) Service and overrides sayHello
Service (interface) implements hello,goodbye
Hello (has a mixin HelloMixin) has method sayHello
Goodbye (has a mixin GoodbyeMixin) has method sayGoodbye
I've tried doing the above using the concern approach in ServiceChild
public class ServiceChild extends ConcernOf<Service> implements Hello
{
#Override
public String sayHello() {
return "Rulle Pharfar";
}
}
However using this approach only the Hello implementation are detected by java and not the rest of the stuff from the Service class. So is there any other approach that would work?
I'm not sure I understand what you are trying to do, but a concern should more be seen as a wrapper around the original implementation of the class it is a concern of.
As the documentation states:
A concern is a stateless Fragment, shared between invocations, that acts as an interceptor of the call to the Mixin.
And would usually do this:
//Given interface MyStuff
#Mixins( MyStuff.Mixin.class )
#Concerns( MyStuffConcern.class )
public interface MyStuff
{
public void doStuff();
abstract class Mixin implements MyStuff
{
public void doStuff()
{
System.out.println( "Doing original stuff." );
}
}
}
public class MyStuffConcern extends ConcernOf<MyStuff>
implements MyStuff
{
public void doStuff()
{
// if I want to do anything before going down the call chain I'll do it here
System.out.println( "Doing stuff before original." );
// calling the next concern or actual implementation
next.doStuff();
// anything to do after calling down the call chain - here is the place for it
System.out.println( "Doing stuff after original." );
}
}
But nevertheless if you have a concern on a interface you should also implement said interface:
public abstract class ServiceChild extends ConcernOf<Service> implements Service
{
public String sayHello()
{
return "Rulle Pharfar";
}
}
Hope this helped.
I also don't fully understand the question.
As Arvice says, Concerns are the equivalent of around-advice in AOP, with much more precise pointcut semantics. Although it is technically correct that a concern 'wraps' the underlying concerns/mixins, I prefer to not thinking of it as a 'wrapper' but an 'interceptor'. It is the incoming call that is handled. Conceptually slightly different, and it may not work for everyone.
It is also possible that both Concerns (stateless) and Mixins (stateful) implements only a subset of the methods in the interface they override, simply by making the class 'abstract'. Qi4j will fill in the missing (and unused) method calls. And any combination may be used.
Further, well implemented concerns should call the 'next', because they should be unaware of their actual uses. If the concerns are expected to take care of the method call. There must be a Mixin for each composite type method, or assembly will fail.
So in short;
1. A Mixin implementation may implement zero (a.k.a private mixins), one or more methods of the composite type interface.
2. A Concern may implement one or more methods of the composite type interface.
It is also interesting to note that when a class (mixin or concern) calls one of its own methods that are in the composite type interface, the call will not be intra-class, but call the composite from the outside, so the entire call stack is invoked, to ensure that an internal call and an external call are identical in results. Patterns exists if this needs to be bypassed.

Is there a #visibility package concept in PHPDoc / PHPStorm?

I have a domain model written in PHP, and some of my classes (entities inside an aggregate) have public methods, which should never be called from outside the aggregate.
PHP does not have the package visibility concept, so I'm wondering if there is some kind of standardized way to define #package and #visibility package in the docblocks, and to have a static analysis tool that would report violations of the visibility scope.
I'm currently trying out PHPStorm, which I've found very good so far, so I'm wondering if this software has support for this feature; if not, do you know any static code analysis tool that would?
The closest parallel to this line of thinking that I see in PHP's capability is using "protected" scope rather than public for these kinds of methods. Granted, that requires using inheritance to grant access to the protected items. In my years of managing phpDocumentor, I've never encountered anything else that attempts to mimic that kind of "package scope" that I remember from my Java days.
If the entities within your aggregate root should not be modifiable without going through the aggregate root, then the only means you have to control that is making the entity a private or protected member so that all modifications to the entity have to go through the aggregate.
class RootEntity {
private $_otherEntity;
public function DoSomething() {
$this->_otherEntity->DoSomething();
}
public function setOtherEntity( OtherEntity $entity ) {
$this->_otherEntity = $entity;
}
}
Someone can still always do:
$otherEntity = new OtherEntity();
$otherEntity->DoSomethingElse();
$rootEntity->setOtherEntity($otherEntity);
Though, I guess you could use the magic __call() method to prohibit setting of the _otherEntity anywhere except during construction. This falls under total hack category :)
class RootEntity {
private $_otherEntity;
private $_isLoaded = false;
public function __call( $method, $args ) {
$factoryMethod = 'FactoryOnly_'.$method;
if( !$this->_isLoaded && method_exists($this,$factoryMethod) {
call_user_func_array(array($this,$factoryMethod),$args
}
}
public function IsLoaded() {
$this->_isLoaded = true;
}
protected function FactoryOnly_setOtherEntity( OtherEntity $otherEntity ) {
$this->_otherEntity = $otherEntity;
}
}
So, from there, when you build the object, you can call $agg->setOtherEntity($otherEntity) from your factory or repository. Then when you are done building the object, call IsLoaded(). From there, nobody else will be able to introduce a new OtherEntity into the class and will have to use the publicly available methods on your aggregate.
I'm not sure if you can call that a "good" answer, but it's the only thing I could think of to truly limit access to an entity within an aggregate.
[EDIT]: Also, forgot to mention...the closest for documentation is that there is an #internal for phpdoc:
http://www.phpdoc.org/docs/latest/for-users/tags/internal.html
I doubt that it will modify the IDE's code completion, however. Though, you could probably make a public function/property but label it as "#access private" with phpdoc to keep it from being in code completion.
So far, PHPStorm does not seem to provide this feature.

Creating New Array with Class Object in GWT

I would like to create a new array with a given type from a class object in GWT.
What I mean is I would like to emulate the functionality of
java.lang.reflect.Array.newInstance(Class<?> componentClass, int size)
The reason I need this to occur is that I have a library which occasionally needs to do the following:
Class<?> cls = array.getClass();
Class<?> cmp = cls.getComponentType();
This works if I pass it an array class normally, but I can't dynamically create a new array from some arbitrary component type.
I am well aware of GWT's lack of reflection; I understand this. However, this seems feasible even given GWT's limited reflection. The reason I believe this is that in the implementation, there exists an inaccessible static method for creating a class object for an array.
Similarly, I understand the array methods to just be type-safe wrappers around JavaScript arrays, and so should be easily hackable, even if JSNI is required.
In reality, the more important thing would be getting the class object, I can work around not being able to make new arrays.
If you are cool with creating a seed array of the correct type, you can use jsni along with some knowledge of super-super-source to create arrays WITHOUT copying through ArrayList (I avoid java.util overhead like the plague):
public static native <T> T[] newArray(T[] seed, int length)
/*-{
return #com.google.gwt.lang.Array::createFrom([Ljava/lang/Object;I)(seed, length);
}-*/;
Where seed is a zero-length array of the correct type you want, and length is the length you want (although, in production mode, arrays don't really have upper bounds, it makes the [].length field work correctly).
The com.google.gwt.lang package is a set of core utilities used in the compiler for base emulation, and can be found in gwt-dev!com/google/gwt/dev/jjs/intrinsic/com/google/gwt/lang.
You can only use these classes through jsni calls, and only in production gwt code (use if GWT.isProdMode()). In general, if you only access the com.google.gwt.lang classes in super-source code, you are guaranteed to never leak references to classes that only exist in compiled javascript.
if (GWT.isProdMode()){
return newArray(seed, length);
}else{
return Array.newInstance(seed.getComponentType(), length);
}
Note, you'll probably need to super-source the java.lang.reflect.Array class to avoid gwt compiler error, which suggests you'll want to put your native helper method there. However, I can't help you more than this, as it would overstep the bounds of my work contract.
The way that I did a similar thing was to pass an empty, 0 length array to the constructor of the object that will want to create the array from.
public class Foo extends Bar<Baz> {
public Foo()
{
super(new Baz[0]);
}
...
}
Baz:
public abstract class Baz<T>
{
private T[] emptyArray;
public Baz(T[] emptyArray)
{
this.emptyArray = emptyArray;
}
...
}
In this case the Bar class can't directly create new T[10], but we can do this:
ArrayList<T> al = new ArrayList<T>();
// add the items you want etc
T[] theArray = al.toArray(emptyArray);
And you get your array in a typesafe way (otherwise in your call super(new Baz[0]); will cause a compiler error).
I had to do something similar, I found it was possible using the Guava library's ObjectArrays class. Instead of the class object it requires a reference to an existing array.
T[] newArray = ObjectArrays.newArray(oldArray, oldArray.length);
For implementing an array concatenation method, I also stepped into the issue of missing Array.newInstance-method.
It's still not implemented, but if you have an existing array you can use
Arrays.copyOf(T[] original, int newLength)
instead.

Resources