"with" keyword in Dart - dart

Could somebody please write some formal definition of keyword with in Dart?
In official Dart examples I have only found:
class TaskElement extends LIElement with Polymer, Observable {
But I still can't understand what is it exactly doing.

The with keyword indicates the use of a "mixin". See here.
A mixin refers to the ability to add the capabilities of another class or classes to your own class, without inheriting from those classes. The methods of those classes can now be called on your class, and the code within those classes will execute. Dart does not have multiple inheritance, but the use of mixins allows you to fold in other classes to achieve code reuse while avoiding the issues that multiple inheritance would cause.
I note that you have answered some questions about Java -- in Java terms, you can think of a mixin as an interface that lets you not merely specify that a given class will contain a given method, but also provide the code for that method.

You can think mixin as Interface in Java and like protocol in Swift.Here is the simple example.
mixin Human {
String name;
int age;
void about();
}
class Doctor with Human {
String specialization;
Doctor(String doctorName, int doctorAge, String specialization) {
name = doctorName;
age = doctorAge;
this.specialization = specialization;
}
void about() {
print('$name is $age years old. He is $specialization specialist.');
}
}
void main() {
Doctor doctor = Doctor("Harish Chandra", 54, 'child');
print(doctor.name);
print(doctor.age);
doctor.about();
}
Hope it help to understand.

Related

Is it possible in Dart to accept parameters that satisfy both types at the same time?

I'm new to Dart, and I want to receive only widgets that inherit a specific interface.
In other languages, a class that satisfies two interfaces could be passed to a function.
But in Dart, I can't find a similar function or Generic even if I search, so I'm asking a question.
class TypeClassA {
}
mixin TypeMixInA {
}
class TypeClassB extends TypeClassA with TypeMixInA {
}
class TypeClassC extends TypeClassA with TypeMixInA {
}
void functionA(TypeClassA & TypeMixInA param) { // TypeClassA & TypeMixInA is possible?
}
void main() {
functionA(TypeClassB());
functionA(TypeClassC());
}
Is there a way to receive two interface (two mixins or two classes, etc.) like functionA in the example above?
No, it's not possible.
If TypeMixInA is only ever mixed-in on top of TypeClassA, then you can add implements TypeClassA on TypeMixInA and just use TypeMixInA as the argument type.
If the two are used independently, that won't fly.
Then you can introduce abstract class TypeClassAWithMixInA implements TypeMixInA, TypeClassA {} and make both TypeClassB and TypeClassC implement TypeClassAWithMixInA.
If you're not the author of TypeClassB or TypeClassC, that also won't work.
At that point, there is nothing you can do in the static type system to request only instances of classes that implement two separate interfaces.
The Dart type system does not have intersection types, which is what that would be.
You have to accept one of the types, then dynamically check that it also implements the other type, and throw at run-time if it doesn't.

Extension method on a class without a constructor in dart? [duplicate]

I'm trying to create a static extension method on one of my classes (which is autogenerated, so I can't easily modify it). According to the docs, this should be possible:
Extensions can also have static fields and static helper methods.
Yet even this small example does not compile:
extension Foo on String {
static String foo() => 'foo!';
}
void main() {
print(String.foo());
}
Error: Method not found: 'String.foo'.
print(String.foo());
^^^
What am I doing wrong?
The docs mean that the extension classes themselves can have static fields and helper methods. These won't be extensions on the extended class. That is, in your example, Foo.foo() is legal but String.foo() is not.
You currently cannot create extension methods that are static. See https://github.com/dart-lang/language/issues/723.
Note that you also might see Dart extension methods referred to as "static extension methods", but "static" there means that the extensions are applied statically (i.e., based on the object's type known at compilation-time, not its runtime type).
As James mentioned, you can't use the static method directly on the extended class as of today, the current solution to your problem would be:
extension Foo on String {
String foo() => 'foo!';
}
void main() {
print('Hi'.foo());
}

How can I require that a class has fromJson in Dart? [duplicate]

Say I have the abstract class A
abstract class A {
A.someConstructor(Foo foo);
}
and all subclasses of A should then implement such constructor:
class B extends A {
#override
B.someConstructor(Foo foo) {
// ...
}
}
So basically what I want is some kind of abstract constructors.
Is there any way of achieving this (of course the above code does not work) or do I need a normal abstract method which then creates the object and sets its properties?
EDIT: Ok so it looks like the only way to create at least a similar behaviour would be something like this:
abstract class A {
A.someConstructor(Object foo);
}
class B extends A {
B.someConstructor(Object foo) : super.someConstructor(foo) {
// ...
}
}
This isn't exactly useful, and after some thinking about my problem I realized that in fact my original goal itself is not really neccessary, so this questions is now answered.
You want to enforce a pattern on the constructors of subclasses. The Dart language has no support for doing that.
Dart has types and interfaces which can be used to restrict values and class instance members.
If a class implements an interface, then its instance members must satisfy the signatures declared by the super-interface. This restricts instance members.
If a variable has a type, for example a function type, then you can only assign values of that type to it. This restricts values. Because a class is a subtype of its interfaces, the subclass restriction means that class typed variables can be used safely (the subtype can be used as its supertype because it has a compatible interface).
There is no way to restrict static members or constructors of classes, or members of libraries, because there is no way to abstract over them. You always have to refer directly to them by their precise name, so there is no need for them to match a particular pattern.
(Which may explain why you found the goal not necessary too).
In this situation, your subclasses must call the A.someConstructor constructor, but they are free to choose the signature of their own constructors. They can do:
class B extends A {
B.someConstructor(Object foo) : super.someConstructor(foo);
}
// or
class C extends A {
C.differentName(Object foo) : super.someConstructor(foo);
}
// or even
class D extends A {
D() : super.someConstructor(new Object());
}
Constructors aren’t inherited
Subclasses don’t inherit constructors from their superclass. A
subclass that declares no constructors has only the default (no
argument, no name) constructor.
Source

How to create a static extension method in Dart?

I'm trying to create a static extension method on one of my classes (which is autogenerated, so I can't easily modify it). According to the docs, this should be possible:
Extensions can also have static fields and static helper methods.
Yet even this small example does not compile:
extension Foo on String {
static String foo() => 'foo!';
}
void main() {
print(String.foo());
}
Error: Method not found: 'String.foo'.
print(String.foo());
^^^
What am I doing wrong?
The docs mean that the extension classes themselves can have static fields and helper methods. These won't be extensions on the extended class. That is, in your example, Foo.foo() is legal but String.foo() is not.
You currently cannot create extension methods that are static. See https://github.com/dart-lang/language/issues/723.
Note that you also might see Dart extension methods referred to as "static extension methods", but "static" there means that the extensions are applied statically (i.e., based on the object's type known at compilation-time, not its runtime type).
As James mentioned, you can't use the static method directly on the extended class as of today, the current solution to your problem would be:
extension Foo on String {
String foo() => 'foo!';
}
void main() {
print('Hi'.foo());
}

PHP Dependency Injection - magic methods injections?

I'm trying to get my head around DI. Am I doing it correctly for classes that follow DI pattern?
class Boo
{
public $title = 'Mr';
public $name = 'John';
protected $deps;
public function __construct($deps)
{
$this->deps = $deps;
}
public function methodBoo()
{
return 'Boo method '.$this->deps;
}
}
class Foo
{
private $objects;
public function __construct()
{
}
// Set the inaccessible property magically.
public function __set($name, $value)
{
$this->$name = $value;
}
// Set the inaccessible $class magically.
public function __get($class)
{
if(isset($this->objects[$class]))
{
return $this->objects[$class];
}
return $this->objects[$class] = new $class($this->deps);
}
public function methodFoo()
{
return $this->Boo->methodBoo();
}
}
$Foo = new Foo();
$Foo->deps = 'says hello';
var_dump($Foo->methodFoo());
result,
string 'Boo method says hello' (length=21)
I don't want to use construction injection in some cases because not all methods in Foo rely on the same injections. For instance,methodFoo()in Foo relies on Boo only, while other methods rely on other classes/ injections.
Also, I don't want to use setter injection either because I might have to write lots of them in Foo, like
setBoo() {}
setToo() {}
setLoo() {}
... and so on...
So I thought using the magic method __get and __set could save me from ending up writing a long list of them. With this, I only 'inject' the dependency when it is needed by a method in Foo.
Is this correct way of doing it? I haven't done any test with an unit test before. Can this solution be tested?
Or any better solutions you have got?
Don't Use Magic Methods If Possible...
Don't use magic methods if possible as it can make it very difficult for yourself or anyone else to come back at a later date and understand where and how certain objects were injected (even when using a good IDE). These __set and __get magic methods are not a long term solution to your problem and will only add confusion in the long run.
As you already know you can use 'constructor' injection for setting properties and injecting objects that are 'required' during instantiation of your object.
Alternatively, if you have dependencies that are 'optional' then use setter / getter methods. That way you 'know' what objects your class uses to perform it's function.
If your class needs say 5 or more dependencies (required or optional) than perhaps your class is try to do to much. Break it down into smaller classes that require less dependencies and you will find your code not only becomes more readable / understandable but also more modular and reusable. (Separation of concerns, etc.)
Regarding testing of a class that uses magic methods, I'm sure it can be done but at much more pains than if one didn't use magic methods.
Google 'Design Patterns'. What you find and learn about design patterns will improve the way you 'join' or 'wire' your classes together.

Resources