Featured FREE Whitepapers

What's New Here?

java-logo

Understanding strategy pattern by designing game of chess

Today we will try to understand Strategy Pattern with the help of an example. The example we will consider is The Game of Chess. The intention here is to explain strategy pattern and not to build a comprehensive Chess Game solution. Strategy Pattern : The Strategy pattern is known as a behavioural pattern – it’s used to manage algorithms, relationships and responsibilities between objects. The main benefit of strategy pattern is to choose the algorithm/behaviour at runtime.        Lets try to understand this by implementing this to design the chess game. In chess there are different characters like King, Queen, Bishop and all of them have different moves. There could be many possible solutions to this design, lets explore one by one :The first way would be to define movement in each and every class, every character will have its own move() implementation. In this way there is no code reusability and we can not change the implementation at run time. Make a separate MovementController Class and put an if else for each type of movement of an object.public class BadDesginCharacterMovementController {public void move(Character character){ if(character instanceof King){ System.out.print("Move One Step forward"); }else if(character instanceof Queen){ System.out.print("Move One Step forward"); }else if(character instanceof Bishop){ System.out.print("Move diagonally"); } } } This is a poor design, with strong coupling, moreover using if/else makes it ugly. So, we would like to have a design where we can have loose coupling, where we can decide the movement algorithm at run time and there is code reusability. Lets see this complete implementation using Strategy Pattern. Below is that class diagram of our implementation:The complete source code can be downloaded from here.We will have our base abstract class as Character Class, which all the characters can extend and set their own MovementBehaviour implementation. public class Character {private MovementBehaviour movementBehaviour;String move(){ return movementBehaviour.move(); }public void setMovementBehaviour(MovementBehaviour movementBehaviour) { this.movementBehaviour = movementBehaviour; } } This class has a movement Behaviour: public interface MovementBehaviour {String move(); } So, each Character : King,Queen,Bishop will extend Character and they can have their own implementation of Movement Behaviour. public class King extends Character {public King() { setMovementBehaviour(new SingleForward()); } } Here for simplicity, I have called the setMovemementBehaviour method inside the constructor of King. Similarly, another character Queen can be defined as : public class Queen extends Character {public Queen() { setMovementBehaviour(new SingleForward()); } } And, Bishop as : public class Bishop extends Character {public Bishop() { setMovementBehaviour(new DiagonalMovement()); } } The implementation of different movements can be as follows: Single Forward : public class SingleForward implements MovementBehaviour {@Override public String move() { return "move one step forward"; } } Diagonal Movement: public class DiagonalMovement implements MovementBehaviour {@Override public String move() { return "Moving Diagonally"; } } With this example we can understand the Strategy Pattern.Reference: Understanding strategy pattern by designing game of chess from our JCG partner Anirudh Bhatnagar at the anirudh bhatnagar blog....
software-development-2-logo

CallSerially The EDT & InvokeAndBlock (Part 1)

We last explained some of the concepts behind the EDT in 2008 so its high time we wrote about it again, there is a section about it in the developer guide as well as in the courses on Udemy but since this is the most important thing to understand in Codename One it bares repeating. One of the nice things about the EDT is that many of the concepts within it are similar to the concepts in pretty much every other GUI environment (Swing/FX, Android, iOS etc.). So if you can understand this explanation this might help you when working in other platforms too. Codename One can have as many threads as you want, however there is one thread created internally in Codename One named “EDT” for Event Dispatch Thread. This name doesn’t do the thread justice since it handles everything including painting etc. You can imagine the EDT as a loop such as this: while(codenameOneRunning) { performEventCallbacks(); performCallSeriallyCalls(); drawGraphicsAndAnimations(); sleepUntilNextEDTCycle(); } The general rule of the thumb in Codename One is: Every time Codename One invokes a method its probably on the EDT (unless explicitly stated otherwise), every time you invoke something in Codename One it should be on the EDT (unless explicitly stated otherwise). There are a few notable special cases:NetworkManager/ConnectionRequest – use the network thread internally and not the EDT. However they can/should be invoked from the EDT. BrowserNavigationCallback – due to its unique function it MUST be invoked on the native browser thread. Displays invokeAndBlock/startThread – create completely new threads.Other than those pretty much everything is on the EDT. If you are unsure you can use the Display.isEDT method to check whether you are on the EDT or not. EDT Violations You can violate the EDT in two major ways:Call a method in Codename One from a thread that isn’t the EDT thread (e.g. the network thread or a thread created by you). Do a CPU intensive task (such as reading a large file) on the EDT – this will effectively block all event processing, painting etc. making the application feel slow.Luckily we have a tool in the simulator: the EDT violation detection tool. This effectively prints a stack trace to suspect violations of the EDT. Its not fool proof and might land your with false positives but it should help you with some of these issues which are hard to detect. So how do you prevent an EDT violation? To prevent abuse of the EDT thread (slow operations on the EDT) just spawn a new thread using either new Thread(), Display.startThread or invokeAndBlock (more on that later). Then when you need to broadcast your updates back to the EDT you can use callSerially or callSeriallyAndWait. CallSerially callSerially invokes the run() method of the runnable argument it receives on the Event Dispatch Thread. This is very useful if you are on a separate thread but is also occasionally useful when we are on the EDT and want to postpone actions to the next cycle of the EDT (more on that next time). callSeriallyAndWait is identical to call serially but it waits for the callSerially to complete before returning. For obvious reasons it can’t be invoked on the EDT. In the second part of this mini tutorial I will discuss invokeAndBlock and why we might want to use callSerially when we already are on the EDT.Reference: CallSerially The EDT & InvokeAndBlock (Part 1) from our JCG partner Shai Almog at the Codename One blog....
ceylon_logo

Ceylon: Planning the future of Ceylon 1.x

With the release of Ceylon 1.1, we’ve reached a point where we need to do some serious thinking about what are our priorities for the development of Ceylon 1.1.5, 1.2, and beyond. I definitely don’t yet have a crystal clear vision of what is going to be in 1.2, so we’re also looking for community feedback on this. I do know of one item which is the top priority right now, and will be the main feature of Ceylon 1.1.5:      Serialization.This was a feature that slipped from Ceylon 1.0, and which again narrowly missed out on inclusion in Ceylon 1.1. The concept behind serialization in Ceylon is to have an API responsible for assembling and disassembling objects that is agnostic as to the actual format of the serialized stream. Of course, this API also has to be platform neutral, in order to allow serialization between programs running on the JVM and programs running on a JavaScript VM. Tom Bentley already has a working prototype implementation. Once this feature is done, we can start working on serialization libraries supporting JSON and whatever else. I also count the following as a high priority areas of work:Java EE integration, and support for technologies like JPA and CDI. Adding properties to the language, that is, a new syntax for attribute references, allowing easy MVC UI bindings. Improving the Cayla web framework, and ceylon.html.Beyond that, we’re not sure where else we should concentrate development effort. Here are some things that stick out to me:Addition of named constructors, allowing multiple ways to instantiate and initialize a class. AST transformers—a system of compiler plugins, based around ceylon.ast, enabling advanced compile-time metaprogramming, which would form the foundation for LINQ-style queries, interceptors and proxies, and autogeneration of equals(), hash, and string, and more. Addition of a syntax for expressing patterns in BNF. The Ceylon plugin for IntelliJ IDEA. Android support. Assemblies—a facility for packaging multiple modules into a deployable “application”. New platform modules defining dynamic interfaces for typesafe interaction with JavaScript APIs such as the DOM, jQuery, etc. Interoperation with dynamic languages on the JVM, via Ceylon’s dynamic blocks and dynamic interfaces. Enabling the use of Ceylon for scripting.We can’t do all of this in Ceylon 1.2. Therefore, we’re looking for feedback from the community. Let us know, here in comments, or on the mailing list, what you feel is missing from Ceylon, either from the above list, or whatever else you think is important.Reference: Ceylon: Planning the future of Ceylon 1.x from our JCG partner Gavin King at the Ceylon Team blog blog....
software-development-2-logo

right-pad values with XSLT

In this post an XSLT function that can be used to right-pad the value of an element with a chosen character to a certain length. No rocket science but this might become handy again so by putting it down here I don’t have to reinvent it later. The function itself looks like:               <xsl:stylesheet version="2.0" xmlns:functx="http://my/functions" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:function name="functx:pad-string-to-length" as="xsd:string"> <xsl:param name="stringToPad" as="xsd:string?"/> <xsl:param name="padChar" as="xsd:string"/> <xsl:param name="length" as="xsd:integer"/> <xsl:sequence select=" substring( string-join ( ($stringToPad, for $i in (1 to $length) return $padChar) ,'') ,1,$length) "/> </xsl:function></xsl:stylesheet> And with this function available you can use it like: <xsl:template match="/"> <xsl:value-of select="functx:pad-string-to-length(//short_value, '0', 12)" /> </xsl:template> The input XML like: <test> <short_value>123</short_value> </test> will give as a result in this case: 123000000000 By the way, this function only works with XSLT2!Reference: right-pad values with XSLT from our JCG partner Pascal Alma at the The Pragmatic Integrator blog....
java-logo

Java Tutorial Through Katas: Mars Rover

A programming kata is an exercise which helps a programmer hone his skills through practice and repetition. This article is part of the series Java Tutorial Through Katas. The article assumes that the reader already has experience with Java, that he is familiar with the basics of unit tests and that he knows how to run them from his favorite IDE (mine is IntelliJ IDEA). Tests that prove that the solution is correct are displayed below. Recommended way to solve this kata is to use test-driven development approach (write the implementation for the first test, confirm that it passes and move to the next). Once all of the tests pass, the kata can be considered solved. For more information about best practices, please read the Test Driven Development (TDD): Best Practices Using Java Examples. One possible solution is provided below the tests. Try to solve the kata by yourself first. Mars Rover Develop an api that moves a rover around on a grid. Rules:You are given the initial starting point (x,y) of a rover and the direction (N,S,E,W) it is facing. The rover receives a character array of commands. Implement commands that move the rover forward/backward (f,b). Implement commands that turn the rover left/right (l,r). Implement wrapping from one edge of the grid to another. (planets are spheres after all) Implement obstacle detection before each move to a new square. If a given sequence of commands encounters an obstacle, the rover moves up to the last possible point and reports the obstacle.Tests Following is a set of unit tests that can be used to solve this kata in the TDD fashion. package com.technologyconversations.kata.marsrover;import org.junit.Before; import org.junit.Test;import java.util.ArrayList; import java.util.Arrays; import java.util.List;import static org.assertj.core.api.Assertions.*;/* Source: http://dallashackclub.com/roverDevelop an api that moves a rover around on a grid. * You are given the initial starting point (x,y) of a rover and the direction (N,S,E,W) it is facing. * - The rover receives a character array of commands. * - Implement commands that move the rover forward/backward (f,b). * - Implement commands that turn the rover left/right (l,r). * - Implement wrapping from one edge of the grid to another. (planets are spheres after all) * - Implement obstacle detection before each move to a new square. * If a given sequence of commands encounters an obstacle, the rover moves up to the last possible point and reports the obstacle. */ public class RoverSpec {private Rover rover; private Coordinates roverCoordinates; private final Direction direction = Direction.NORTH; private Point x; private Point y; private List<Obstacle> obstacles;@Before public void beforeRoverTest() { x = new Point(1, 9); y = new Point(2, 9); obstacles = new ArrayList<Obstacle>(); roverCoordinates = new Coordinates(x, y, direction, obstacles); rover = new Rover(roverCoordinates); }@Test public void newInstanceShouldSetRoverCoordinatesAndDirection() { assertThat(rover.getCoordinates()).isEqualToComparingFieldByField(roverCoordinates); }@Test public void receiveSingleCommandShouldMoveForwardWhenCommandIsF() throws Exception { int expected = y.getLocation() + 1; rover.receiveSingleCommand('F'); assertThat(rover.getCoordinates().getY().getLocation()).isEqualTo(expected); }@Test public void receiveSingleCommandShouldMoveBackwardWhenCommandIsB() throws Exception { int expected = y.getLocation() - 1; rover.receiveSingleCommand('B'); assertThat(rover.getCoordinates().getY().getLocation()).isEqualTo(expected); }@Test public void receiveSingleCommandShouldTurnLeftWhenCommandIsL() throws Exception { rover.receiveSingleCommand('L'); assertThat(rover.getCoordinates().getDirection()).isEqualTo(Direction.WEST); }@Test public void receiveSingleCommandShouldTurnRightWhenCommandIsR() throws Exception { rover.receiveSingleCommand('R'); assertThat(rover.getCoordinates().getDirection()).isEqualTo(Direction.EAST); }@Test public void receiveSingleCommandShouldIgnoreCase() throws Exception { rover.receiveSingleCommand('r'); assertThat(rover.getCoordinates().getDirection()).isEqualTo(Direction.EAST); }@Test(expected = Exception.class) public void receiveSingleCommandShouldThrowExceptionWhenCommandIsUnknown() throws Exception { rover.receiveSingleCommand('X'); }@Test public void receiveCommandsShouldBeAbleToReceiveMultipleCommands() throws Exception { int expected = x.getLocation() + 1; rover.receiveCommands("RFR"); assertThat(rover.getCoordinates().getX().getLocation()).isEqualTo(expected); assertThat(rover.getCoordinates().getDirection()).isEqualTo(Direction.SOUTH); }@Test public void receiveCommandShouldWhatFromOneEdgeOfTheGridToAnother() throws Exception { int expected = x.getMaxLocation() + x.getLocation() - 2; rover.receiveCommands("LFFF"); assertThat(rover.getCoordinates().getX().getLocation()).isEqualTo(expected); }@Test public void receiveCommandsShouldStopWhenObstacleIsFound() throws Exception { int expected = x.getLocation() + 1; rover.getCoordinates().setObstacles(Arrays.asList(new Obstacle(expected + 1, y.getLocation()))); rover.getCoordinates().setDirection(Direction.EAST); rover.receiveCommands("FFFRF"); assertThat(rover.getCoordinates().getX().getLocation()).isEqualTo(expected); assertThat(rover.getCoordinates().getDirection()).isEqualTo(Direction.EAST); }@Test public void positionShouldReturnXYAndDirection() throws Exception { rover.receiveCommands("LFFFRFF"); assertThat(rover.getPosition()).isEqualTo("8 X 4 N"); }@Test public void positionShouldReturnNokWhenObstacleIsFound() throws Exception { rover.getCoordinates().setObstacles(Arrays.asList(new Obstacle(x.getLocation() + 1, y.getLocation()))); rover.getCoordinates().setDirection(Direction.EAST); rover.receiveCommands("F"); assertThat(rover.getPosition()).endsWith(" NOK"); }} One possible solution is following. package com.technologyconversations.kata.marsrover;/* Method receiveCommands should be used to transmit commands to the rover. */ public class Rover {private Coordinates coordinates; public void setCoordinates(Coordinates value) { coordinates = value; } public Coordinates getCoordinates() { return coordinates; }public Rover(Coordinates coordinatesValue) { setCoordinates(coordinatesValue); }public void receiveCommands(String commands) throws Exception { for (char command : commands.toCharArray()) { if (!receiveSingleCommand(command)) { break; } } }public boolean receiveSingleCommand(char command) throws Exception { switch(Character.toUpperCase(command)) { case 'F': return getCoordinates().moveForward(); case 'B': return getCoordinates().moveBackward(); case 'L': getCoordinates().changeDirectionLeft(); return true; case 'R': getCoordinates().changeDirectionRight(); return true; default: throw new Exception("Command " + command + " is unknown."); } }public String getPosition() { return getCoordinates().toString(); }} Full source is located in the GitHub repo [https://github.com/vfarcic/mars-rover-kata-java). Above code presents only the code of the main class. There are several other classes/objects with their corresponding specification. Besides tests and implementation, repository includes build.gradle that can be used, among other things, to download AssertJ dependencies and run tests README.md contains short instructions how to set up the project. What was your solution? Post it as a comment so that we can compare different ways to solve this kata.Reference: Java Tutorial Through Katas: Mars Rover from our JCG partner Viktor Farcic at the Technology conversations blog....
software-development-2-logo

Why Your IoT Product Strategy Needs to Include Open Source

For the last two years, I have been talking about why open source will be critical to the success of the Internet of Things.  The current state of IoT/M2M is a lot of propriertary platforms and protocols. This can’t last and won’t win in the long term. This week during a webinar about the new Vorto IoT project from Bosch, I saw the best illustration of why companies that don’t include open source in their product strategy will eventually fail.  Check out this slide about the Bosch IoT Platform Strategy:        Bosch is one of the leading industrial companies in the IoT industry. They definitely get it and their analysis of the market is definitely worth considering. Consider each of their assumptions very carefully:2-5 major IoTS platforms (in next 5-7 years) – At the start of every new technology innovation there are lots of different platforms that are developed. However, overtime the industry consolidates around 2-5 key providers, ex databases, web servers, Java servers, etc.   This will happen in IoT. At least one of them will be Open Source – Open source has proven to be a provider of production quality software. In many markets, open source is the dominant supplier.  There is no reason to believe that this will not be the case in IoT. Bosch not able to develop one of these proprietary platforms alone and customers/partners would not accept it – Developing a proprietary platform takes a LOT of development resources but more importantly a LOT of marketing, sales, and business development resources. Even a company as large as Bosch recognizes this fact. Companies like Google, Apple, IBM, SAP, Oracle, Salesforce, Microsoft plus some others may have the resources and skills to compete but most companies don’t. Most companies will need to identify their key value add for IoT. Providing a platform is not going to be a value add that is sustainable in the long-term. No risk/dependency on proprietary 3rd party platform – Bosch and other companies still need an IoT platform, so they are making a make vs buy decision. If they decide to not Make  (see #3) then the buy decision comes down to a proprietary platform or an open source platform. Considering #2, deciding to go with an open source platform provides a lot more flexibility and less risk of being dependent on another company.If you are setting a product strategy for an IoT product, you will be faced with a Make vs Buy decision.  I think Bosch makes a pretty compelling case for open source. More importantly, Bosch has decided to be a leader in open source, ensuring they have a significant role and stake in the success. Reason #2 The other reason open source is going to win is captured in by Matt Asay in his recent article. The answer of course is: Developers.  As Matt points out ‘Developers aren’t going to go for proprietary standards.’  And as Matt points out, developers are attracted to code:But let’s be clear: None of these companies lining up to join this or that foundation will prove dispositive in cementing any particular standard as theopen source standard. Developers do that. And developers are attracted by tools and platforms that make them more productive, fast. Getting a marquee list of donors to a foundation is meaningless if the foundation doesn’t generate code that appeals to developers.This is why what we are doing at Eclipse IoT is so important. We have code, sandbox servers and tutorials to make it easy for developers to get start with IoT. It is clear code and openness will win in IoT. Join us in creating an amazing IoT open source community.Reference: Why Your IoT Product Strategy Needs to Include Open Source from our JCG partner Ian Skerrett at the Ian Skerrett’s blog blog....
career-logo

What Happens When a Contractor Wants to Go Full time

This just happened to me recently.  I have been looking for a job actively for the last six months.  One of the major questions I had were if I wanted to stay in a government contractor firm or go full time in a private company.  With contracting, one knows when is the last day.  On the other hand, I know there is no plan to dump me by a certain date.  That may be too harsh but most contracting firms just do not have the money to keep an employee that is not billing to some account besides overhead.         The Real Problem One of the great things about being a contractor is that about every five years or so, one is doing something different.  It is exciting and one learns a lot.  The problem with that is you get a Senior Developer with four or three years of this and that.  I have become a jack-of-all-trades-and-a-master-of-none developer.  See where this is going?  I get turned down by companies that want ten years experience on a certain technology.  I simply do not have that kind of experience.  The only companies that get excited about that kind of experience were really only contracting companies with “long term” contracts of six months plus.  I am working on a five year contract that just got a six month extension and I have benefits with that job.  Can you give me that kind of job?  The answer was “No.” Solution After talking with one of the many recruiters that I had.  I really enjoyed working with him.  One of the best recruiters I have ever had.  No, he did not land me my new job but I could not have done it without him.  If you are in the market and know Java, please contact me and I will get you his information.  If he cannot help, he will know someone that does.  We worked out a strategy to convince managers that I was worth the risk.  I distilled that talk into the following things:I pick up technology quick – As a contractor, when I get into a new contract, I am already behind.  If I do not understand what is going on, the customer will not be happy.  If the customer is not happy, they may start asking for someone else.  Except for four to six months, I have been doing this my entire career so I learn quick.  For example, when I started learning Primefaces, I made a custom drag and drop interface in a week.  Ask another developer how hard that is. I have seen what does not work – My varied experience is a benefit here.  I have seen what does and does not work.  One may not be doing it the best way possible.  Ask me during the interview how I would do things given the situation.  I will answer a few questions like that but unless I volunteer, one is coming closer to “pay for it” territory. I am cheaper than one thinks – Sure I am asking for a lot but I have never been in a job where software development was my only thing to do.  I have stood up and maintained continuous integration, bug tracking, wiki and software repository servers.  Start doing the math and I am getting to be pretty cheap. I have passion – I love software development.  I like learning the “problem space” and developing a solution to the problem.  I am so eager to learn that I will try different technologies to see what works.  No, I do not have ten years in Java EE, that is because I was fulfilling requirements in the best way possible.Moral of the Story In the end, I decided to take a job with another government contractor.  Everything about the job felt right.  However, if one is looking for a Java developer and finds a resume that has a lot of different technologies but not enough of one to meet your experience requirements, do not dump it.  Give him or her a call.  That might be the one that fits the position better than one hoped.Reference: What Happens When a Contractor Wants to Go Full time from our JCG partner Daryl Mathison at the Daryl Mathison’s Java Blog blog....
java-logo

The dreaded DefaultAbstractHelperImpl

A while ago, we have published this fun game we like to call Spring API Bingo. It is a tribute and flattery to Spring’s immense creativeness when forming meaningful class names likeFactoryAdvisorAdapterHandlerLoader ContainerPreTranslatorInfoDisposable BeanFactoryDestinationResolver LocalPersistenceManagerFactoryBeanTwo of the above classes actually exist. Can you spot them? If no, play Spring API Bingo! Clearly, the Spring API suffers from having… To name things There are only two hard problems in computer science. Cache invalidation, naming things, and off-by-one errors – Tim Bray quoting Phil Karlton There are a couple of these prefixes or suffixes that are just hard to get rid of in Java software. Consider this recent discussion on Twitter, that inevitably lead to an (very) interesting discussion: Having Interface: PaymentService Implementation: PaymentServiceImpl The test should be called PaymentServiceImplTest not PaymentServiceTest — Tom Bujok (@tombujok) October 8, 2014Yes, the Impl suffix is an interesting topic. Why do we have it, and why do we keep naming things that way? Specification vs. body Java is a quirky language. At the time it was invented, object orientation was a hot topic. But procedural languages had interesting features as well. One very interesting language at the time was Ada (and also PL/SQL, which was largely derived from Ada). Ada (like PL/SQL) reasonably organises procedures and functions in packages, which come in two flavours: specification and body. From the wikipedia example: -- Specification package Example is procedure Print_and_Increment (j: in out Number); end Example;-- Body package body Example is procedure Print_and_Increment (j: in out Number) is begin -- [...] end Print_and_Increment; begin -- [...] end Example; You always have to do this, and the two things are named exactly the same: Example. And they’re stored in two different files called Example.ads (ad for Ada and s for specification) and Example.adb (b for body). PL/SQL followed suit and names package files Example.pks and Example.pkb with pk for Package. Java went a different way mainly because of polymorphism and because of the way classes work:Classes are both specification AND body in one Interfaces cannot be named the same as their implementing classes (mostly, because there are many implementations, of course)In particular, classes can be a hybrid of spec-only, with a partial body (when they’re abstract), and full spec and body (when they’re concrete). How this translates to naming in Java Not everyone appreciates clean separation of specs and body, and this can certainly be debated. But when you’re in that Ada-esque mind set, then you probably want one interface for every class, at least wherever API is exposed. We’re doing the same for jOOQ, where we have established the following policy to name things: *Impl All implementations (bodies) that are in a 1:1 relationship with a corresponding interface are suffixed Impl. If ever possible, we try to keep those implementations package-private and thus sealed in the org.jooq.impl package. Examples are:Cursor and it corresponding CursorImpl DAO and it corresponding DAOImpl Record and it corresponding RecordImplThis strict naming scheme makes it immediately clear, which one is the interface (and thus public API), and which one is the implementation. We wish Java were more like Ada with this respect, but we have polymorphism, which is great, and… Abstract* … and it leads to reusing code in base classes. As we all know, common base classes should (almost) always be abstract. Simply because they’re most often incomplete implementations (bodies) of their corresponding specification. Thus, we have a lot of partial implementations that are also in a 1:1 relationship with a corresponding interface, and we prefix them with Abstract. Most often, these partial implementations are also package-private and sealed in the org.jooq.impl package. Examples are:Field and it corresponding AbstractField Query and it corresponding AbstractQuery ResultQuery and it corresponding AbstractResultQueryIn particular, ResultQuery is an interface that extends Query, and thus AbstractResultQuery is a partial implementation that extends the AbstractQuery, which is also a partial implementation. Having partial implementations makes perfect sense in our API, because our API is an internal DSL (Domain-Specific Language) and thus has thousands of methods that are always the same, no matter what the concrete Field really does – e.g. Substring Default* We do everything API related with interfaces. This has proven highly effective already in popular Java SE APIs, such as:Collections Streams JDBC DOMWe also do everything SPI (Service Provider Interface) related with interfaces. There is one essential difference between APIs and SPIs in terms of API evolution:APIs are consumed by users, hardly implemented SPIs are implemented by users, hardly consumedIf you’re not developing the JDK (and thus don’t have completely mad backwards-compatibility rules), you’re probably mostly safe adding new methods to API interfaces. In fact, we do so in every minor release as we do not expect anyone to implement our DSL (who’d want to implement Field‘s 286 methods, or DSL‘s 677 methods. That’s mad!) But SPIs are different. Whenever you provide your user with SPIs, such as anything suffixed *Listener or *Provider, you can’t just simply add new methods to them – at least not prior to Java 8, as that would break implementations, and there are many of them. Well. We still do it, because we don’t have those JDK backwards-compatibility rules. We have more relaxed ones. But we suggest our users do not implement the interfaces directly themselves, but extend a Default implementation instead, which is empty. For instance ExecuteListener and the corresponding DefaultExecuteListener: public interface ExecuteListener { void start(ExecuteContext ctx); void renderStart(ExecuteContext ctx); // [...] }public class DefaultExecuteListener implements ExecuteListener {@Override public void start(ExecuteContext ctx) {}@Override public void renderStart(ExecuteContext ctx) {}// [...] } So, Default* is a prefix that is commonly used to provide a single public implementation that API consumers can use and instantiate, or SPI implementors can extend – without risking backwards-compatibility issues. It’s pretty much a workaround for Java 6 / 7’s lack of interface default methods, which is why the prefix naming is even more appropriate. Java 8 Version of this rule In fact, this practice makes it evident that a “good” rule to specify Java-8 compatible SPIs is to use interfaces and to make all methods default with an empty body. If jOOQ didn’t support Java 6, we’d probably specify our ExecuteListener like this: public interface ExecuteListener { default void start(ExecuteContext ctx) {} default void renderStart(ExecuteContext ctx) {} // [...] } *Utils or *Helper OK, so here’s one for the mock/testing/coverage experts and aficionados out there. It’s TOTALLY OK to have a “dump” for all sorts of static utility methods. I mean, of course you could be a member of the object-orientation police. But… Please. Don’t be “that guy”! So, there are various techniques of identifying utility classes. Ideally, you take a naming convention and then stick to it. E.g. *Utils. From our perspective, ideally you’d even just dump all utility methods that are not stricly bound to a very specific domain in a single class, because frankly, when did you last appreciate having to go through millions of classes to find that utility method? Never. We have org.jooq.impl.Utils. Why? Because it’ll allow you to do: import static org.jooq.impl.Utils.*; This then almost feels as if you had something like “top-level functions” throughout your application. “global” functions. Which we think is a nice thing. And we totally don’t buy the “we can’t mock this” argument, so don’t even try starting a discussion Discussion … or, in fact, let’s do start a discussion. What are your techniques, and why? Here are a couple of reactions to Tom Bujok’s original Tweet, to help get you started: @tombujok No. PaymentServiceImplTestImpl! — Konrad Malawski (@ktosopl) October 8, 2014@tombujok get rid of the interface — Simon Martinelli (@simas_ch) October 8, 2014@tombujok Impl everything! — Bartosz Majsak (@majson) October 8, 2014@tombujok @lukaseder @ktosopl root cause is the class should *not* be called *Impl, but I know you were trolling us all the time anyway — Peter Kofler (@codecopkofler) October 9, 2014Let’s go !Reference: The dreaded DefaultAbstractHelperImpl from our JCG partner Lukas Eder at the JAVA, SQL, AND JOOQ blog....
java-interview-questions-answers

Poking around your REST application with a scriptable endpoint

I love the fact that JDK comes with a ScriptEngine. It’s so flexible when you want to evaluate and troubleshoot your application that’s already deployed in an server environment. Add this REST endpoint into a Java EE app, and it will give you instant access to internal states of the app.             package myrestapp;import java.io.StringReader; import java.util.logging.Logger; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Context;/** * Give instant access to your internal application with dynamic scripting. * * <p>Example script: * <pre> * "sc" + servletContext + ", req=" + request; * </pre> * * <p>Example2 * <pre> * names = servletContext.getAttributeNames(); * while(names.hasMoreElements()) { * name = names.nextElement(); * println(name); * } * </pre> */ @Path("script") public class ScriptResource { private static final Logger logger = Logger.getLogger(ScriptResource.class.getName()); @Context private ServletContext servletContext; @POST public String script(@Context HttpServletRequest request, String scriptText) throws Exception { String engineName = "JavaScript"; ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(engineName); logger.info("Running script text length=" + scriptText.length() + ", engine=" + engine); Object result = null; try (StringReader reader = new StringReader(scriptText)) { Bindings bindings = engine.createBindings(); bindings.put("servletContext", servletContext); bindings.put("request", request); result = engine.eval(reader, bindings); } logger.info("Result " + result); return "" + result; } } Notice that I gave couple JavaScript examples in the comment area already. You will have access to two binding variables that should give you full access to many internal components of your application. Need an UI to test out this endpoint? How about give the “Advance Rest Client” Chrome Extension a try? (Thanks to my co-worker’s Chris Griffin tips on this cool extension. It’s really handy tool to have!).Reference: Poking around your REST application with a scriptable endpoint from our JCG partner Zemian Deng at the A Programmer’s Journal blog....
java-logo

AssertJ > Fest > Hamcrest

I have previously blogged about Hamcrest, and using its assertThat methods in preference to JUnit’s Assert. However, I quickly after discovered FEST Assertions, and happily switched to it. It provides the same improved test readability and improves failure messages as Hamcrest, but has the extra benefit of enabling IDE auto completion, rather than having to search through package and class docs to find the right matcher. Unfortunately, Fest seems to not longer be actively developed. The last stable release of the 1.x branch, 1.4, was released way back in 2011, and the new 2.x branch never made it to a stable release and hasn’t had a commit since June 2013. Enter AssertJ… Assert J AssertJ is a fork of Fest Assert, and seems to provide all the benefits plus a bunch of new features. Collections For example, it has all the nifty collections handling I so liked from Fest: List<String> stringList = Lists.newArrayList("A", "B", "C"); assertThat(stringList).contains("A"); //true assertThat(stringList).doesNotContain("D"); //true assertThat(stringList).containsOnly("A"); //false assertThat(stringList).containsExactly("A", "C", "B"); //false assertThat(stringList).containsExactly("A", "B", "C"); //true Collect all errors before failing It also has the ability to catch all failures before failing. For example, the above eample would fail as the first failed assumpion. The below example allows you to see all failed assertions: List<String> stringList = Lists.newArrayList("A", "B", "C"); SoftAssertions softly = new SoftAssertions(); softly.assertThat(stringList).contains("A"); //true softly.assertThat(stringList).containsOnly("A"); //false softly.assertThat(stringList).containsExactly("A", "C", "B"); //false softly.assertThat(stringList).containsExactly("A", "B", "C"); //true // Don't forget to call SoftAssertions global verification! softly.assertAll(); And results in a message like this: The following 2 assertions failed: 1) Expecting: <["A", "B", "C"]> to contain only: <["A"]> elements not found: <[]> and elements not expected: <["B", "C"]> 2) Actual and expected have the same elements but not in the same order, at index 1 actual element was: <"B"> whereas expected element was: <"C"> Definitely worth a look. AssertJ core code and issue tracker are hosted on github.Reference: AssertJ > Fest > Hamcrest from our JCG partner Shaun Abram at the Shaun Abram’s blog blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close