Are there any creational design patterns that instantiate newly written classes? - object

Are there any creational design patterns that allow for completely new objects (as in newly written) to be instantiated without having to add a new statement somewhere in existing code?

The main problem to solve is how to identify the class or classes to instantiate. I know of and have used three general patterns for discovering classes, which I'll call registration, self-registration and discovery by type. I'm not aware of them having been written up in a formal pattern description.
Registration: Each class that wants to be discovered is registered somewhere where a framework can find it:
the class name is put in an environment variable or Java system property, in a file, etc.
some code adds the class or its name to a singleton list early in program execution
Self-registration: Each class that wants to be discovered registers itself, probably in a singleton list. The trick is how the class knows when to do that.
The class might have to be explicitly referred to by some code early in the program (e.g. the old way of choosing a JDBC driver).
In Ruby, the code that defines a class can register the class somewhere (or do anything else) when the class is defined. It suffices to require the file that contains the class.
Discovery by type: Each class that wants to be discovered extends or implements a type defined by the framework, or is named in a particular way. Spring autowiring class annotations are another version of this pattern.
There are several ways to find classes that descend from a given type in Java (here's one SO question, here's another) and Ruby. As with self-registration, in languages like those where classes are dynamically loaded, something has to be done to be sure the class is loaded before asking the runtime what classes are available.

One things which I think here is that someone needs to do a new to your newly written Class. If you are not doing that then may be some framework needs to do that.
I could remember something similar which I did in one of my side projects using Java Spring . I had an interface and multiple implementations to it. My project required to iterate over all the implementations do some processing. Now for this even I was looking for some solution with which I would not have to manually do the instantiation of that particular class or some explicit wiring of that particular class. So Spring facilitated me to do that through #Autowired annotation. It injected all the implementation of that interface on the fly. Eg :-
#Autowired
private List<IMyClass> myClassImplementations;
Now in the above example I can simply iterate over the list of implementations injected and I would not have to do instantiation of my new implementation every time I write a new one.
But I think in most of the cases it would be difficult to use this approach (even though it fits in my case). I would rather go with a Factory pattern in general case and try to use that for creating new instances. I know that would require new but in my perception engineering it in a way that its object is automatically created and injected is a bit an extra overhead.

Related

Codeigniter4 - Difference between Libraries, helper and model

I walk the first steps in codeigniter4.
Now I ask myself what are the big differences between a "Model" where I do at first all database related things, a "Helper" where I defined a set of functions or a "Libary"?
In which cases should I create my own libary, helper, model?
The CI4 Docu won't give me a answer for that, so I hope someone can explain it for me (and other ones)
The documentation is pretty straight forward when it comes to Models, there's really no caveats there. A Model is a class that represents a single table in the database and it provides to you a wide variety of related functionality: built-in CRUD methods, the ability to save Entities, transparent use of Query Builder methods, etc.
In general, you would typically have one Model class per database table that you're working with. That being said, you do not necessarily need Models in order to work with a database; however if you expect to need the functionality a Model provides, it can be used to save you the work of doing it yourself.
The documentation is indeed far more opaque on the differences between Libraries and Helpers. As such, I've found the most objective measure of difference to be in how CodeIgniter itself utilizes them, and the distinction is rather subtle:
Libraries provide their functionality through methods that exist within the namespace of the class they're defined in.
Helpers provide their functionality through functions that exist within the namespace of the importing class.
(NB: In PHP, a method is simply the name for a function that's defined within a class)
In other words, Libraries are typically non-static classes that (like all non-static classes) must be 'constructed' before use. The methods defined within that class reside within the namespace of the class itself, not the class they're called from.
For example, to gain access to the current Session object, I retrieve an instance of the Session Library class: $session = session(); Using $session, I can then invoke methods provided by that Session class, like $session->destroy().
On the other hand, Helpers are typically just a collection of functions that are imported into the namespace of the importing class itself. They are called in the current context and their use is not predicated upon the use of an object.
For example, if I loaded the Array Helper (helper('array');), it would grant me access to a handful of functions that I could call directly from the current context (e.g. $result = array_deep_search(...)). I didn't have to create an object first, that function was imported directly into my current namespace.
This distinction could matter for a couple of reasons, the biggest of which is probably naming conflicts. If you have two Helpers, each with an identically-named function, you can't import both of those functions at the same time. On the other hand, you could have one hundred different classes with the destroy() method defined, because each of those method definitions resides within the namespace of the defining class itself and is invoked through an instance of that specific class.
You may notice that all of CI's Helper functions are prefixed with the name of the Helper itself, e.g. 'array' or 'form'; this is to prevent the aforementioned naming conflict.
This probably doesn't answer when you want to use one or the other, and in truth that really comes down to your opinion. In the end, it's all just namespacing. You can put things wherever you want, as long as the code that needs it knows where to look for it. I personally try to follow CI's lead on things, so I tend to follow their distinction between the two.

How to go with well-known classes and interfaces in an UML class diagram

Given I have two Java classes Foo and Bar, and Bar has a getFoos() method that returns a List<Foo>.
In Java, all classes extend the parent class Object. List is an interface that extends the interface Collection, which in turn extends Iterable. All of these are provided by the Java core and do not require programming. However, they have methods that can be used or overridden. Interface hierarchy may be necessary to be known, for example a method that takes an Iterable<Foo> will accept a List<Foo>.
When drawing a class diagram from these in UML, how do I do with the well-known classes (Object) and interfaces (List, and its super interfaces Collection and Iterable)? Do I have to draw them into the diagram as well? Can I skip them completely? Is there a special symbol for these (a cloud would feel great to me)? What about not-that-common classes that should be qualified (i.e. if it would be an java.awt.List and not a java.util.List)?
UML is not linked to any language, there is nothing in the norm about JDK classes.
A lot's of tools provide a profile with JDK classes already defined.
So you have to look in your tool if you get menu like "import profile" and look which profiles are available.
Two others solutions could be:
Define in your models the minimum set of JDK classes you need
Trying to write a java program to generate the XMI of JDK classes. Theoretically not so complicated, but the JDK includes JNI classes on which the introspection can not be used.
Your choice for how to deal with well-known classes will depend on how you plan on using your UML class diagram.
If the main purpose for creating a UML diagram is to communicate design details to a team, I would opt for not including well-know classes (not just from the JDK but also classes that are well-known in your context). The reason being that you want your message to be focused. Adding these well-known classes can quickly clutter your diagram while adding nothing to your message. For the same reason I typically exclude getters/setters and any information that is not essential to understanding the design. For classes that are not well-known I will include them because they communicate information that is not easily accessible to the team.
If your class diagram is going to be used in MDA, i.e. it will be used to generate a system implementation, then you have to include well-known classes.

Metaobject Protocol (MOP) in Groovy

I am new to the Groovy programming language and I am trying to fully understand the dynamic nature and capabilities it has. What I do know is that every class created in Groovy in its most basic form looks like this (implements GroovyObject and extending java Object).
public class Foo implements groovy.lang.GroovyObject extends java.lang.Object { }
Groovy object also contains a MetaClass that extends MetaObjectProtocol. It is this class hierarchy that provides some of Groovy's dynamic capabilities. This includes the ability to introspect itself (getProperties,getMethods) or intercept methods (invokeMethod,missingMethod).
I also understand the different types of meta programming available in Groovy. These give you the ability to add or override functionality at runtime or compile time.
Runtime
Categories
Expando / MetaClass / ExpandoMetaClass
Compile Time
AST Transformations
Extension Module
Now that have some of that out of the way we can get to the meat of this question. When someone or a book refers to the "Metaobject Protocol" in Groovy are we talking about a specific class or a collection of things. I have hard time grasping something that isn't defined or set in stone. One of my books defined it as
A protocol is a collection of rules and formats. The
Meta-Object-Protocol (MOP) is the collection of rules of how a request
for a method call is handled by the Groovy runtime system and how to
control the intermediate layer. The "format" of the protocol is
defined by the respective APIs,
I also have Venkat's Programming Groovy 2 book and in it there is a diagram that defines this method lookup process. So I am guessing this is the rules of how we request a method (at least a POGO, I understand a POJO is different).
Anyways I think I am going down the right path but I feel like I am still missing that "ahhhaa" moment. Can anyone fill me in on what I am missing? Or at the very least tell me my ramblings here made some sort of sense :) Thank you!!
This is the answer. "The Meta-Object-Protocol (MOP) is the collection of rules of how a request for a method call is handled by the Groovy runtime system and how to control the intermediate layer." Once you understand the process a method call goes through and the API that comes with it I think it all makes sense. I was just over thinking it all. Thanks!!

How do I force usage of a CDI producer method?

Part of my problem here is using the proper vocabulary, so I apologize in advance for what might be a simple matter of terminology.
Suppose I have a Person interface, and a PersonBean class that implements that interface.
Suppose further I have a producer method somewhere (annotated #Produces) that returns a Person. Internally it returns a new PersonBean, but that's neither here nor there.
Finally, suppose I have another CDI bean somewhere with an injection point defined like this:
#Inject
private Person person;
Assuming I have all my beans.xml files in place etc. and have bootstrapped Weld or another CDI-1.0-compliant environment, as this all stands I will get an ambiguous definition error. This makes sense: Weld will find my PersonBean as a candidate for injection (it could just call the constructor) and will find the output of my producer method as a candidate for injection.
What I'd like to do is somehow force the production of Person instances in this application to always route through the producer method.
I understand I could invent some qualifier somewhere and make the producer method produce Person instances that are qualified by that qualifier. If I do that, and change my injection point to include the qualifier, then obviously there's only one source of these qualified injectables (namely my producer method), so voila, problem solved.
But suppose I don't want to invent some bogus qualifier. (I'm not saying this is the case; just trying to more deeply understand the issues.) What are my options? Do I have any? I suppose I could put #Typed(Object.class) on the PersonBean to make it so that it was not seen as a Person by CDI....
Any ideas welcomed, including pointers to documentation, or better ways to understand this. Thanks.
Annotate you PersonBean as #Alternative then it will use the producer method.
From digesting several different answers here and elsewhere, the solution I've adopted is to use the #Typed annotation with a value of Object.class on my bean. This means that it will only be eligible to be injected into fields that are declared like this:
#Inject
private Object something;
...which thankfully prove to be pretty much nonexistent. :-)
What I'd like to do is somehow force the production of Person
instances in this application to always route through the producer
method.
Seam solder has a solution for this.
I'm not 100% sure how this will develop with the merge of Seam 3 and Deltaspike (the page is so 90s, but the content rocks :-), but putting Solder in your classpath is certainly a safe bet.
Oh, and as far as I know a comparable mechanism made it into the CDI 1.1 spec.

Meta Programming, whats it good for?

So Meta Programming -- the idea that you can modify classes/objects at runtime, injecting new methods and properties. I know its good for framework development; been working with Grails, and that framework adds a bunch of methods to your classes at runtime. You have a name property on a User object, and bamm, you get a findByName method injected at runtime.
Has my description completely described the concept?
What else is it good for (specific examples) other than framework development?
To me, meta-programming is "a program that writes programs".
Meta-programming is especially good for reuse, because it supports generalization: you can define a family of concepts that belong to a particular pattern. Then, through variability you can apply that concept in similar, but different scenarios.
The simplest example is Java's getters and setters as mentioned by #Sjoerd:
Both getter and setter follow a well-defined pattern: A getter returns a class member, and a setter sets a class member's value. Usually you build what it's called a template to allow application and reuse of that particular pattern. How a template works depends on the meta-programming/code generation approach being used.
If you want a getter or setter to behave in a slightly different way, you may add some parameters to your template. This is variability. For instance, if you want to add additional processing code when getting/setting, you may add a block of code as a variability parameter. Mixing custom code and generated code can be tricky. ABSE is currently the only MDSD approach that I know that natively supports custom code directly as a template parameter.
Meta programming is not only adding methods at runtime, it can also be automatically creating code at compile time. I.e. code generating code.
Web services (i.e. the methods are defined in the WSDL, and you want to use them as if they were real methods on an object)
Avoiding boilerplate code. For example, in Java you should use getters and setters, but these can be made automatically for most properties.

Resources