Tuesday, January 7, 2014

Sproogle 0.0.3 Released

Sproogle (Spring/Google Integration) 0.0.3 has now been cut and promoted and will be available for download from Maven Central under the com.mattwhipple.sproogle group.  Information on the project itself is available on GitHub: https://github.com/mwhipple/sproogle .

Note

The mention in the Spring Blog makes me realize the description should be made more specific.  Presently this project is focusing on using Google Closure Templates in Spring and further "integration" is meant to be code/library integration and not service, EIP style integration.  I'll be changing the project description to be more clear and use a less overloaded synonym.  

Notable Changes

  • There are now alternate Interfaces made available so that templates can be easily rendered to Strings rather than expecting to be used only in the Spring MVC View rendering flow
  • A jQuery plugin was created to allow quickly rendering exposed closure templates within a specified element.  Sample usage has been added in the sample project.
  • TruthyRequestParameterActiveDelegatePackageProvider can now be configured to store the result in the users session.  This could be used for purposes such as passing ?debug=true in one request which would continue to use debug delegate templates for the rest of that session or until ?debug=false is passed, or this could also be easily leveraged for purposes like A/B testing.
This will be the last planned release under 0.0.x, the next being 0.1.0 which will include the cleanup and removal of some deprecated code and therefore introducing minor backwards incompatibilities.

Update

There was an issue with the transitive dependency of the Jackson module on the main project in 0.0.3, so 0.0.4 has just been promoted and should be preferred. (I'm blaming it on jinxing myself with that last sentence).  

Tuesday, December 31, 2013

Why and how the "this" keyword in JavaScript should be avoided.

The this keyword in JavaScript is a great source of confusion for newcomers to the language, particularly if they come from many other Object Oriented languages and discover the hard way that this does not behave as they would expect.  After working through the initial confusion, however, the keyword is still a wart on the language, and one that should normally be avoided.

The Problem

This has been something that has been simmering in my mind for a couple weeks now after deciding that I was swearing off of this, and now I think the underlying issue in my mind has finally resolved itself beyond vague code smells.  For anyone unaware, this in JavaScript is bound at the time of invocation rather than definition.  This, when combined with the implicit nature of it being a keywords leads to what is the potential for broken encapsulation and less controlled behavior within the body of a function where this is used.  In a collaborative environment where code is intended to be shared and re-used this is a recipe for disaster (no pun intended).

The combination that causes the issue is that this changes at invocation time and is implicitly available within the function body, thereby baking assumptions into the code (expecting that the function will be called as designed).  In other OO languages the assumption is not present because the keyword would be bound at the time of definition...but again the issue is the combination of the two factors without either being a problem in itself.  The issue with this is that it it will vary depending on how a function is called but it is not part of the signature of the function.  Signatures are the standard and proven way to express how behavior can be modified at the time of calling a function, and that is where something analogous to this belongs.


Symptoms of the Problem

Lack of Clarity

As previously mentioned a clear sign is the confusion that newcomers to the language suffer through and the amount of blog posts dedicated to explaining how to use this.  That by itself of course is solved when the concept is grasped, but using the signature analog that confusion would be at least significantly reduced.  It is far more digestible to know that a function called in a certain context has certain parameters in the signature rather than differentiating the meaning of a single inconsistent identifier: differences are more easily understood when they're...different. Also subtle dangers such as polluting the global namespace when forgetting the new keyword before a pseudo-classical constructor function would be avoided entirely if it was expected that the new instance was the first parameter rather than the magical this (or the mistake would be more obvious).  

Lack of Simplicity

call, apply, and bind are all designed to work around controlling this (in addition to further approaches provided by libraries and frameworks).  They quickly become standard tools for experienced JavaScript programmers and the immediate reaction for many of them would be "and what's the problem with them?".  The problem is that they are extra pieces to handle execution time behavior when there is something far simpler already present.  On a conceptual level these calls could also very quickly lead to the fragmentation of function arguments: there is nothing preventing using this as an operand within the body of the function and when combined with the above calls the execution path could become very muddled for no good reason.  If a signature analog were preferred over this then none of the above would be needed at all and the resultant code would be far simpler and more consistent.

Lack of Control

Another standard practice for experienced JavaScript programmers is to alias this so that objects from surrounding context can be more clearly and consistently accessed.  Again the immediate question may be "what's the problem with that?".   The problem is that this is effectively fighting the language; the utility that has been provided has proven unsuitable enough that it is consistently overwritten.  If, however, the signature analog were used then the concept of the alias would be replaced by a parameter name which could be controlled to produce the same result as the alias.  This would save the extra line of code but would also mean that you are working with the language rather than fighting against it, and it would also be more inherently readable as the parameter would be directly within the signature of the function for which it is providing the context rather than relying on a breakable convention.

The Solution

The proposed solution is not anything new and is essentially stolen from other languages which are more multi-paradigm than they are OO (such as Perl and Python).  In any case where a function is attached to an object and effectively becomes a method, the containing object is available to the function as the first parameter.  This is an elegant solution in languages where functions are optionally methods and is also very easy to understand as the language effectively just dissects a method call and passes the object receiving the message in as an argument to the method, behavior which could virtually be syntactic sugar.  

In JavaScript this makes a fantastic amount of sense since JavaScript has at least strong functional leanings (one could consider it a functional language with objects).  The concept of first class functions while also retaining some form of implicit enclosing context is an odd combination at least.  More importantly since JavaScript does provide functional approaches merging the concept of this into the standard function behavior provides access to all of the techniques developed in other functional languages.

The language as it presently stands provides support for this approach and the end result will be a simpler, more predictable, and at least as powerful platform.  Creating functions which expect their context as the first argument are able to be called with any arguments desired and without worrying about the invocation context.  Attaching those functions to become methods on an object is as simple as assigning a reference to that function that has been curried to consistently pass that object.  A method attached this way will also consistently have access to its containing object even if called through an alias, unlike one called with this which is reliant on the method call syntax.

Conclusion

So far life without this has resulted in simpler more consistent code.  This post took a bit longer than expected so code examples were skipped, but this may be revisited, subsequent posts may be added, or sample code will be referenced in relevant FOSS projects.

There may be times when this is needed since it is for better or worse part of the core language.  This should be minimized and kept out of any business code.  

Sunday, December 8, 2013

New Web site, Web presence

My latest attempt at a Web site is now online, and this blog has been updated as part of a pursuit to build a consistent Web presence.  Previous Web sites have suffered from neglect and ultimate abandonment.  This has been largely due to the fact that I've often looked to my Web site as a chance to experiment and refine some of my development work...and this led to there being enough overhead in working on the site that it wouldn't get done (even if that overhead was as simple as opening the project in an editor and uploading a new version).

The new site is built on top of Google Sites which removes that overhead.   The newly touted Google Apps Scripts could also be leveraged enough to provide the level of functionality that I may look to add, where previously I had worried about boxing myself in needlessly (and options like VosaoCMS weren't overly appealing for personal use).  The Google platform is being used because it's there, I'm already using it, and I have no reason to shift.

The development itself will be done in an incremental, ad-hoc fashion as demonstrated by the state at the time this is written (updates will be jammed into different places on the live site as part of other work in an attempt to stumble towards consistency, the present state is a representative crooked step).

There is also a greater reason for the new site as my spare development time is shifting to focus more on FOSS related projects, and therefore there should be more to share publicly (and greater time to do so without the administrivia related to doing contract style work). 

Saturday, December 8, 2012

Thoughts on Spring Surf

Spring Surf is a View composition solution originally developed as part of Alfresco projects but which has recently been spun off into its own project (technlogies mentioned were previously s/Spring/Alfresco/).  I've been working with Surf on a project for the past 6 months and have grown familiar with many of its intricacies

What it is

Spring Surf  is probably best known for its use within Alfresco Share.  Surf provides a skeleton around Spring Webscripts which are effectively bundles of convention driven MVC functionality made to work within Alfresco.  Surf is largely notable for its very verbose XML based view definitions where the various components are customizable in multiple locations.  Additionally Surf creates a rich model which represents the assorted objects which play a role in the View and can be used while rendering for some view specific logic.

My Hopes

I adopted Spring Surf for a project because we use Alfresco and I was looking for a replacement solution that would keep stakeholders from desiring that some stale legacy code was carried forward.  The verbosity of Surf seemed to promise higher levels of flexibility, and combined with Alfresco that could allow for a greater amount of runtime control and publishing of a wide range of View updates through Alfresco Web forms.  The splitting off of Surf into a Spring project was promising as it indicated that Alfresco was interested in creating a richer ecosystem of libraries that were less coupled to their architecture.

DevCon

 I recently went to Alfresco DevCon 2012 primarily to get a feel for the future direction of the project so that any of my work would not diverge too strongly (particularly since most documentation is still focused on version 3 while 4 appeared to be a major shift).  Alfresco is understandably focused on enhancing its role as an ECM which co-exists with other solutions and in particular becoming the cloud compatible ECM.  Solutions which are not directly concerned with document management are increasingly being handled outside of Alfresco using CMIS and entirely different technologies (like Drupal).

My Realities(not necessarily anyone else's)

The biggest single hurdle in working with Surf was the lack of documentation.  Although it had been split off, the Spring pages were seemingly given no attention and there was effectively no information about using the framework in non-Alfresco contexts.  After DevCon it became painfully clear that this is due to Surf not being useful outside of Alfresco, particularly Alfresco Share.

Being focused on being an ECM Alfresco is in the role of allowing their solutions to be able to be worked with, but it is not their role to develop external solutions.  The splitting of Share into a more distinct client application was necessary to become more Cloud-y.  I can only suppose that shifting Webscripts and Surf to the Spring umbrella was done in the hopes that they would gain traction outside of Alfresco (which they haven't).  Alfresco provides a powerful platform for the repository and for the Share client, but on the client side the result is that you must be on top of the platform to reap the benefits.  The idea of further modularization into a library or loosely coupled framework is not on their horizon.

Surf is too cumbersome to compete with other similar solutions.  There is virtually no tooling to help with the creation of Surf files.  The one possible exception is the now seemingly abandoned Spring Roo plugin, which from my eyes is on the wrong end of the development tools: a possible benefit of having the view defined using Surf's approach would be to transfer greater power to a non-engineer (non Roo user).

The imagined flexibility didn't pan out as the model of the View is created entirely at start-up.  This makes sense and there are ways to work around it, but ultimately it does not provide any out of the box flexibility beyond any other view composition approaches.

Webscripts still have promise (and are used effectively in another department at my office), but unless they are communicating with Alfresco they could also be replaced by a far simpler and lighter solution.

Ultimately Spring Surf only makes sense as Alfresco Surf and used in Alfresco Share.  The entire structure makes perfect sense when viewed through the lens of a larger platform which allows for a consistent programming model when dealing with repository nodes and a View which represents the interface to that repository.  Outside of that context, however, the complexity it introduces provides no benefit over slight modifications of far, far simpler alternatives.

If you are building a solution that should sensibly be tied to the Alfresco platform, then using Surf to customize Share and optionally working with an Alfresco partner makes a lot of sense.  If you're looking for a more general purpose solution and may have even thought something like Spring == a solution that can help for a variety of problems: keep looking.

Transparent REST client code for your services using Spring 3 and RESTEasy

The advantages to creating REST services has been re-iterated enough to be skipped here.  I will quickly mention my personal most practical favorite is that it allows the I/O of the service to be visible enough that the endpoints can be easily debugged in isolation using curl.  One of the big dangers is that the simplicity of creating client code can lead to issues like duplication and inconsistency as on- off code is thrown together.  Ironically the simplicity that is the strength of REST can become its weakness as the need for structure is so dramatically reduced.  Most JAX-RS implementations (I think) provide support for a client package where you can be left with the best of both worlds: a simple REST service and a means to automatically generate
structured client code.

RESTEasy is being used because the target environment is running JBoss servers.  Alternative JAX-RS implementations such as Jersey and CXF should offer similar mechanisms, though they were not researched thoroughly.

Background

Basic Objectives

This solution assumes that both a service and a client package for that service are being developed.  There is nothing to prevent the client solution from being used by itself, but it would likely not be justifiable considering the relative complexity of the produced system and the associated dependencies.

The basic goals are as follows:
  • The service should be a simple, standard REST service
  • Java client could should be able to transparently access the service
  • The API information should be DRY between systems
  • It should be easier to code than alternatives

The simple client alternative

More often than not it seems as though REST clients are created directly using HttpClient or (in Spring) using the RestTemplate.  This a very simple and straightforward approach.  Additionally...it is quite likely the most viable alternative when accessing a third party service that does not provide a specific client package.  In particular this would make sense if the service is implemented in another language (and I would probably recommend using a language that allows for faster development unless there's a reason for Java.

Possible Issues

(All of these could be avoided of course)
  • The API information (including DTOs) is likely to be duplicated in the client and the server
  • Management of the connection and serialization concerns may need to be addressed (and therefore likely to be buggy)
  • The connection may be implemented outside of a properly defined layer and interface

RESTEasy Proxy Client in Spring

RESTEasy provides a proxy client that can be used to connect to a defined service interface.  The documentation demonstrates how it can be used, but (as it is framework agnostic) does not provide integration information.  Using Spring 3 programmatic configuration allows for seamless automatic creation of a service layer which can be used to access the remote REST API.  This keeps the definition of the service consolidated between client and server and therefor eases maintenance.  Additionally it allows the client system to call the proxy and be provided with an object without concern of where it is coming from, and allowing the RESTEasy code to properly handle the details.

Implementation

The Interface

The JAX-RS information should be provided in the form of an Interface if that is not normally practiced.  The JAX-RS Interface is what drives everything, it should be packaged in a location that is accessible to both the client and the server (as should any DTOs), within the client module would work as a default.  Simple example:

@Path(ExampleResource.PATH)
public interface ExampleResource {
  public static final String PATH = "/collection/";

  @GET
  @Path("/{id}")
  @Produces(Mediatype.APPLICATION_JSON)
  Example findOne(@PathParam("id") Long id);

}

The Server

The server should provide the endpoint that implements the created Interface.  This is standard JAX-RS behavior.  It could be done directly on top of an existing service, I personally like to keep it in a controller layer to ensure that it can remain resource oriented while the services may be more message oriented.

The Client (the actual significant part)

Now the fun way to bridge the gap left in the RESTEasy docs of how to tie those client proxies in to your system.  Using Spring 3 annotations for programmatic configuration you can add the following to a re-usable client module:

@Configuration
public class RestClientConfiguration {
  @Value("${restServiceRoot}")
  private String restServiceRoot;

  public ServiceBeanConfiguration() {
    RegisterBuiltin.register(
      ResteasyProviderFactory.getInstance());
  }

  @Bean
  public ExampleResource exampleResourceClientService() {
    return ProxyFactory.create(ExampleResource.class, restServiceRoot);
  }
}

This creates a new Spring bean named "exampleResourceClientService" (the name of the method or specified as a value for @Bean) which can then just be injected as needed (ideally using the Interface) and called like Example example = exampleResourceClientService.findOne(id);.  Additionally the above assumes you have a property named restServiceRoot which points to the server (such as "http://myservice.example.com/rest").

Conclusion

Following the above you should be able to create a client jar that can be included in any project and scanned to get an easily maintained client package for very little work.  Additional services can be created by adding new methods to the configuration class, and further customizations can be easily applied.  You end up with a nice simple REST API but with the kind of client proxy that is normally associated with heavier communication technologies.

Saturday, October 6, 2012

Why Constructor Injection Should Be Used

Spring and other DI frameworks normally support 2 types of injection, setter injection and constructor injection.  Since setter injection is the more flexible it has become the far more popular approach, but making better use of constructor injection makes code clearer and more robust.

Setter Injection and JavaBeans

Setter injection will always get you where you want to be.  It also has the advantage of being in line with the standard JavaBean approach of using a default nullary constructor and then setting what is needed.  To start, in the context of more modern languages the concept of the standard JavaBeans is laughable. The idea that code like:

Person me = new Person();
me.setFirstName("Matt");
me.setMood("Laughing");

is some kind of win for convention is absurd.  It is verbose, and a visual correspondence to an underlying data structure is lost.  It is preferable to telescopic constructors with ambiguous arguments, but it doesn't seem to offer enough benefit to justify potential problems (Groovy does offer some nice sugar that addresses this, but this is about Java).

What's the problem?

Nullary constructors lead to objects that are an inconsistent state if they have have required members.  Continuing the example above, suppose every person must have a first name.  When that object is first created, it does not have a first name until that setter is called.  This is almost certainly not an issue in this code since everything is wrapped up in the same stack frame and so nothing should be able to accidentally sneak in between those 2 statements.  But it does limit the use of that class into only being operated on in thread safe contexts such as above.  The class itself is not inherently thread safe.

The other possible issue is mutability.  First names can change, but suppose this Person is being stored in some database where it has a numeric primary key.  Mucking around with that id after the object exists could be a recipe for disaster, locking the  id would make everything a lot safer.

Spring Cleaning

The simplest example for this problem in a DI container is looking at a typical Spring managed beans.  In general most layered applications with persistence will consist of a service layer which interacts with the repository layer.  The code with setter injection (with annotations, and javax.inject since I like standards) could be something like (there may be typos since I'm IDE dependent but am not using one, and I'm omitting the @Transactional annotation(s)).

@Service
public class SomeServiceImpl implements SomeService() {
  
  private SomeRepository someRepository;

  @Inject //Or on the variable itself
  public void setSomeRepository(SomeRepository someRepository) {
   this.someRepository = someRepository;
  }

  @Override
  public void updateSomeData(DataStruct struct) {
   //Do some magic
   someRepository.storeData(struct);
  }
}

The possibility of "updateSomeData" being called when the object is in an inconsistent state is more apparent in this type of class where you'd expect calls from multiple clients.  But...Spring takes care of that for you by wiring all of your beans together on start-up.  But this does become an issue when the bean is used outside of the context of Spring.  One of the pursuits of frameworks like Spring is to allow your code to remain decoupled from the underlying framework, but the code above is operating under a potentially fatal presumption.

Constructor Version

@Service
@Transactional
public class SomeServiceImpl implements SomeService() {
  
  private final SomeRepository someRepository;

  @Inject //Or on the variable itself
  public SomeServiceImpl(SomeRepository someRepository) {
    if (someRepository == null) throw new NullPointerException();
    this.someRepository = someRepository;
  }

  @Override
  public void updateSomeData(DataStruct struct) {
   //Do some magic
   someRepository.storeData(struct);
  }
}

As you can see there is no substantial difference in code length, but this class is far stronger.  Spring operates in virtually the same way, but the annotation is moved to the new constructor (the xml version does add a slight amount of extra knowledge but still less than 10 minutes to process).  Objects of this class cannot be in an inconsistent state, its dependencies are checked and locked before the object is made available (throwing the NPE in the style recommended in Effective Java by Joshua Bloch, but other approaches could work).

An additional benefit is that the code has a clearer intent.  By defining the key dependencies of a class as constructor dependencies (and as final where relevant), the class becomes more self-describing: "These are the pieces that I am useless without and will blow up if I don't have them".  This can then be augmented by setter injection for those other managed beans which are looser, less essential dependencies (such as Strategies that may be used in 1 or 2 methods, or a service which will by bypassed if not available).  

Conclusion

Constructors provide a powerful means to ensure that your objects are in a consistent state throughout their life and can help minimize needless mutability and their exposed API.  A possible downside of Spring (and other DI containers) is that the easy and consistent setter usage  can discourage the use of constructors.  Proper use of constructors in place of setters leads to more resilient and more intentional code.  

Sunday, September 23, 2012

Using Spring Form Binding When the View Resolver Doesn't Support It (Take 2)

So in an earlier post (what is now Take 1), I covered how to expose Spring form binding to pass through everything that is needed in the event that your View resolver of choice doesn't support it (more information is available in that post).  At the time I used a handler interceptor to move the logic outside of the View resolver.   This introduced the small annoyance that there was a check on each request to see whether this was the right kind of view.  Additionally as discovered later, this also presents problems elsewhere...so time to push it back into the view resolver where it belongs.

Broken Exceptions

What caught up with me using that approach was using Spring exception handling.  Adding an exception handler to a controller, for instance, can prevent you from having to worry about system errors in addition to expected error conditions.  You obviously shouldn't be doing much with Spring form binding in your exception handling, but it's nice to be able to do something like throw the user back out to the form they were using (or another form for that matter) with an appropriate message.  For instance I was working on a form that was processed locally before communicating with a remote service.  In the case of most errors I wanted to give the user a chance to try again, but I didn't want to pollute the local code with _all_ of the remote concerns.

Into the View Resolver

But where?  Like before I wanted to keep this piece decently modularized and Spring didn't provide much to help.  After fishing through the source code for a bit the best place seemed to be to intercept the call to render() on the View interface.

 public void render(Map<String, ?> model, HttpServletRequest request,
   HttpServletResponse response) throws Exception {

This can be modified using a Decorative wrapper:

public class RequestContextViewDecorator implements View {

 private final View innerView;
 private final ApplicationContext applicationContext;
 
 public RequestContextViewDecorator(View innerView, ApplicationContext applicationContext) {
  this.innerView = innerView;
  this.applicationContext = applicationContext;
 }

The first issue is getting around that pesky wildcard capture "?" in the model. This is easily done by a small method to get back a known safe type:

 private Map<String, Object> getTypedMap(Map<String, ?> model) {
  Map%lt;String, Object> typedMap = new HashMap%lt;String, Object>();
  typedMap.putAll(model);
  return typedMap;
 }

This could easily be refactored in to an abstract class and then use a Template abstract method which receives the typed map if you have other classes doing similar things or like to add extra classes to keep things focused.  This object then inherits the same behavior covered from the first post, throwing what it needs in the model and then delegating to the wrapped View:

        @Override
 public void render(Map%lt;String, ?> untypedModel, HttpServletRequest request,
   HttpServletResponse response) throws Exception {

  Map model = getTypedMap(untypedModel);
   
  if (exposeSpringMacroHelpers) {
   if (!model.containsKey(MODEL_KEY)) {
    model.put(MODEL_KEY, new RequestContext(request, response, ((WebApplicationContext) applicationContext).getServletContext(), model));
   }
  }
....
        innerView.render(model, request, response);
     }


Now just plug in to to your view resolver (in this case the Surf(again) view resolver):


public class RequestContextPageViewResolver extends PageViewResolver {
 
 @Override
 protected View loadView(String viewName, Locale locale) throws Exception {
  return new RequestContextViewDecorator(super.loadView(viewName, locale), this.getApplicationContext());
 }
}


And there you have it (after you wire in your View resolver of choice in your Spring config): a nice OOP way of integrating the request context needed for Spring form binding in a modular way to a View resolver which for some reason or another does not have the functionality in its inheritance hierarchy.