Grails Transient Fields - grails

Coming from a Rails background, I don’t really understand what transient means in Grails. I read this, http://www.grails.org/doc/1.3.7/ref/Domain%20Classes/transients.html
So as it says
"...In this case it doesn't make sense to persist this property..."
The guide is referring to String getUpperCaseName() { name.toUpperCase() }
I understand that String name will be picked up when trying to save to the database but why will grails bother with a getter method? It is a method to start with..

The reason why it "bothers" with a method is because of bean naming conventions where properties (in Java) are based on setters and getters. The pattern for identifying a "property" (through reflection) based on these are: getXYZ() and setXYZ() where XYZ is the property name in bean format (name becomes Name and fullName becomes FullName).
The reasoning was the fact these methods are public they can be reflected upon and derive properties from, since actual properties were typically private (for many good reasons). I still recall when this came about. (I'm getting too old)
That's why. Java.
It's not a Grails thing. It's a Java thing. You can read more about the JavaBean specification if you want a deeper understanding of the technologies you are using..

Related

Dependency injection: Is it ok to instatiate a concrete object from a concrete factory

I am fairly new to Dependency Injection, and I wrote a great little app that worked exactly like Mark Seemann told me it would and the world was great. I even added some extra complexity to it just to see if I could handle that using DI. And I could, happy days.
Then I took it to a real world application and spent a long time scratching my head. Mark tells me that I am not allowed to use the 'new' keyword to instantiate objects, and I should instead let the IoC do this for me.
However, say that I have a repository and I want it to be able to return me a list of things, thusly:
public interface IThingRepository
{
public IEnumerable<IThing> GetThings();
}
Surely at least one implementation of this interface will have to instantiate some Thing's? And it doesn't seem so bad being allowing ThingRepository to new up some Things as they are related anyway.
I could instead pass round a POCO instead, but at some point I'm going to have to convert the POCO in to a business object, which would require me to new something up.
This situation seems to occur every time I want a number of things which is not knowable in the Composition Root (ie we only find out this information later - for example when querying the database).
Does anyone know what the best practice is in these kinds of situations?
In addition to Steven's answer, I think it is ok for a specific factory to new up it's specific matching-implementation that it was created for.
Update
Also, check this answer, specifically the comments, which say something about new-ing up instances.
Example:
public interface IContext {
T GetById<T>(int id);
}
public interface IContextFactory {
IContext Create();
}
public class EntityContext : DbContext, IContext {
public T GetById<T>(int id) {
var entity = ...; // Retrieve from db
return entity;
}
}
public class EntityContextFactory : IContextFactory {
public IContext Create() {
// I think this is ok, since the factory was specifically created
// to return the matching implementation of IContext.
return new EntityContext();
}
}
Mark tells me that I am not allowed to use the 'new' keyword to instantiate objects
That's not what Mark Seemann tells you, or what he means. You must make the clear separation between services (controlled by your composition root) at one side and primitives, entities, DTOs, view models and messages on the other side. Services are injectables and all other types are newables. You should only prevent using new on service types. It would be silly to prevent newing up strings for instance.
Since in your example the service is a repository, it seems reasonable to assume that the repository returns domain objects. Domain objects are newables and there's no reason not to new them manually.
Thanks for the answers everybody, they led me to the following conclusions.
Mark makes a distinction between stable and unstable dependencies in the book I am reading ( "Dependency injection in .NET"). Stable dependencies (eg Strings) can be created at will. Unstable dependencies should be moved behind a seam / interface.
A dependency is anything that is in a different assembly from the one that we are writing.
An unstable dependency is any of the following
It requires a run time environment to be set up such as a database, web server, maybe even the file system (otherwise it won't be extensible or testable, and it means we couldn't do late binding if we wanted to)
It doesn't exist yet (otherwise we can't do parallel development)
It requires something that isn't installed on all machines (otherwise it can cause test difficulties)
It contains non deterministic behaviour (otherwise impossible to test well)
So this is all well and good.
However, I often hide things behind seams within the same assembly. I find this extremely helpful for testing. For example if I am doing a complex calculation it is impossible to test the entire calculation well in one go. If I split the calculation up into lots of smaller classes and hide these behind seams, then I can easily inject any arbirtary intermediate results into a calculating class.
So, having had a good old think about it, these are my conclusions:
It is always OK to create a stable dependency
You should never create unstable dependencies directly
It can be useful to use seams within an assembly, particularly to break up big classes and make them more easily testable.
And in answer to my original question, it is ok to instatiate a concrete object from a concrete factory.

Distinguishing between Grails domain-class fields and getBlah() methods via GrailsDomainClassProperty

I'm writing a Groovy script (as part of a Grails plugin) and I want to get a list of properties for a GrailsDomainClass that a user of my plugin might define. I can do this using domainClass.properties (where domainClass is a GrailsDomainClass).
However, suppose a user has the grails domain class:
class Example {
String name
static constraints = {
}
def getSomeNonExistingProperty(){
return "Not-a-real-property"
}
}
In this case, domainClass.properties returns a list with both name and someNoneExistingProperty
I understand that this is because of Grails is generating a read-only property on-the-fly for use where someone has a getBlah() method. That's great, but in my script I want to perform some actions with the "real" properties only (or at least non read-only properties).
That is, I would like some way of distinguishing or identifying someNonExistingProperty as a read-only property, or, alternatively, as a property generated by Grails and not entered explicitly as a field in the domainClass by the user of my plugin.
I've looked at the GrailsDomainClassProperty Class and it has a range of methods providing information about the property. However, none of them appear to tell me whether a property is read-only or not, or to allow me to distinguish between a field defined in the domainClass and a field created on-the-fly by Grails as a result of a "getSomeNonExistingProperty()" method.
Am I missing something obvious here? Is there a way of getting a list of just the explicitly user-defined fields (eg name, in the above example)?
I believe transient properties are what you are trying to exclude
I've run into this problem a few times, and instead of trying to work around it I typically just end up renaming my getX() method. It's probably the easiest option.
Edit:
Alternatively, I wonder if you could use reflection to see which methods are defined on the class, and while iterating over your properties see if the property has an explicit getter defined, and omit it. I'm not very familiar with reflection when it comes to Groovy and Grails, especially with the dynamic methods, but it's a possible route of investigation.

Techniques for dependency injection into a domain model

I have a domain model type. One of its numerous properties requires an ITranslationService to provide the ability to translate its return value into the appropriate language.
Should I inject the ITranslationService into the constructor of the domain model type (thereby having to alter everywhere the type is instantiated and having to be concerned about initialisation when retrieved via NhIbernate), even though it is used by a tiny part of the type (one of many properties); or is there another functional pattern I can use?
Does anyone have any relevant experience they can share?
I would not expect the domain object to do the translation - instead, use the translation service with the domain object (or the relevant property value) as a parameter, and return the translated value. For example, you could simply do
var translatedString = yourServiceInstance.Translate(theDomainObject.Property);
Should I inject the
ITranslationService into the
constructor of the domain model type
Yes, that may make sense, depending on your situation. If you would always avoid the injection of services into entities, then that might lead to an anemic domain model which is an anti-pattern.
Code which needs to instantiate entities can be shielded from the extra constructor argument by using a factory, which takes care of the dependency injection.
NHibernate can also inject services into an entity via the constructor: http://fabiomaulo.blogspot.com/2008/11/entities-behavior-injection.html

Grails internals : Auto mapping and Domain object creation

I am trying to make a taglib to represent an object (to read and display at the UI). When creating an object (save method in the controller), I see the domain class and association are created by the auto assignment of parameter
def Book = new Book(params)
It also maps complex types (for eg: joda time). I wonder about the naming convention necessary to facilitate this mapping. Out of curiosity, can someone also point where in the grails source code I could see how grails handles this mapping. I'm still learning Spring and probably this would be a good exercise.
Thanks,
Babu.
AFAIK the naming conventions are rather straightforward. If there's a field params.foo and the object you are binding to has a field foo, it will bind the value, assuming the type conversion works properly. If there's a params.bar.id set with an Long value and your object has a complex property of type Bar, it will lookup this instance and inject it.
If you need more control over the binding process, you might want to use bindData.
If you are interested into the details of the binding process, have a look at Java's PropertyEditor as this is what is being used in the background. I wrote a blog post on how to create and register PropertyEditors a while ago, maybe it helps you getting started with that stuff.

Dependency injection through constructors or property setters?

I'm refactoring a class and adding a new dependency to it. The class is currently taking its existing dependencies in the constructor. So for consistency, I add the parameter to the constructor.
Of course, there are a few subclasses plus even more for unit tests, so now I am playing the game of going around altering all the constructors to match, and it's taking ages.
It makes me think that using properties with setters is a better way of getting dependencies. I don't think injected dependencies should be part of the interface to constructing an instance of a class. You add a dependency and now all your users (subclasses and anyone instantiating you directly) suddenly know about it. That feels like a break of encapsulation.
This doesn't seem to be the pattern with the existing code here, so I am looking to find out what the general consensus is, pros and cons of constructors versus properties. Is using property setters better?
Well, it depends :-).
If the class cannot do its job without the dependency, then add it to the constructor. The class needs the new dependency, so you want your change to break things. Also, creating a class that is not fully initialized ("two-step construction") is an anti-pattern (IMHO).
If the class can work without the dependency, a setter is fine.
The users of a class are supposed to know about the dependencies of a given class. If I had a class that, for example, connected to a database, and didn't provide a means to inject a persistence layer dependency, a user would never know that a connection to the database would have to be available. However, if I alter the constructor I let the users know that there is a dependency on the persistence layer.
Also, to prevent yourself from having to alter every use of the old constructor, simply apply constructor chaining as a temporary bridge between the old and new constructor.
public class ClassExample
{
public ClassExample(IDependencyOne dependencyOne, IDependencyTwo dependencyTwo)
: this (dependnecyOne, dependencyTwo, new DependnecyThreeConcreteImpl())
{ }
public ClassExample(IDependencyOne dependencyOne, IDependencyTwo dependencyTwo, IDependencyThree dependencyThree)
{
// Set the properties here.
}
}
One of the points of dependency injection is to reveal what dependencies the class has. If the class has too many dependencies, then it may be time for some refactoring to take place: Does every method of the class use all the dependencies? If not, then that's a good starting point to see where the class could be split up.
Of course, putting on the constructor means that you can validate all at once. If you assign things into read-only fields then you have some guarantees about your object's dependencies right from construction time.
It is a real pain adding new dependencies, but at least this way the compiler keeps complaining until it's correct. Which is a good thing, I think.
If you have large number of optional dependencies (which is already a smell) then probably setter injection is the way to go. Constructor injection better reveals your dependencies though.
The general preferred approach is to use constructor injection as much as possible.
Constructor injection exactly states what are the required dependencies for the object to function properly - nothing is more annoying than newing up an object and having it crashing when calling a method on it because some dependency is not set. The object returned by a constructor should be in a working state.
Try to have only one constructor, it keeps the design simple and avoids ambiguity (if not for humans, for the DI container).
You can use property injection when you have what Mark Seemann calls a local default in his book "Dependency Injection in .NET": the dependency is optional because you can provide a fine working implementation but want to allow the caller to specify a different one if needed.
(Former answer below)
I think that constructor injection are better if the injection is mandatory. If this adds too many constructors, consider using factories instead of constructors.
The setter injection is nice if the injection is optional, or if you want to change it halfway trough. I generally don't like setters, but it's a matter of taste.
It's largely a matter of personal taste.
Personally I tend to prefer the setter injection, because I believe it gives you more flexibility in the way that you can substitute implementations at runtime.
Furthermore, constructors with a lot of arguments are not clean in my opinion, and the arguments provided in a constructor should be limited to non-optional arguments.
As long as the classes interface (API) is clear in what it needs to perform its task,
you're good.
I prefer constructor injection because it helps "enforce" a class's dependency requirements. If it's in the c'tor, a consumer has to set the objects to get the app to compile. If you use setter injection they may not know they have a problem until run time - and depending on the object, it might be late in run time.
I still use setter injection from time to time when the injected object maybe needs a bunch of work itself, like initialization.
I personally prefer the Extract and Override "pattern" over injecting dependencies in the constructor, largely for the reason outlined in your question. You can set the properties as virtual and then override the implementation in a derived testable class.
I perfer constructor injection, because this seems most logical. Its like saying my class requires these dependencies to do its job. If its an optional dependency then properties seem reasonable.
I also use property injection for setting things that the container does not have a references to such as an ASP.NET View on a presenter created using the container.
I dont think it breaks encapsulation. The inner workings should remain internal and the dependencies deal with a different concern.
One option that might be worth considering is composing complex multiple-dependencies out of simple single dependencies. That is, define extra classes for compound dependencies. This makes things a little easier WRT constructor injection - fewer parameters per call - while still maintaining the must-supply-all-dependencies-to-instantiate thing.
Of course it makes most sense if there's some kind of logical grouping of dependencies, so the compound is more than an arbitrary aggregate, and it makes most sense if there are multiple dependents for a single compound dependency - but the parameter block "pattern" has been around for a long time, and most of those that I've seen have been pretty arbitrary.
Personally, though, I'm more a fan of using methods/property-setters to specify dependencies, options etc. The call names help describe what is going on. It's a good idea to provide example this-is-how-to-set-it-up snippets, though, and make sure the dependent class does enough error checks. You might want to use a finite state model for the setup.
I recently ran into a situation where I had multiple dependencies in a class, but only one of the dependencies was necessarily going to change in each implementation. Since the data access and error logging dependencies would likely only be changed for testing purposes, I added optional parameters for those dependencies and provided default implementations of those dependencies in my constructor code. In this way, the class maintains its default behavior unless overridden by the consumer of the class.
Using optional parameters can only be accomplished in frameworks that support them, such as .NET 4 (for both C# and VB.NET, though VB.NET has always had them). Of course, you can accomplish similar functionality by simply using a property that can be reassigned by the consumer of your class, but you don't get the advantage of immutability provided by having a private interface object assigned to a parameter of the constructor.
All of this being said, if you are introducing a new dependency that must be provided by every consumer, you're going to have to refactor your constructor and all code that consumers your class. My suggestions above really only apply if you have the luxury of being able to provide a default implementation for all of your current code but still provide the ability to override the default implementation if necessary.
Constructor injection does explicitly reveal the dependencies, making code more readable and less prone to unhandled run-time errors if arguments are checked in the constructor, but it really does come down to personal opinion, and the more you use DI the more you'll tend to sway back and forth one way or the other depending on the project. I personally have issues with code smells like constructors with a long list of arguments, and I feel that the consumer of an object should know the dependencies in order to use the object anyway, so this makes a case for using property injection. I don't like the implicit nature of property injection, but I find it more elegant, resulting in cleaner-looking code. But on the other hand, constructor injection does offer a higher degree of encapsulation, and in my experience I try to avoid default constructors, as they can have an ill effect on the integrity of the encapsulated data if one is not careful.
Choose injection by constructor or by property wisely based on your specific scenario. And don't feel that you have to use DI just because it seems necessary and it will prevent bad design and code smells. Sometimes it's not worth the effort to use a pattern if the effort and complexity outweighs the benefit. Keep it simple.
This is an old post, but if it is needed in future maybe this is of any use:
https://github.com/omegamit6zeichen/prinject
I had a similar idea and came up with this framework. It is probably far from complete, but it is an idea of a framework focusing on property injection
It depends on how you want to implement.
I prefer constructor injection wherever I feel the values that go in to the implementation doesnt change often. Eg: If the compnay stragtegy is go with oracle server, I will configure my datsource values for a bean achiveing connections via constructor injection.
Else, if my app is a product and chances it can connect to any db of the customer , I would implement such db configuration and multi brand implementation through setter injection. I have just taken an example but there are better ways of implementing the scenarios I mentioned above.
When to use Constructor injection?
When we want to make sure that the Object is created with all of its dependencies and to ensure that required dependencies are not null.
When to use Setter injection?
When we are working with optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency.
Additionally, setter methods make objects of that class open to reconfiguration or re-injection at a later time.
Sources:
Spring documentation ,
Java Revisited

Resources