I want to declare, but not define a factory constructor in an abstract class.
In my case, I want to create a method that accepts any class that implements a String toJson() method as well as a fromJson(Map<String, dynamic> data) factory constructor.
Is there any way to achieve that in Dart?
I'm looking for something like the following, which is not valid Dart code:
abstract class JsonSerializable {
factory fromJson(Map<String, dynamic> data);
String toJson();
}
I'm afraid that it doesn't work the way you want it to.
Constructors are not part of an interface. They act more like static members.
So, you can't add a factory to the interface, and code wouldn't have any way to call the factory constructor given a type variable extending this type anyway.
So, since constructors cannot be part of interfaces, constructors also cannot be abstract. Being abstract simply means "make the member part of the interface, but no implementation is added to class".
You can declare the factory as a normal method, but then you would only be able to call it when you already have an instance, which likely isn't what you want with a constructor.
The only way to pass code around is as functions or objects with methods. So, if you want to parameterize something by a type which is JsonSerializable, and you want to be able to create such an object, you need to pass a factory function along:
T deserialize<T extends JsonSerializable>(
String json,
T factory(Map<String, dynamic> data),
) {
return factory(jsonDecode(json) as Map<String, dynamic>);
}
You an then call it with:
var myValue = deserialize(jsonString, (x) => MyClass.fromJson(x));
(If MyClass.fromJson had been a static function instead of a constructor, you could just write deserialize(jsonString, MyClass.fromJson), but Dart doesn't yet have constructor tear-offs).
As suggested in the accepted answer, I ended up creating a Serializer<T> type that got implemented by a serializer for each class:
Turns out, this has several benefits over just having toJson/fromJson on the classes directly:
It decouples the serialization logic from the actual classes. That means better code readability because classes only contain methods that relate directly to the class — serializers can even be put into their own files.
Currently, extensions can't create constructors. So having serializers separately makes it possible to write serializers for existing classes, like String or Flutter's Color, where you can't just add a fromColor constructor.
Both these points combined mean it also works well with code generation — the classes are hand-written and the serializer can be generated in a separate file.
Code example:
class Fruit {
Fruit(this.name, this.color);
final String name;
final String color;
}
// in another file
class FruitSerializer extends Serializer<Fruit> {
Map<String, dynamic> toJson(Fruit fruit) {
return ...;
}
Fruit fromJson(Map<String, dynamic> data) {
return Fruit(...);
}
}
An then also pass the serializer to the code that needs it:
someMethod<T>(Serializer<T> serializer, T value) {
...
}
someMethod(FruitSerializer(), someFruit);
final fruit = recreateFruit(FruitSerializer());
Obviously, you can't pass an object that can't be serialized to the code, because the method expects a Serializer<T>.
Related
I was trying to write something with the following design pattern:
void main()
{
document.registerElement('abs-test', Test);
TestExtend test = new TestExtend();
document.body.append(test);
}
abstract class Test extends HtmlElement
{
Test.created() : super.created();
factory Test() => new Element.tag('abs-test')..text = "test";
}
class RedTest extends Test
{
TestExtend() : super() => style.color = 'red';
}
My aim with this is to create a custom HtmlElement registered to the abstract class "Test". This abstract class "Test" would have some properties that all elements of type Test need to have. In this example, all elements of type Test need to have the word "test" as their text.
However, I wanted then to only allow the user to create subclasses of "Test" with more specific properties. In this example we have RedTest which then sets the color of Test to red. The resulting HTML would be:
<abs-test style="color:red;">test</abs-test>
I have 2 problems with this:
1) Is it possible to call the factory constructor of a parent class? (If not, is it possible to extend HtmlElement in a different way that doesn't require a factory constructor)
2) Is it possible to extends HtmlElement with an abstract class?
I have been testing for a while with different constructors but am unable to make it work. Can anyone advice?
You register a tag with a class so that the browser can instantiate it for you. If this isn't an 1:1 relation, there is no way for the browser to know what class to instantiate.
Therefore
You need
a different tag for each class
register each tag with a concrete (non-abstract) class
You normally can call the constructor of a subclass in a factory constructor of an abstract class
factory Test() => new RedTest()..text = "test";
is valid in Dart, but because extending an element requires to return
new Element.tag('abs-test')
this won't work, because you can't return both at the same time.
You need to register each concrete subclass with a different tag like
document.registerElement('abs-test-red', TestRed);
document.registerElement('abs-test-blue', TestBlue);
Say I have two JdbcTemplates, one for "employee_database" and one for "customer_database". Say a class EmployeeDAO requires the former as a constructor dependency, and CustomerDAO requires the latter. If I were writing these classes myself, I'd do
public class EmployeeDAO {
public EmployeeDAO(#Named("employee") JdbcTemplate employeeJdbcTemplate)
and
bind(JdbcTemplate.class).annotatedWith(Names.named("employee")).toInstance(employeeJdbcTemplateInstance);
And likewise for CustomerDAO
But I can't modify EmployeeDAO to add the Named annotation to the constructor parameters.
What's the canonical way to insure the DAO objects get their respective JdbcTemplates in this scenario without having to instantiate them myself?
In a sense, this is similar to the "robot legs problem", as you're trying to create similar-but-slightly-different trees of objects. In the eponymous problem, you're using a reusable Leg object that receives a #Left Foot and a #Right Foot as needed; in this problem, you're similarly varying the binding of an inner object (JdbcTemplate) based on an outer object's (DAO's) context.
A "cheap way" is to use #Provides methods, which is a particularly low-cost solution if your consumer DAOs have few dependencies and are unlikely to change frequently. Naturally, creating a full Provider would also work too, but this syntax works just fine for most cases.
public class YourModule extends AbstractModule {
#Override public void configure() {}
#Provides EmployeeDao createEmployeeDao( // Name doesn't matter.
#Named("employeeJdbcTemplate") JdbcTemplate employeeTemplate,
Dep2 dep2,
Provider<Dep3> dep3Provider) {
return new EmployeeDao(employeeTemplate, dep2, dep3Provider);
}
}
If the dep list is long, deps change frequently, or multiple classes depend on a JdbcTemplate, then private modules may be the way to go.
install(new PrivateModule() {
#Override public void configure() {
bind(JdbcTemplate.class).toInstance(employeeJdbcTemplate);
expose(EmployeeDao.class);
}
});
The example above uses an anonymous inner class, but you could also create a named class (either top-level or nested) that accepts a JdbcTemplate instance and a DAO class literal, and call it like so:
install(new DaoModule(employeeTemplate, EmployeeDao.class));
install(new DaoModule(customerTemplate, CustomerDao.class));
Can someone explain me the difference between both interfaces InputFilterAwareInterface and InputFilterProviderInterface? Both seem to serve to the same purpose, to get an InputFilter, but I know they cannot be the same... And when do they get called?
Thanks
Both interfaces exist for different purposes. The InputFilterAwareInterface guarantees that implemented classes will have a setInputFilter() and getInputFilter() methods which accept and return an InputFilter instance when necessary. On the other hand, the InputFilterProviderInterface guarantees only that implemented classes will have a getInputFilterSpecification() method which returns a filter specification (configuration array) which is ready to use as argument in various input factories.
For example; the snippet below came from Zend\Form\Form.php class:
if ($fieldset === $this && $fieldset instanceof InputFilterProviderInterface) {
foreach ($fieldset->getInputFilterSpecification() as $name => $spec) {
$input = $inputFactory->createInput($spec);
$inputFilter->add($input, $name);
}
}
As you can see, the Form class creates inputs and binds them to related filter using given specification which is returned by getInputFilterSpecification() method of the implementing class ($fieldset int this case).
Using Traits
Zend Framework 2 also provides lot of traits for commonly used interfaces. For example InputFilterAwareTrait for InputFilterInterface. This means, you can easily implement that interface if you have PHP >= 5.4
namespace MyNamespace;
use Zend\InputFilter\InputFilterInterface;
MyClass implements InputFilterInterface {
// Here is the trait which provides set and getInputFilter methods
// with a protected $inputFilter attribute to all MyClass instances.
use \Zend\InputFilter\InputFilterAwareTrait;
// Your other methods.
...
}
Now anywhere in your code, you can do this:
$myClass->setInputFilter($AnInputFilterInstance);
$myClass->getInputFilter(); // Returns an inputfilter instance.
As you can imagine, no trait exists for InputFilterProviderInterface because its responsibility is only returning a valid config spec. It doesn't deal with any instance or class attribute like is forced in InputFilterInterface.
Total Guice noob here, have read a few articles and seen the intro video, that's about it.
Here's my simplified old code that I'm trying to "guicifiy". Can't quite figure out how to, since (as far as I understand), I can only #inject-annotate one of the two constructors? How can a calling class create the one or the other instance? Or will I have to refactor this somehow?
public class MyDialog extends JDialog {
public MyDialog( JFrame parent, <other parameters...> ) {
super( parent );
}
public MyDialog( JDialog parent, <other parameters...>) {
super( parent );
}
}
You can only inject into the one ctor.
Depending on how this class is being used, you could:
Inject a factory into the client code with two "new" methods.
Roll all the arguments into one ctor and pass null when not required.
How can a calling class create the one or the other instance?
This suggests that the calling classes will want multiple instances of MyDialog? Then you need to use a hand-rolled factory (Assisted Inject can handle this for you if you only had one ctor). I don't know the details of what you are up to and I'm likely repeating what you already know but as a blanked statement I'd suggest also extracting an interface from MyDialog and have the factory return them. This way you can fake MyDialog in tests.
Constructor injection is very clean. mlk is right, saying that you can inject into one constructor only.
What you can do is use method injection:
public class Smt {
private int a;
private Cereal cereal;
private Personality personality;
private ignition;
public Smt() {
this.a = 5;
}
public Smt(int a) {
this.a = a;
}
#Inject
public void setup(#CiniMini Cereal cereal, #Rastafarian Personality personality,
Ignition ignition) {
this.cereal = cereal;
this.personality = personality;
this.ignition = ignition;
}
}
What Guice will do is call your class' setup class method and provide all the injections. Then you do the same thing as in the constructor--assign the objects to your class' attributes.
I agree with the previous comments.
Just an additional hint: constructor injection is supposed to provide all dependencies a class needs. As mlk says, one approach could be to annotate the constructor with most arguments and then refactor the other one to call the former by passing null values where needed.
Additionally, Guice 3.0 supports the so called Constructor Bindings which allow the programmer to specify which constructor to use. See here for more details.
I understand how the implementation of dynamic binding works and also the difference between static and dynamic binding, I am just having trouble wrapping my brain around the definition of dynamic binding. Basically other than it is a run-time binding type.
Basically, dynamic binding means that the address for a function call is not hard-coded into the code segment of your program when it's translated into assembly language, and is instead obtained from elsewhere, i.e. stack variables, array lookups, etc.
At a higher level, if you have a line of code:
foo(bar) //Calls a funciton
If it can be known at compile time exactly what function this will call, this is static binding. If foo could mean multiple functions depending on things not knowable at compile time, this is dynamic binding.
I understand it being evident in polymorphism. Typically when creating multiple classes that derive from a base class. If each one of the derived classes contains a function that each one uses. The base class can be used to execute a function of the derived classs and it will be properly call the correct function.
For example:
class Animal
{
void talk();
}
class Dog extends Animal
{
public void talk() { System.out.println("woof"); }
}
class Cat extends Animal
{
public void talk() { System.out.println("meow"); }
}
....
Animal zoo[2];
zoo[0] = new Dog();
zoo[1] = new Cat();
for(Animal animalToggle: zoo)
{
animalToggle.talk();
}
will print:
woof
meow
My interpretation hopefully it helps.