Dart implements/extends for abstract class - dart

For abstract classes is there difference between implements and extends? Which one should I use? In Java for interfaces you would use implements, but I see dart doesn't have interfaces and both implements/extends work. If I want to declare abstract class for my api methods, should I use implements or extends?
void main() {
User user = new User();
user.printName();
}
abstract class Profile {
String printName();
}
class User extends Profile {
#override
String printName() {
print("I work!!");
return "Test";
}
}

All classes in Dart can be used as interfaces. A class being abstract means you cannot make an instance of the class since some of its members might not be implemented.
extends means you take whatever a class already have of code and you are then building a class on top of this. So if you don't override a method, you get the method from the class you extends from. You can only extend from one class.
implements means you want to just take the interface of class but come with your own implementation of all members. So your class ends up being compatible with another class but does not come with any of the other class's implementation. You can implement multiple classes.
A third options, which you did not mention, is mixin which allow us to take the implementation of multiple mixin defined classes and put them into our own class. You can read more about them here: https://dart.dev/guides/language/language-tour#adding-features-to-a-class-mixins

Related

Dart: Extend HTMLElement with abstract class

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

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

What is the difference between ComponentModel.DataAnnotation and decorator pattern.?

I was implementing repository decorator pattern on my project as:
[Auditable]
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
}
I got this idea from the following link.
https://efpatterns.codeplex.com/discussions/282699
But couldn't successfully implemented. Then I start learning about decorator pattern and DataAnnotation because the way Auditable attribute on Product entity is somewhat similar in DataAnnotation and decorator pattern. So my question is are they same thing.? If they are the same then how would I implement Auditable repository pattern (more on link) on my project.
That's not the decorator pattern as originally described by the Gang Of Four.
The decorator pattern is an inheritance technique to add functionality to existing classes. The pattern works by creating a set of subclasses which each provide a specific type of functionality on top of the base class.
Then you compose a combination by passing the existing instance as inner object to a subclass instance:
public class SecurityToken
public class ExpiringToken : SecurityToken;
public class RpcSecurityToken : SecurityToken;
So if you would like to have a token which is remote and will expire after an amount of time:
var token = new RpcSecurityToken(new ExpiringToken(new SecurityToken("sds")));
What you do is to just decorate a class with an attribute, which not is the same thing.
The decorator pattern is a mechanism of taking a base implementation of a given interface as extending its behavior without modification of original implementation.
Its similar to inheriting from a base class, however it has more flexibility. For example, a decorator class can be applied to any other class that implements the same interface, there is no restriction to only extending a single base class. They can also be chained together etc...
e.g
public interface IThing
{
void AMethod()
}
public abstract class ThingDecorator : IThing
{
private IThing inner;
public ThingDecorator(IThing inner)
{
this.inner = inner;
}
public virtual void AMethod()
{
this.inner.AMethod();
}
}
Inheriting from ThingDecorator and applying your own extension to the virtual AMethod will add behavior (decorate) the inner instance that is passed in. As the inner instance is coupled to an interface it can be any implementation of that interface.
In your example, you could inherit ThingDecorator as AuditThingDecorator, and override AMethod and include Audit features before you call the base.AMethod()
This is different to just applying an attribute to a class. I think you are trying to apply behavior with an attribute. Attributes can only apply behavior to the class if there is a container, or some other part of the system that can read them and actually apply given behavior. With DataAnnotations, there are other classes that read these attributes and apply behavior (for example, within ASP.NET MVC, the DefaultModelBinder use some of the attributes to provide validation when binding the model).
This is a AOP (apsect orientated programming) approach. One way to apply this (and a way I tend to use) is to use Castle.Core and create interceptors that can automatically implement interface methods or extend virtual methods and read attributes from the Methods/properties that are intercepting, and then apply behavior:
http://docs.castleproject.org/Tools.DynamicProxy-Introduction.ashx
They are both essentially proxies of a given type, however the Decorator pattern above is not dynamic, they are created within code, and the AOP approach can apply behavior at runtime.

How to call GORM methods on domain classes in a generic way?

I have written a list() method for retrieving a list of domain class instances matching a set of filters, and this method is used for different domain classes ; the code is exactly the same except the class on which the GORM methods are called :
Store => Store.createCriteria()
Client => Client.createCriteria()
and so on.
To avoid code duplication, I have tried to make a generic version of the list method, by creating a generic class :
class QueryUtils<T> {
def list(params) {
T.createCriteria()
[...]
}
}
This way, each of my services (StoreService, ClientService, etc) can extend QueryUtils :
class StoreService extends QueryUtils<Store>
class ClientService extends QueryUtils<ClientService>
and so on, and inherit the list() method corresponding to its domain class type.
The problem is that during the execution, it doesn't work since the effective type of T is java.lang.Object, instead of the domain class type I have specified :
groovy.lang.MissingMethodException: No signature of method: static java.lang.Object.createCriteria() is applicable for argument types: () values: []
Do you know how to solve this problem?
I did something like this a while back for Hibernate (outside of Grails) - https://burtbeckwith.com/blog/?p=21
But it doesn't work with Groovy since the compiler ignores generics. But you could change it to take the class in the constructor instead of as a generic type:
class QueryUtils {
private final Class clazz
QueryUtils(Class clazz) {
this.clazz = clazz
}
def list(params) {
clazz.createCriteria()
[...]
}
}

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