What's New Here?

java-logo

Happy 8th Birthday Java!

It’s been another longer journey but yesterday, exactly two years, seven months, and eighteen days after the release of Java 7 we now have production-ready builds of Java 8 available for download! This new major release contains several new features and enhancements that increase the performance of existing applications, make it easier to develop applications for modern platforms, and increase maintainability of code. Here is a brief overview about my personal highlights.           What’s new overall?Several areas of the language itself, profiles, security, JavaFX, tooling, scripting, Date and Time, concurrency and a more or less lengthy list of things changed or got added. More than 8.000 bugs and features have been addressed and be incorporated into this release. The complete list can be found in the official release-notes. Java Mission Control 5.3 One of the highlights is the new Java Mission Control release. It is bundled with the JDK and comes with a separate list of enhancements in it’s own release-notes. Find the complete documentation as part of the official Java SE 8 documentation. Compact Profiles The newly introduced profiles enable reduced memory footprint for applications that do not require the entire Java platform. The javac compiler has a -profile option, which allows the application to be compiled using one of the supported profiles. The three are additive layers, so that each Profile contains all of the APIs in profiles smaller than itself. The compact profiles feature is useful in small devices with less hardware power. And yes, I am personally still totally frustrated that Jigsaw will probably never see the light. But I am happy to be proven wrong on that. Java Date-Time Packages Thank you Stephen! Thank you for this great piece of work. TimesTen is the new Date and Time API in Java 8. Clear, Fluent, Immutable, Extensible. There are two basic ways to represent time. One way represents time in human terms, referred to as human time, such as year, month, day, hour, minute and second. The other way, machine time, measures time continuously along a timeline from an origin, called the epoch, in nanosecond resolution. See the official tutorial for more examples and usages. Good Bye PermGen! Removal of PermGen. Full stop. It’s gone! YES! Security Enhancements More and stronger Algorithms, TLS 1.2 default and further enhancements. Nashorn Java 8 is co-bundled with the Nashorn, which is an implementation of the ECMAScript Edition 5.1 Language Specification. See the user-guide for all the details. Happy 8th Birthday Java!Congratulations to everybody involved. Especially the Adopt-OpenJDK community which was driven by the London-Java-Community and supported the Date-Time efforts by providing tests.Reference: Happy 8th Birthday Java! from our JCG partner Markus Eisele at the Enterprise Software Development with Java blog....
devops-logo

Frustration-Driven Development – Towards DevOps, Lean, Clojure

My wife has mentioned that she likes my passion for doing things right in software development. That made me thinking, why do I actually care so much and do not just enjoy the coding itself? It boils down to that I am not happy until my code is in production. Seeking the satisfaction of having my code used by and helping people while trying to eliminate all unnecessary mental drain is behind all the practices that I embrace and evangelize. It’s a drug I like to take often, in small doses.           practices = f(max(delivered value), min(mental energy)) So how does this relate to DevOps, Continuous Delivery, testing, single-piece-flow, Lean Startup, Clojure? It is simple. Build It Fast I care about DevOps and Continuous Delivery because they are about getting my stuff out as soon as possible. I love to build & ship, get it used right after finishing. Having my work sitting in a queue – for a code review, testing, deployment – is frustrating. I want to finish it, see it running, being used, and working well and put it off my brain so that i can focus on the next thing with a clear mind. That is why also single-piece-flow sounds so attractive to me. If my work is not deployed, used, and thus confirmed to be OK and useful, it is not finished. It may come back due to defects and I have no proof that it actually was worthwhile. The lack of the it’s-working-and-valuable gratification and the mental drain of having multiple unfinished things (see Zeigarnik effect) is frustrating. Build The Right Thing For the same reason I care about users and building the right thing, i.e. something that they actually will use and benefit from, while also making it as user-friendly as possible. A tight contact with users/business, A/B testing and other Lean Startup techniques, user monitoring are some of great tools and practices that help us ensure that we indeed build the right thing. I am a very skeptical person. History has shown many times that we are terrible at predicting what users need / want so I don’t believe in the value of a product until I see data that prove it. As Marry Poppendieck famously put it, “Show me the money!” I’m convinced that development is primarily about discovery – both of value (for users) and of the technical (challenges and solutions). The degree of uncertainty may vary but it is always there. It is frustrating to see projects following blindly the course set by an “omniscient” stakeholder / PM / architect. Build It Right I also care a lot about testing, TDD, and the “build quality in” of lean. I want to get the fruit of my work to users to improve their lives ASAP and then delete it from my brain. But defects make it come back. So without good quality, I may never know whether I am actually finished or not. Context switching and re-loading the previous work into my mind is mentally tiring. Also, I dislike testing phases and code freeze, they are obstacles – not just rocks, but mountains – on the path from code to value. Therefore good quality built in, automated tests, and all the Continuous Delivery practices are crucial. I crave for improving people’s (users’) lives. I want to have the satisfaction of this drug of mine often and quickly. Struggling with spaghetti legacy code is slowing me down. Therefore I care about good and simple architecture and design (DRY, SRP and all the stuff). I care a lot for refactoring; a true professional aims for long-term sustainable high development speed over quick fixes. I have been too often on the bad end of “let’s hack this quickly now and pay the price later.” Use The Best Tools My love for producing value for users also explains why I have grown to dislike Java and like Clojure (though it can be generalized to other languages, f.ex. C# vs. F#). In Java, it feels very wasteful to keep repeating myself due to weak abstractions and to write heaps of boilerplate code (all those getters, Comparators etc.) Clojure is much more powerful, with abstractions that make it easy to “say things once” such as higher-order functions and multimethods, and is malleable to fit the problem at hand like a glove (thanks to macros etc.). Java, on the other hand, forces me to fit the problem to the language and to write loads of boilerplate code. Also, in Clojure, REPL enables truly interactive and exploratory development, with an extremely short feedback loop and thus helps me go fast. My favorite example of the Clojure-Java dichotomy is a map-reduce job written using the Clojure library Cascalog vs. what it would look like in plain Hadoop Java. (It is a little pears-and-apples comparison but demonstrates the point of 90% business code vs. 90% boilerplate code). For similar reasons, when I have to use a framework or a library, I prefer one that actually makes my life simpler and does not make me fight it all the time. (So no to JSF.) People Matter Too Organizations based on trust, with good inter-personal relationships, are the most conductive for creativity and productivity. I therefore prefer synergistic/chaordic organizations (over analytic or, Cthulhu save us, toxic ones) and good teams. Few Historical Examples Project Gnomes: This was a technically great project, with DevOps, full control over everything, frequent releases. Yet it frustrated me because I did not believe in the value of the product being built. Project Blackjack: On the positive side, this was a very business/users-oriented project driven by actual needs of real users. But it was in the stone age of development, with outdated technologies, hosting and thus all environment changes outsourced to a less-than-flexible international company with changes taking from days to months, and the development was little too much focused on risk. Why Should The Business Care? The business does care about making money, not about making me happy. So why should they care about my frustration? Why should they care about starting to get value from IT ASAP? About verifying that an investment of IT resources is really worth it? About avoiding defects and downtimes (and lost customers and sales)? Ehm, do I need to answer? (Also, happy developers = productive developers so yes, they should care about our satisfaction and frustrations.) Summary For me, development is essentially about maximizing value <=> minimizing the idea-to-”cash” time. This naturally leads to DevOps, Continuous Delivery, lean startup practices and thinking, “build the quality in,” single piece flow, and it drives my choice of tools and languages. Psychologically, it is about maximizing gratification while minimizing mental drain, i.e. the expenditure of mental energy.Reference: Frustration-Driven Development – Towards DevOps, Lean, Clojure from our JCG partner Jakub Holy at the The Holy Java blog....
akka-logo

Akka Toolkit 2.3 released

The release of 2.3.0 version of Akka toolkit was recently announced. Akka is a very useful toolkit and runtime for building highly concurrent, distributed, and fault tolerant event-driven applications on the JVM. It is distributed and provides high-level abstractions like Actors, Futures and STM. Its new release comes eight months after the 2.2.0 release and brings along new features. One of the most important ones is that now Actor and FSM support Java 8 lamda expressions (still in experimental mode). The syntax used is very close to Scala’s pattern matching.   Other important features are :Cluster nodes can now come back after being in an unreachable state. So cluster becomes more resilient transient network failures. Stateful actors can be distributed to the cluster when not fitting in one machine, without knowing their actual location, which may change over time. This feature is the sharding of actors. The experimental label is removed from Akka IO package, but with the Pipeline infrastructure is discontinued. The OSGi support has been reworked to make akka-actor an OSGi bundle.The most exciting new feature is Akka Persistence. In Akka Persistence the actors persist their internal state, so when restarted after a crash or after migration they can recover it. The actors actually persist their changes to a journal, so stateful actors can be recovered by replaying stored changes, rebuilding the actors’ internal state. Akka Persistence provides point-to-point communication channels with at-least-once message delivery semantics. There have been changes to the documentations so as to get started with the new release of the framework. ...
android-logo

Android App tutorial:Peg board game

I released in Github the source code of an app that can be used to play peg board. This app was published on the market some times ago and this is a new version. The app screenshots are shown below:                  There are some interesting aspects we can consider in this app and they are described below. It can be used as example how to integrate different elements like SlidingPaneLayoutfragments, event handling and so on.App structure The main android UI pattern used by the app is the Sliding Pane layout because we need to have the screen divided in two area: the main area is where we can play with our pegs and the other one that usually is closed is the menu. So the overall layout is: <android.support.v4.widget.SlidingPaneLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/sp" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/tilebkg" ><fragment android:id="@+id/pinMenu" android:name="com.survivingwithandroid.pegboard.fragment.MenuFragment" android:layout_width="200dp" android:layout_height="match_parent" android:layout_gravity="left" /><fragment android:id="@+id/pinTable" android:name="com.survivingwithandroid.pegboard.fragment.DreamPinTableFragment" android:layout_width="600dp" android:layout_height="match_parent" android:layout_gravity="right" android:layout_weight="1" /></android.support.v4.widget.SlidingPaneLayout> The result is shown below:As you can notice the SlidingPaneLayout handles two fragments DreamPinTableFragment and MenuFragment. DreamPinTableFragment takes care of creating the table and handling the user touch so that the user can place pins on it, while the MenuFragment handles the some options like choosing the pin colors, save the work and so on. Custom Layout with ViewGroup The peg board is implemented as custom layout. The class that implements it is called PinTableView that extends ViewGroup. This custom layout takes care of dividing the UI screen in small cells that corresponds to the holes where the pegs are placed. The app screen is treated as a table divided in rows and columns. The first method called by DreamPinTableFragment is disposePin. This method calculates the number or rows and columns and initializes the table: public int[] disposePins(int width, int height, int dotSize) {this.dotSize = dotSize;numRow = height / dotSize + 1; numCol = width / dotSize + 1;int[] dotColors = Pin.createDotArray(dotSize, true);for (int r=0; r < numRow ; r++) { for (int c=0; c < numCol; c++) { PinImageView pinImg = new PinImageView(getContext(), r, c); this.addView(pinImg); } }return new int[]{numRow, numCol}; } Notice that in this method we add PinImageView (another custom view) to the layout (line…) giving to them the right row and column number. Then in onLayout method we traverse the list of childs (we added previously) and start placing them in the right position. In this case we need to calculate the x and y coordinates in real pixel, this is simple once we know the row and column number and the cell pixel size: @Override protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) { int childCount = getChildCount();for (int i=0; i < childCount; i++) { PinImageView pinImg = (PinImageView) getChildAt(i);//int left = pinImg.getCol() * dotSize + dotSize * (pinImg.getType() == PinImageView.COLOR_COMMANDS || pinImg.getType() == PinImageView.DELETE ? 0 : 1); int left = pinImg.getCol() * dotSize; //int top = pinImg.getRow() * dotSize + dotSize * (pinImg.getType() == PinImageView.COLOR_COMMANDS || pinImg.getType() == PinImageView.DELETE ? 0 : 1); int top = pinImg.getRow() * dotSize; int right = left + dotSize ; int bottom = top + dotSize ;pinImg.layout(left, top, right, bottom); }} In this way, we created an empty board that looks like the picture shown below:Custom imageView: PinImageView As we saw before, we place in our layout a custom ImageView childs. PinImageView is a simple class that extends ImageView and represents a single Peg (or pin as we prefer to call it). This class has an internal state that holds the type of the peg it represents and implements some kind of animation to make the UI more attractive. public class PinImageView extends ImageView { private int row; private int col; private int xSize; private int ySize; private int stato = -1; private Context ctx; private int currentPinId;public PinImageView(Context context, int row, int col) { super(context); this.ctx = context; this.row = row; this.col = col; //this.parent = parent;// Load image Drawable d = getResources().getDrawable(TableConfig.pinBackground); setImageDrawable(d); xSize = this.getWidth(); ySize = this.getHeight(); this.currentPinId = TableConfig.pinBackground;} ... class AnimView implements Runnable {Animation anim; Drawable d;public AnimView(Animation anim, Drawable d) { this.anim = anim; this.d = d; } @Override public void run() { anim.setAnimationListener(new Animation.AnimationListener() {@Override public void onAnimationStart(Animation animation) { TableConfig.playSound(PinImageView.this.ctx); }@Override public void onAnimationRepeat(Animation animation) {}@Override public void onAnimationEnd(Animation animation) { setImageDrawable(d); PinImageView.this.setVisibility(View.VISIBLE); } });PinImageView.this.startAnimation(anim); }} } Handle user touch: OnTouchEvent and OnTouchListener The next step is handling the user touch. We define that DreamPinTableFragment listens to the events triggered when user touches the screen. We want to place a peg in the position where user touched the screen: @Override public boolean onTouch(View v, MotionEvent event) {int x = (int) event.getX() ; int y = (int) event.getY() ;if (event.getAction() == MotionEvent.ACTION_DOWN) { pinsTable.changePinColor(x, y); return true; } else if (event.getAction() == MotionEvent.ACTION_MOVE) { pinsTable.changePinColor(x, y); return true; }return false;} and then we delegate to the PinTableView to handle the event passing the coordinates: public void changePinColor(int x, int y) { int row = getRow(y); int col = getColumn(x);PinImageView pinImg = (PinImageView) getChildAt(col + ( row * numCol )); if (pinImg != null) { pinImg.setPinColor(currentColor);} } Knowing the x and y coordinates we can calculate the corresponding row and column and set the peg with the right color. App Menu As we explained before the app has a menu where user can select the pincolor, save the work or change the table background. The class that handles the menu is called MenuFragment. This is very simple class, it just notifies to the main activity the events triggered when user selects a menu item. In turn, the main activity handle this event informing the other fragment when these event regards pegs or some actions that have to be taken on the table. The MenuFragment defines an interface (a listener) that we have to implement when we want to have information on the events occurred in the menu: public static interface MenuEventListener { public void onPinSelected(int pinId); public void onClearSelected(); public void onSaveSelected(); public void onBackgroundSelected(); } So the main activity: public class DreamPinsActivity extends Activity implements MenuFragment.MenuEventListener { .... @Override public void onPinSelected(int pinId) {pinTableFrag.setCurrentPin(pinId); closeMenu(); }@Override public void onClearSelected() { ... }@Override public void onSaveSelected() { closeMenu(); ... }public void onBackgroundSelected() { ... } } Save layout as image The last aspect we want to cover is saving the layout as image. We can implement it in this way: in the PinsTableView: public Bitmap createBitmap() { Bitmap b = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.RGB_565); Canvas c = new Canvas(b);this.draw(c);return b; } where we create an empty bitmap having the same size of the screen and then draw on the corresponding Canvas. Once we have our bitmap that contains the screenshot of the app screen we save it in a file: OutputStream outStream = context.getContentResolver() .openOutputStream(uri);b.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close();Source code availabe @ github  Reference: Android App tutorial:Peg board game from our JCG partner Francesco Azzola at the Surviving w/ Android blog. ...
java-logo

Joy of Coding… and mutation testing in Java

For many years now it has been good practice to write unit tests for your source-code. And also to use test coverage reporting to see how much of your code is covered by tests. Although line + branch coverage reporting is quite useful, it doesn’t tell you how good your unit tests actually are. Hence it’s even possibly to achieve 100% coverage without even a single assert in your tests. Being interested in better ways of testing I attended the “Mutation testing” workshop during this years Joy of Coding conference. Mutation testing is a radical different approach of executing and analyzing the result and coverage of your unit tests. Instead of measuring how much of your code is “accessed from” your unit tests it determines how much of your code is actually “tested by” your unit tests. So how does it actually work The basic idea behind mutation testing is to make a small change (a mutation) to the (byte) code and then execute your tests to see if it is detected by the unit tests. Possible mutations are altering a “>” into “>=“, replacing “++” with “--” and removing “void” method invocations. Each mutation therefor creates an altered version of your code called a “mutant”. Prior to the actual mutation testing our unit tests first need to be executed against the original code to see if no tests are failing. Then the unit tests will be run for each “mutant” (making it possibly very time consuming) the see if:the mutant is detected by our unit tests: the tests fails and therefore the “mutant” is considered “killed”. the mutant remains unnoticed by our unit tests: the tests did “not” fail (the “mutant” is considered “alive”) and didn’t notice the mutation; this means that the “mutant” is actually “not” tested (uncovered) by the unit tests.An example of mutation testing So how does this “mutation testing” actually work? Consider the following method: public String foo(int i) { if ( i >= 0 ) { return "foo"; } else { return "bar"; } } And the fact that the unit tests consist of only one test method:@Test public void testFoo() { testee.foo(0); } What if we would create a “mutant” of our code in which “>=” is altered into “>“? We would expect our unit test method to detect this, right? Well in this case it’s not since the test method doesn’t contain a single assertion. What is we would change a “testFoo” method to include an assertion: @Test public void testFoo() { String result = testee.foo(0); assertEquals("foo", result); } Now our unit test method will fail and detect (aka “killed) the “mutant” code. Besides altering “>=” into “>” additional “mutants” could be created:the first return method could be altered to return null (instead of "foo"); this “mutant” is “killed” by the “testFoo” method due to the “assertEquals” statement but remains unnoticed the original “testFoo” method (without any assertions). the second return method can be altered to return null (instead of "bar"); since no test method actually covers this execution path this “mutant” will remain unnoticed.NOTE: some mutation testing tooling (like PIT for Java) won’t even bother creating a “mutant” for the second return statement as it will never be covered by the unit tests (as detected by traditional line coverage). Equivalent mutations causing false-positives As apposed to traditional line + branch coverage, mutation coverage can possibly lead to false-positives. It could “incorrectly” report (a false-positive) that a “mutant” as “not” being detected by your unit tests. For instance consider the following Java code: public int someNonVoidMethod() { return 0; } public void foo() { int i = someNonVoidMethod(); // do more stuff with i } During mutation testing (using PIT Mutation testing with some “non”-default configuration) the following “mutant” could have been created: public int someNonVoidMethod() { return 0; } public void foo() { int i = 0; // do more stuff with i } The “int i = 0” statement in the “mutant” is functionally “equivalent” to the original code in which “someNonVoidMethod” returns 0. Such an “equivalent mutation” cannot be detected since the unit tests will (and should) not fail on it. And therefore it will be reported as being non-covered whereas it is actually a false-positive. When using PIT, a mutation testing framework for Java, “equivalent mutations” should, according to the documention, be minimal using the “default” set of mutators. For instance the “Non Void Method Call Mutator” of PIT causing the “int i = 0” equivalent mutation is disabled at default. Conclusion After participating in workshop, some additional investigation and playing around with PIT, I got really enthusiastic about using “mutation testing” in the near future (starting with new components) on my current project. As apposed to traditional coverage reporting the mutation test coverage actually measures the quality of your tests and cannot be fooled like traditional coverage reporting. In case you also got interested:check out this very funny presentation from Chris Rimmer about the basic concept of mutation testing. furthermore there’s an interesting article from a company called TheLadders using the PIT mutation testing tool. also theres an extensive article from Filip van Laenen about “mutation testing” in edition 108 of the overload magazine. last but not least there’s the documentation on the PIT mutation testing website.Reference: Joy of Coding… and mutation testing in Java from our JCG partner Emil Galen at the JDriven blog....
agile-logo

Estimation by stuffing things into boxes

I’ve started using an approach for software project estimation that so far is proving to be fairly transparent, quick and reliable. I’ve observed that within a reasonable degree of variation, most teams seems to complete about one “user-relevant task” per developer per calendar week. There are so many theoretical holes in my argument that there’s no point trying to cover them all. The funny thing is that it seems to work fairly well in practice. And to the degree that it’s dirty, it’s at least quick and dirty. The only thing I will address is that one of these “user relevant tasks” is smaller than a typical application feature. Most importantly: Most teams never get it right on the first try. Or they spend too long gold-plating everything. Or both. This article shows an example of estimating a fictive project: The Temporary Staffing System. The high-level scope Let’s say that our organization has come up with the following vision: For a temporary employment agent who wants to match candidates to client needs, the Temporary Staffing System is an interactive web application, which lets them register and match candidates and positions. Unlike competing systems this lets us share selective information with our clients. We come up with the following flow through the application:A new company wants to hire a skilled worker for a temporary position Administrative user adds the client details to the system Administrative user adds client logins to the system (perhaps we also should let the clients log in with LinkedIn etc?) Client logs into the application and completes new position description, including skill requirements Temp agency adds a worker to the system Temp agency proposes the worker to a position registered by a client (in the future, the worker may register themselves!) Client gets notified of new proposals (via email) Client views status of all open positions in the system External to the system: Client interviews candidate, request further information and makes a decision whether to hire or not Client accepts or rejects the worker in the system As worker performs work, they register their time in the system At the end of a billing period, the system generates billing information to accounting system At the end of a salary period, the system generates salary information to the accounting systemSome of these steps may be one user story, some may be many. The top of the backlog We choose some of the most central parts of the scope to create the beginning of the backlog. In order to accommodate for the learning as we go along, the first draft of our backlog may look like this:Experimental create open position Experimental list positions Simplified create open position Simplified list positions Complete create open positions Complete list positionsAn “experimental” version of a story is a functionality trivial version that touches all parts of the technology. In the case of these two stories, perhaps we have the application leave the logged in client as a hard coded variable. The story may only include writing some of the fields of the positions, maybe only title and description. The Simplified version may add more complex properties, such as skills from a skill list or it may add filters to the list. The complete version should be something we’re prepared to put in front of real users. By revisiting a feature like this, we have the chance to get the feedback to create a good feature without gold-plating. Continuing the backlog We add enough of the other stories to the backlog to cover an interesting part of the scope:… Basic create client account Complete create client account Basic login admin user Basic login client user Complete login client user Basic add worker Complete add worker Basic propose worker for position Complete propose worker for position Complete confirm worker for position Basic enter timesheet (in this version temp agency enters on behalf of worker) Experimental billing report Basic billing report Basic salary reportThis functionality should be enough to have a pilot release where some clients and workers can be supported by the new system. Or we may complete the backlog with complete versions of all functionality, worker login and perhaps a polished version of a feature or two. Adding the non-functional tasks There are some tasks that we want to plan some extra time for. I generally find that many of these tasks are tasks that customers understand quite well:… Attend training on CSS (the team is rusty in design skills) Basic layout and styling of web pages Complete layout and styling of web pages Polished layout and styling of web pages (they want it really nice) Locate slowest pages and make some performance improvements Deploy solution to target platform Deploy demo version to wider set of stakeholders Deploy pilot version Exploratory test of complete flowPlanning the project In this example project, we have five team members plus a coach/project manager on half-time. Since our team will be working in pairs, we want to work on three functional areas per week. This way, we can avoid huge merge conflicts. The team agrees to plan for five stories per week, but only three the first week, because things generally go slower. Here is the top of the completed backlog:Week 1: Experimental create open position Week 1: Experimental list positions Week 1: Attend training on CSS Week 2: Simplified create open position Week 2: Simplified list positions Week 2: Basic create client account Week 2: Basic layout and styling of web pages Week 3: Basic login client user Week 3: Deploy solution to target platform Week 3: Basic add worker Week 3: Basic propose worker for position Week 3: Basic enter timesheet (temp agency enters on behalf of worker) Week 4: Experimental salary report Week 4: Complete layout and styling of web pages Week 4: Complete create open positions Week 4: Complete list positions Week 4: Deploy demo version to wider set of stakeholders … Week 6: Exploratory test of complete flow Week 7: Deploy pilot versionPresenting the plan Working through the list gives us a complete timeframe of just over 6 weeks for full feature set for the pilot release. To cover realities of life, we probably want to plan for at least one week of slack or even more, depending on the strength of our commitment and the consequences of being wrong. This gives a plan indicating 7 weeks times 5 people at 40 hours per week plus a 50% project manager at 20 hours per week or a total of 1540 hours. I generally find that after a pilot release (or even before it), things change a lot. So I don’t invest much time into planning this. Tracking the development The true strength of a plan like this appears when you start running the project. Each week, the team will report on which stories they completed. This allows us to adjust the plan to actual progress. On the flip side, the weekly planning comes down the team and the customers agreeing on the definition of a story. The vagueness of “basic add worker” is by design! But the team should agree on what they mean by “experimental”, “simplified”, “basic”, “complete” and “polished”. Conclusions In this article, I have showed a quick and accurate way of coming up with a project forecast, complete with time and cost estimates. It’s easy to see and react to deviations from the forecast. A few critical critical observations support this methodology:I never believe a developer estimate other than “by the end of the day” or “by the end of the week”. (Don’t talk to me about hours!) Estimating in hours is a silly way to get to project costs. Any hour-based estimate is always prodded and padded before magically turning into cost. Instead, estimate number of features, feature per week and cost by week. Visiting a feature multiple times lowers total cost due to less gold-plating and investment of in poorly understood areas. It also improves the success of the final feature The ambition of a feature (that is, how many times we will visit it) is a more reliable indication of cost than developer gut feelingI’ve left many questions on the table, for example: What about architecture? What is meant by a “simplified” user story? How to deal with deviations from the forecast? Feel free to grill me for details in the comments to the article. “So what will it cost?” Using this simple method to lay out your project forecast week by week, you can give a better answer next time someone asks.Reference: Estimation by stuffing things into boxes from our JCG partner Johannes Brodwall at the Thinking Inside a Bigger Box blog....
java-logo

JavaSE 7,8: Determining Views Supported by a Particular File System

If you have questions about a file or a directory, such as whether it is hidden, whether it is a directory, what its size is, and who owns it, you can get answers to those questions (and many others) from the metadata, which is data about other data. NIO.2 associates the notion of metadata with attributes and provides access to them through the java.nio.file.attribute package. Since different file systems have different notions about which attributes should be tracked, NIO.2 groups the attributes into views, each of which maps to a particular file system implementation. Generally, views provide the attributes in bulk through a common method, readAttributes(). In addition, you can extract and set a single attribute with the getAttribute() and setAttribute( methods, respectively, which are available in the java.nio.file.Files class. Depending On the view, other methods are available for additional tasks. Here i will explain how with NIO.2 you can manage more details about files’ metadata than ever before. Attributes are divided into categories, and now they cover POSIX systems as well. Before you attempt to access a view’s attributes, make sure that your file system supports the corresponding view. NIO.2 comes with a set of six views (BasicDos,POSIXFileOwner,ACL and UserDefinedFileAttributeView).POSIX (Portable Operating System Interface for UNIX). All file systems support the basic view, so you should get at least the basic name in your output.The supported views are:BasicFileAttributeView This is a view of basic attributes that must be supported by all file system implementations. The attribute view name is basic. DosFileAttributeView This view provides the standard four supported attributes on file systems that support the DOS attributes. The attribute view name is dos. PosixFileAttributeView This view extends the basic attribute view with attributes supported on file systems that support the POSIX (Portable Operating System Interface for Unix) family of standards, such as Unix. The attribute view name is posix. FileOwnerAttributeView This view is supported by any file system implementation that supports the concept of a file owner. The attribute view name is owner. AclFileAttributeView This view supports reading or updating a file’s ACL. The NFSv4 ACL model is supported. The attribute view name is acl. UserDefinedFileAttributeView This view enables support of metadata that is user defined.Here are code snipets that shows different operationsGet all supported file system views import static java.lang.System.out; ....... FileSystem fs = FileSystems.getDefault(); for (String sfsView : fs.supportedFileAttributeViews()) { out.println(sfsView); }Check if the file store support a specific view You can test a particular view on a file store by calling the FileStore.supportsFileAttributeView() method. You can pass the desired view as a String or as a class name. import static java.lang.System.out; ....... FileSystem fs = FileSystems.getDefault(); for (FileStore fileStore : fs.getFileStores()) { boolean supported = fileStore.supportsFileAttributeView(BasicFileAttributeView.class); out.println("Is " + fileStore.name() + ": supports \'basic file attribute view\' ---> " + (supported ? "Yes" : "No")); }Check if a file store in which a particular file resides supports a single view Moreover, you can check if a file store in which a particular file resides supports a single view. import static java.lang.System.out; import static java.lang.System.err; ....... FileSystem fs = FileSystems.getDefault(); try { FileStore store = getFileStore(path); boolean supported = store.supportsFileAttributeView("acl"); out.println("Is " + store.name() + ": supports \'ACL file attribute view\' ---> " + (supported ? "Yes" : "No")); } catch (IOException ex) { err.println(ex); }That’s all, have fun, if you like it share it. Resources:JDK7: Part 1- The power of java 7 NIO.2 (JSR 203) (important concepts) JSR 203: More New I/O APIs for the JavaTM Platform (“NIO.2″)  Reference: JavaSE 7,8: Determining Views Supported by a Particular File System from our JCG partner Mohamed Taman at the Improve your life Through Science and Art blog. ...
agile-logo

Design Your Agile Project, Part 1

The more I see teams transition to agile, the more I am convinced that each team is unique. Each project is unique. Each organizational context is unique. Why would you take an off-the-shelf solution that does not fit your context? (I wrote Manage It! because I believe in a context-driven approach to project management in general.) One of the nice things about Scrum is the inspect-and-adapt approach to it. Unfortunately, most people do not marry the XP engineering practices with Scrum, which means they don’t understand why their transition to agile fails. In fact, they think that Scrum alone without the engineering practices, is agile. How many times do you hear “Scrum/Agile”? (I hear it too many times. Way too many.) I like kanban, because you can see where the work is. “We have a lot of features in process.” Or, “Our testers never get to done.” (I hate when I hear that. Hate it! That’s an example of people not working as a cross-functional team to get to done. Makes me nuts. But that’s a symptom, not a cause.) A kanban board often provides more data than a Scrum board does. Can there be guidelines for people transitioning to agile? Or guidelines for projects in a program? There can be principles. Let’s explore them. The first one is to start by knowing how your product releases, starting with the end in mind. I’m a fan of continuous delivery of code into the code base. Can you deliver your product that way? Maybe. How Does Your Product Release? I wish there were just two kinds of products: those that released continuously, as in Software as a Service, and those with hardware, that released infrequently. The infrequent releases release that way because of the cost to release. But, there’s a continuum of release frequency:How expensive is it to release your product? The expense of release will change your business decision about when to release your product. You want to separate the business decision of releasing your product from making your software releaseable. That is, the more to the left of the continuum you are, the more you can marry your releases to your iterations or your features, if you want. Your project portfolio decisions are easier to make, and they can occur as often as you want, as long as you get to done, every feature or iteration. The more to the right of the continuum you are, the more you need to separate the business decision of releasing from finishing features or iterations. The more to the right of the continuum, the more important it is to be able to get to done on a regular basis, so you can make good project portfolio decisions. Why? Because you often have money tied up in long-lead item expenses. You have to make decisions early for committing to hardware or Non Recurring Engineering expenses. How Complex is Your Product? Let’s look at the Cynefin model to see if it has suggestions for how we should think about our projects: I’ll talk more about you might want to use the Cynefin model to analyze your project or program in a later post. Sorry, it’s a system, and I can’t do it all justice in one post. In the meantime, take a look at the Cynefin model, and see where you think you might fall in the model. Do you have one collocated cross-functional team who wants to transition to agile? You are in the “known knowns” situation for agile. As for your product, you are likely in the “known unknowns” situation. Are you willing to use the engineering practices and work in one- or two-week iterations? Almost anything in the agile or lean community will work for you. As soon as you have more than one or two teams, or you have geographically distributed teams, or you are on the right hand side of the “Potential for Release Frequency” chart above, do you see how you are no longer in the “Complicated” or “Obvious” side of the Cynefin model? You have too many unknowns. Where Are We Now? Here are my principles:Separate the business decision for product release from the software being releaseable all the time. Whatever you have for a product, you want the software to be releaseable. Understand what kind of a product you have. The closer you are to the right side of the product release frequency, the more you need a program, and the more you need a kanban to see where everything is in your organization, so you can choose to do something about them. Make sure your batch size is as small as you can make it, program or project. The smaller your features, the more you will see your throughput. The shorter your iteration, the more feedback you will obtain from your product owner and “the business.” You want the feedback so you can learn, and so your management can manage the project portfolio. Use the engineering practices. I cannot emphasize this enough. If you do not keep your stories small so that you can develop automated unit tests, automated system tests, use continuous integration, swarm around stories or pair, and use the XP practices in general, you will not have the safety net that agile provides you to practice at a sustainable pace. You will start wondering why you are always breathless, putting in overtime, never able to do what you want to do.If you have technical debt, start to pay it down a little at a time, as you implement features. You didn’t accumulate it all at once. Pay it off a little at a time. Or, decide that you need a project to prevent the cost of delay for release. If you are a technical team, you have a choice to be professional. No one is asking you to estimate without providing your own safety net. Do not do so. This post is for the easier transitions, the people who want to transition, the people who are collocated, the people who have more knowns than unknowns. The next post is for the people who have fewer knowns. Stay tuned.   Reference: Design Your Agile Project, Part 1 from our JCG partner Johanna Rothman at the Managing Product Development blog. ...
java-logo

Why use Underscore in Numbers from Java SE 7 – Underscore in Numeric Literals

JDK 1.7 release had introduced several useful features, despite most of them being syntactic sugar, there use can greatly improve readability and code quality. One of such feature is introduction of underscore in numeric literals. From Java 7 onwards you can write a long digit e.g.10000000000 to a more readable 10_000_000_000 in your Java source code. One of the most important reason of using underscore in numeric literal is avoiding subtle mistakes which is hard to figure out by looking at code. It’s hard to notice a missing zero or extra zero between 10000000000 and 1000000000, than 10_000_000_000 and 1_000_000_000. So if you are dealing with big numbers in Java  source code, use underscore in numbers to improve readability. By the way, there are rules to use underscore in numeric literals, as they are also a valid character in identifier, you can only use them in between digits, precisely neither at the start of numeric literal nor at the end of numeric literals. In next couple of section, we will learn how underscore in numeric literal is implemented and rules to use them in numerical literals.How underscore in numbers are implemented in Java As I said that it’s a syntactic sugar, much like how String in switch case is implemented, this is also implemented using help of compiler. At compile time, compiler removes these underscore and put actual number into variable. For example 10_000_000 will be converted into 10000000 during compile time. Since CPU has no problem dealing with long String of digits and it’s fun for him, we don’t bother about that, it’s us, poor humans which has problem dealing with longer numbers.  This feature is particularly useful for banking and finance domain application, which deals with large sum of money, credit card number, bank account numbers and other domains, which deals with longer ids. Though it’s strongly discouraged to write sensitive data in Java files and you should never do in production code, life is much easier with underscore in numbers than before. Rules to use underscore in numbers in JavaJava programming language has strict set of rules towards usage of underscore in numeric literals. As stated, you can only use them in between digits. You can not start a number by underscore, or end a number by underscore. Here are some more places, where you just can not place underscore in numeric literals :At the beginning or end of a number Adjacent to a decimal point in a floating point literal Prior to an F or L suffix In positions where a string of digits is expectedHere are couple of examples, which shows some valid and invalid usage of underscore in numeric literals float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent (before) to a decimal point float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent (after) to a decimal point long socialSecurityNumber1 = 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffixint a1 = _52; // This is an identifier, not a numeric literal, starts with underscore int a2 = 5_2; // OK (decimal literal) int a3 = 52_; // Invalid; cannot put underscores at the end of a literal int a4 = 5_______2; // OK (decimal literal)int a5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefix int a6 = 0x_52; // Invalid; cannot put underscores at the beginning of a number int a7 = 0x5_2; // OK (hexadecimal literal) int a8 = 0x52_; // Invalid; cannot put underscores at the end of a numberint a9 = 0_52; // OK (octal literal) int a10 = 05_2; // OK (octal literal) int a11 = 052_; // Invalid; cannot put underscores at the end of a number Here are some more examples of using underscore in numeric literals long creditCardNumber = 6684_5678_9012_3456L; // Never do it on production code long socialSecurityNumber = 333_99_9999L; // Never, Ever do it on production code float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010; You can see that code is much more readable than without using underscore in numbers. By the way, always use L to denote a long literal in Java. Though it’s legal to use small case l, you should never use it with numbers as it looks exactly similar to digit 1. Tell me if you can find out differences between 12l and 121, I guess not many. How about 12L and 121? In short, always use underscore in numbers, especially with long numbers to make them more readable. I know this feature is only available from Java 1.7, and it’s not widely used yet, but given Java 8 profile, I am expected that, Java 8 will be adopted by community more quickly and widely than Java 7.   Reference: Why use Underscore in Numbers from Java SE 7 – Underscore in Numeric Literals from our JCG partner Javin Paul at the Javarevisited blog. ...
javafx-logo

Tower Defense in JavaFX (4)

Ok, so far we’ve created a TileMap, displayed it on screen and made it editable in the first part. In the second part we implemented calculation of the attack path using the A* algorithm and made the enemies follow that path. In part three we created some custom TileSetAnimations so we can rotate the Insectoids around their center by an angle. We then applied this to the Insectoids, so they look forward when they fly, and to the turrets, so they always aim at the closest target. Time to make the turrets shoot at their enemies. First we need TileSets for an explosion and a bullet for the Pellet gun. I found a nice free explosion sheet here. It’s a bit larger (128*128) than the sprites, and the explosion doesn’t start in the center, but after a bit of fiddling with the position relative to the exploding insectoid it works quite nicely. I created the bullet myself and I know I have to come up with something better :-), but at least it’s something that is visible on the screen. After some fiddling with the correct initial position I created this BulletLaunching Behavior: new SpriteBehavior() { @Override public boolean perform(Sprite sprite) { double angle = rotateAnimation.getAngle(); double xVelocity = Math.cos(Math.toRadians(angle)); double yVelocity = Math.sin(Math.toRadians(angle)); final double centerX = x + (width / 2); final double centerY = y + (height / 2); double startX = centerX + (xVelocity * (width / 2)) - 4; double startY = centerY + (yVelocity * (height / 2)) - 4; Sprite bullet = new Sprite(getParent(), shoot, "bullet" + (bulletCounter++), startX, startY, 8, 8, Lookup.EMPTY); bullet.setVelocityX(xVelocity); bullet.setVelocityY(yVelocity); // add bullet behaviorreturn true; }@Override public long getEvaluationInterval() { return 2000000000; //To change body of generated methods, choose Tools | Templates. } }); Most of the code is calculating the initial position and making sure the bullet heads off in the right direction. Now we need to add some collision detection. Some systems do have a centralized collision system, and allow to add listeners. I prefer to again do this via behaviors, because I find it more natural and intuitive that the bullet itself checks if it has hit something: bullet.addBehaviour(new SpriteBehavior() { private double range = 75;@Override public boolean perform(Sprite sprite) { Collection checkCollisions = sprite.getParent().checkCollisions(sprite); for (Collision collision : checkCollisions) { if (collision.getSpriteOne() instanceof EnemySprite) { sprite.getParent().removeSprite(sprite); ((EnemySprite) collision.getSpriteOne()).hit(6); return false; } else if (collision.getSpriteTwo() instanceof EnemySprite) { sprite.getParent().removeSprite(sprite); ((EnemySprite) collision.getSpriteTwo()).hit(6); return false; } } if (distance(sprite.getX(), sprite.getY(), centerX, centerY) > range) { sprite.getParent().removeSprite(sprite); return false; } return true; } }); What we do here is simply ask the GameCanvas for collisions of this specific Sprite and try to cause damage if it’s an enemy. The anonymous inner bullet Sprite and the Behavior will be converted later to regular classes to make the code nicer and to make them easier to create and configure. On the side of the Enemy Sprite we need to implement the “hit” method: public void hit(int impact) { power = power - impact; if (power getParent().removeSprite(this); getParent().addSprite(new Sprite(getParent(), explosionAnimation, "explosion", getX() - 30, getY() - 80, 128, 128, Lookup.EMPTY)); } } Very simple: in case the hit was deadly, we remove the Sprite and add an Explosion Sprite. If the sprite sizes would match, we could have simply set the explosionAnimation on the existing Sprite. If you can create your own SpriteSheets, you should do that, it makes live much easier. The ExplosionAnimation is configured to run only once, and it has an EventHandler that removes the Sprite, once the Animation is complete: explosionAnimation = new TileSetAnimation(explosion, 100f); explosionAnimation.setRepeat(1); explosionAnimation.setOnFinished(new AnimationEventHandler() { @Override public void handleEvent(AnimationEvent event) { Sprite target = event.getTarget(); target.getParent().removeSprite(target); getParent().removeSprite(EnemySprite.this); } }); That’s it. Our Turrets will now fire Bullets at the Enemies and try to hurt them until they explode:    In the video you also see a DebugLayer. Currently it tracks some performance data, mainly FPS and if the time between two pulses is too long. I’ve also added a bullet to the top of the screen, to visually detect stuttering animations. You can safely ignore that… So we’ve got almost everything we need for a Tower Defense Type game now. In the next part of this Tutorial, we’ll add damage indicators to the enemies, and a HUD with the score and a control to start the next wave.   Reference: Tower Defense in JavaFX (4) from our JCG partner Toni Epple at the Eppleton blog. ...
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books