Understanding Dynamic Binding - binding

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.

Related

How to declare factory constructor in abstract classes?

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>.

Should a class have a "has-a" relationship with a configuration class?

I have seen some questions about wrapping a set of configuration properties in a class, but not how to actually use it. Given a configuration class (omitting getters and setters for brevity):
class ServiceConfiguration {
private String foo;
}
Should the service class use the configuration directly?
static class SomeServiceB {
private ServiceConfiguration configuration;
public SomeServiceB(ServiceConfiguration configuration) {
this.configuration = configuration;
}
public void printIt() {
System.out.println(configuration.getFoo());
}
}
Or should it only be concerned with the actual value of foo? For example:
static class SomeServiceA {
private String foo;
public SomeServiceA(String foo) {
this.foo = foo;
}
public void printIt() {
System.out.println(foo);
}
}
I would argue that the SomeServiceA is superior because of the lower coupling and separation of concerns.
Both solutions are correct. The important part is that a class only takes a dependency on configuration values that it actually uses.
This means that injecting an ApplicationConfiguration object that holds all configuration values, or allows access to all application configuration values is a bad idea, because this makes it unclear what configuration values the class actually uses and postponing the reading of configuration values can cause configuration mistakes to only pop up very late. The mantra is: fail-fast.
Injecting an object that encapsulates the values a class needs is typically more convenient than injecting all those values in separate constructor arguments. This is basically the Parameter Object refactoring.
Another advantage of wrapping configuration values (even if it is just one) into a Parameter Object, is that it allows a DI Container to auto-wire this class. This is especially useful when the class has dependencies other than configuration values. For instance:
class SomeServiceB {
public SomeServiceB(IDep1 d1, IDep2 d2, SomeServiceConfig config) {
}
}
Primitive values can't easily be auto-wired by a DI Container, because values like strings and integers are ambigious: you might have multiple instances of these values with total different meanings. For instance, you might have both a connection string and a file path. Both are strings.
It is important though to make the configuration objects immutable to communicate clearly that they can't be changed. You should typically construct them at application startup and register them as singleton.

I want ClassA to get particular a particular instance of ClassB, but can't modify either class directly

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));

Difference between InputFilterAwareInterface and InputFilterProviderInterface in ZF2

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.

How to inject with Guice when there are two different constructors?

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.

Resources