Archive for Java

Three Tech Wishes for 2017

Happy 2017! As we put 2016 in the rearview mirror, we’re all taking a look at the outlook for 2017 as I did here but I wanted to take a more personal angle here and explore what I desperately want to see from the tech community. This list is by no means exhaustive and for the sake of time (and online attention spans) I’m limiting it to my top three.

Google Account Management: Dealing with multiple Google accounts is an unfortunate and annoying fact of life for me both as a regular user and as a developer. In this year alone I’ve probably written thousands of lines of code for myself and for clients to deal with this problem by basically scraping calendar events between two or Google accounts. The business case for this problem is pretty simple. Company A gets a contract to do some work but they don’t have the resources in house, so they subcontract part (or all) of the job to Company B, but Company A doesn’t want the client to figure out that Company B exists and is actually doing the work, so they give all the Company B people Company A Google accounts. My event scraping solution is sloppy and fraught with all sorts of little issues. Google should find a way to implement some sort “vanity account” system that let’s the actual email addresses be masked between multiple domains, so that the customer sees what Company A wants them to, but Company B doesn’t have the overhead of dealing with yet another GMAIL account.

Reactive Programming Hype: A lot has been made of Reactive Programming in 2016. While there is definitely some fire to the smoke, things are getting way too hyped and frankly I’m seeing Jr developers pitching reactive programming on freelance gigs as some sort of silver bullet that will solve all the problems you have have and even ones you don’t know you have yet. This is scary! Sure there has always been hype around “new” (sneer quotes because Reactive Programming is only new from a ‘certain point of view’) technologies and methodologies but this hype train around all things with the word or root ‘react’ in them has the kinetic energy of ten hydrogen bombs. I’ve gotten too many projects in this year from prospective clients that were over-engineered in one of these reactive libraries by some Jr dev who just got a little too excited on the Kool-Aide sales pitch and the story is sadly all the same – the client was happy with what he was told but what he got was a steaming pile of hard to reason about spaghetti code and ultimately a rewrite. For 2017 let’s just pull the cord a little on the hype train, OK?

Docker Direction: Despite some fairly significant pain in upgrading between Docker versions and other more minor issues, I am still a serious believer in Docker as the premier containerization solution. Coder Radio listeners will remember that even as a callow youth I was on the Docker train right from the beginning but my faith has been somewhat shaken and I’d like some clearer communications regarding where the technology is going, who they feel their ideal target users are, and where Docker the company sees its role beginning and ending — in other words where will they and where won’t they compete with vendors who are selling / implementing Docker.

Those are my three (I hope fairly doable) wishes for 2017, but before I go…. I also want to note what I didn’t mention here that I have in my end of year / new year posts for the last years – App Store monetization and more specifically a sign from Apple on where they see that going. We got our answer in 2016 – subscriptions. While that will work for a number of apps and is working fine for my Backpoints (iOS & Android), it does not satisfy all the needs of independent developers and likely will not create the high-value ecosystem of professional paid (paid defined as taking money in any non-donation way) software that the iOS App Store originally enjoyed. When I think about Apple and their answer to the monetization issues on the App Store, I am remained of that great quote from Dan Brown’s Angels and Demons: “God answers all prayers, but sometimes his answer is ‘no’.”

Pallet Town: First Steps to Functional

I’ve been taking a deeper look at Functional Reactive Programming in the form of RxJavaand ReactJS. While I am still at the early stages of really looking at this and forcing myself to actually work in these technologies that I’m still no really sure make a lot of sense for my use cases (more on that at a later date), I was taken aback by the simple usefulness of the “Functional” part of the equation. At the risk of grossly oversimplifying the benefits of functional programming (or at least adopting a more functional style in your object oriented code), there is a ton to be gained with just a little bit of re-thinking of how you think about the relationships between your objects and how you structure your methods. This is because one of the main benefits of functional programming is that it minimizes state and therefore unintended side-effects. Here are the two quickest and easiest ways to improve your code today using a more functional mindset.

One Function == One Action:” Every function you write should do one thing and only one thing. Let’s take a very simple sample of what this should look like:

public Pokemon getPokemon(int id) {
	Pokemon  myPokemon = PokemonStore.getById(id);
	myPokemon.setType("fire");
	PokemonStore.save(myPokemon);
	return myPokemon
}

The Assumptions in that are that we have some PokemonStore class that is effectively an ORM for your Pokemon. That’s fine. The issue here is that our ‘getPokemon’ function doesn’t just fetch us the correct record by id as you would expect it to. Instead it updates it ‘type’ property and reserves the mutated record to the datastore before returning the record. This is obviously terrible on a number of levels but looking at it from a functional point of view, the primary sin is that it does three things (getting a record, mutating a record, and saving a record) rather than just one and what it does doesn’t match the method signature. A better version of this method would have mutating the type in another method and simply return the record:

public Pokemon getPokemon(int id) {
	Pokemon myPokemon = PokemonStore.getById(id);
	return myPokemon;
}

As you can see that’s easy to read, does one thing, and there’s little to know risk that a future developer won’t understand what the method is supposed to do.

Deterministic Outputs: A method given the same inputs should always return the same outputs. If that’s not true, then you likely have too much coupled state in your code that is causing unforeseen issues. This is a great example of what not to do:

public Pokemon getFirstPokemonInRoster() {
	List<Pokemon> roster = User.CurrentUser().getRoster();
	Pokemon starter = roster.get(0);
	return starter;
}

There’s a lot not to like in this method. For starters it relies on the start of a Users.CurrentUser() singleton, which instantly creates couple state. Another issue is that it’s not very flexible — is it really true that we will only ever care about the current user’s roster? Finally it’s not written in a way to be optimized for easy BDD / testing and violates the functional principle (or perhaps guideline) of passing in the objects / values a method needs to run into the method directly rather than pulling them from another place. Here’s a minor change that addresses all of those issues:

public Pokemon getFirstPokemonInRoster(int userId) {
	User user = UserStore.getById(userId);
	List<Pokemon> roster = user.getRoster();
	Pokemon starter = roster.get(0);
	return starter;
}

As you can see, the revised method can now the pull the roster for any arbitrary user and does not rely on a user singleton. You can easily imagine a test being written that passes in a valid user id to test the golden path for this and also another test with an invalid value for the userId paramater; incidentally, my method still doesn’t handle that case, but there are multiple ways you might do that and catching that sort of thing is really what automated testing is for ;).

I hope you’ve found this helpful! If you have any questions or comments, please sound off below or on Twitter.

Programming Pitfalls: Cors & Spring Boot

It’s no secret that I have been dipping my toes back into the world of enterprise Java development over the last moth or so. Thankfully, I haven’t been forced to go full Java EE. In fact for enterprise development I’m getting off pretty easy in the form of Spring Boot.

Spring Boot is an offshoot of the popular Spring framework and brings many conveniences from modern non-Java web development frameworks to Spring developers. It’s related to the Spring MVC framework but is more geared toward use in a mircoservices architecture. I’ll be working in it for a few more weeks and will get some more thoughts together at a later date but for now let’s go over the pain that is CORs. For those that don’t know, CORs is a browser feature that protects against cross-site scripting in JavaScript and the web would be a much more dangerous place without it. As always, security comes at a price and in this case that price is that web services that interact with an API on another domain or IP need to allow cross site access in their response headers or just about every modern browser won’t let the response through.

Ideally, you’d want to change your ‘Access-Allow-Origin header’ to the domains that your client applications will be hitting your API from but if you’re API is public or you don’t yet know what the final domain of your client app.

In Spring Boot this can be done with a simple Filter like so:

@Component 
public class SimpleCORSFilter implements ContainerResponseFilter {
    @Override 
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        MultivaluedMap&lt;String, Object&gt; headers = responseContext.getHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        headers.add("Access-Control-Allow-Headers", "*");
    }
}

Notice the @Component above your subclass of ContainerResponseFilter, that’s what tells the the framework about this calls. What this calss does is add the values to the “Access-Control-Allow-Origin, “Access-Control-Allow-Methods”, and the “Access-Control-Allow-Headers”. In the example above, we are going with the most open settings possible. You likely will want more secure / conservative settings unless your service is intentded to public. This is an important point and it took me hours to figure it out –It is important that this file be in the same package as your “Application” class (the class that has the SpringApplication.run) in it.

I hope this helps somebody! If you found this post interesting reach out to me on Twitter.

Pallet Town: OO with Pokemon and Java pt2

Welcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

Ok, so we are picking up where we left off in our last post. We have a basic Pokemon class:

public Class Pokemon { 	
	public int id;	
	public String name;
	public int hp;
	public int ap;
}

We also have learned how to construct a Pokemon based on our existing class:

Pokemon pikachu = new Pokemon();

And of course how to set some properties for our new pikachu:

Pokemon pikachu = new Pokemon();
pikachu.name = "Pikachu";
pikachu.ap = 10;
pikachu.hp = 100;

That of course works, but is a little bit of a pain. Let’s take things a step further and make a more convenient constructor for our Pokemon class:

public Class Pokemon { 	
	public int id;	
	public String name;
	public int hp;
	public int ap;

	public Pokemon(int _id, String _name, int _hp, int _ap) {
		this.id = _id;
		this.name = _name;
		this.hp = _hp;
		this.ap = _ap;

		return this;
	}
}

I know that might look a little crazy but it is actually pretty simple. Basically, we are setting values for the properties of our Pokemon in the constructor itself rather than having to do so in the implementation — this is a very primitive form of encapsulation, one of the most important concepts of all of software development. So, using our new constructor, we’d create the same pikachu from before:

Pokemon pikachu = new Pokemon(14, "pikachu", 100, 10);

Doesn’t that look much cleaner?

Hope this post helps you on your journey to become a Pokemon… err coding master! Please feel free to send any feedback to me on Twitter or Google+. Also, be sure to check out my company Fingertip Tech, INC on Twitter.

 

Give Duke a Break

If you remember the man to the left of this sentence, then my hat’s off to you. Good old Duke here has seen some good times, some bad times, and frankly some overhyped times. My how times have changed. Some of the “journalists” who heralded Java as solution to all software development problems are now wrongfully spread FUD — implying that Java itself is insecure. Like any technology, Java has its issues, but the space is large and the recent security issues are almost focused on one area: applets. Java applets are more than a little antiquated at this point and there aren’t many developers worth their salt developing them.

The real issue here is not that applets are taking the web development world by storm, because that hasn’t been the case for almost a decade. The issue is that we, software developers, have done a poor job of conveying what software really is to counterparts in the business world. They think that you can contract out for an application or system and the cost of the system will be all (or mostly) taken care of upfront. This “set it and forget” attitude works fine for roasting a chicken. Sadly, software is not a chicken and that attitude eventually becomes problematic in the software world.  Unfortunately, coupled with the questionable coverage of the recent applet security issues, this attitude has lead less sophisticated developers and our business development colleagues to exile Java as though it were some sort of plague ridden rat. We, as a community of software professionals, need to change the way our colleagues view our work.

The reality of software is that it needs to be maintained and cared for, not unlike an automobile. We should clearly explain that the solutions develop are not intended to stay in place until the end of time. This is not a Java problem — this is a software problem. I encourage you to join in changing this conversation. Come on, let’s give Duke a break.  Questions? Comments? Dogmatic rage? Find me on Twitter and Google+. This post was brought to you by Code Journal and Fingertip Tech, INC.

A Look at PFQuery

Querying data is a pretty common task for most if not all mobile apps. iOS and Android have made the work pretty easier for developers, but Parse has thrown their hat into the ring to make it even easier for developers who choose to use their development tools and backend system; yes, I know this sounds a little like a commercial, but I am genuinely excited about this functionality and no I have no business or personal relationships with Parse or anyone therein.

PFQuery is a simple class that, as its name suggests, allows you to query your Parse dataset and getting data returned based on certain criteria. No need to stand on ceremony, let’s take a look at some code:

- (void) someMagicalFunction {
	PFQuery* query = [PFQuery queryWithClassName:@"SomeClass"];
	[query whereKey:@"SomeProperty" equalTo:@"MagicString"];
	[query findObjectsInBackgroundWithBlock:^(NSArray* objects, NSError* error) {
		// do something with the objects

	}];
}

And now for you Android fans:

void someMagicalFunction() {
	ParseQuery query = new ParseQuery("SomeClass");
	query.whereEqualTo("SomeProperty", "MagicString"
	query.findInBackground(new FindCallback() {
		public void done(List< ParseObject >objects, ParseException e) {
		// do something with objects
	});
}

Yup, that’s it. It really is that simple. If you want to know more take a look at the Parse docs. For those of you that are critical of Parse, I will be doing more than just code samples with it; in fact I have found a few deficiencies that I will be discussing in a future blog post.

Review: Mastering Grails 101

I like Ruby and have a soft spot for Java and all things Java, since it was my favorite programming language before I started my professional career and the language that got me my first coding gig. So you’d think that I’d love Grails, a platform that aims to be the best of both worlds. You’d be wrong. However, O’reilly’s tutorial on Grails is pretty good. However, I am not sure that I would recommend it for anyone but a professional developer, as the presenters do seem to assume that the viewer has some professional (mostly Java) experience.

Like all O’reilly videos the production qualities were superb; the video and audio were both crystal clear and I had no problem viewing the code samples on screen. The presenters were very knowledgeable and took time to walk you through some of the more confusing aspects of Grails. The content was  introductory enough that most developers who have had a little Java  experience (in a professional environment of course) would be able to grasp most, if not all, of the concepts and examples laid out by the presenters.

Of course, nothing is perfect. The short length of the individual videos is downright annoying. Some of them are as shorts as three minutes long and you have to manually click to load up the next video in the web player. There is no reason for this. Oreilly of all organizations should be able to either cut multiple chapters into longer videos or enable autoplay on their player. Still, it is hard to fault the presenters for the presentations platform’s failings.

Overall, I would recommend this series to any Java developer that is thinking of taking a step or sto toward the Ruby on Rails side of life or to anyone who has heard of Grails and is curious as to what the hype is about. This series is not appropriate for students or hobbyists.

On Finding a Java Intern / Freelancer

Initially, I planned on working through a fast API in each of the software stacks that I had written about in a previous article. Naturally, a Java based solution was near the top of my list going in. There were a number of reasons for that including my familiarity with the language and the availability of cheap help;  after all, pretty much every college teaches Java and students are always looking for some part time work.

If you have ever had to manage a project you probably already see the fallacy in my line of thinking. That’s right I blindly assumed that throwing more man hours at the project would lead to more productivity; i.e. I foolish assumed that there was a positive and casual relationship between time spent on the project and progress.

So, I got in touch with an old professor and asked to speak to third and fourth year students that were studying programming. Being from the university’s English department, he quickly introduced me to colleague in the appropriate department who eagerly informed me that a heavy emphasis had been put on practical skills and in particular Java in her department since I had graduated and that she was sure I would quickly find appropriate candidates.

I was happy to hear it. I gave her the go ahead to give my e-mail to her students and began the vetting process. Right off the bat I was seeing some strange things: some students proudly boasted Excel macros as their highest programming skill, many others failed to list a project they had done on their resumes, and still others failed to list any programming or programming related courses or competency. Still, I e-mailed several students and set up phone screens with them.

During the screens I asked all the students if they had ever worked with source control. Most said they had heard of it but had not worked with it. Those who had had only worked with SVN and did not know what a distributed source control system is. To be honest, I wasn’t surprised by this. I assumed that most professors would be focusing on somewhat older and more widely excepted enterprise tools rather than newer alternatives. Still, not knowing what source control is in your last year of a development focused degree is a huge red flag.

Disappointed, I moved on to my second line of questioning: what experience do you have with UNIX-like operating systems. To my surprise, only one of the students had ever really used a UNIX-like operating system (Ubuntu in his case) and he was on the IT support track rather than the software development track. I expected most of them to working on Windows PC’s day to day, but assumed that they would have had some training on a UNIX system beyond a history lesson. Ultimately, knowing how to work on a Mac or Linux box would not be essential to the work I needed done, so I didn’t press the point too hard.

I moved on to asking some technical questions. Most of students were able answer the obligatory: what is the JVM?, what is garbage collection?, what is the difference between a class and an object?, what is inheritance? Thankfully, most of the students were able to answer these questions to my satisfaction.

I finished the call by asking each student to tell me about a project they had worked on in Java or any other programming language. This is the question that made me decide to do the work myself. Not a single student had done any programming during the college career beyond small code snippets for assignments. No Github projects and no Super Mario clones. I was crushed.

At this point I realised that adding any of the students I had spoken with to the project would not only cost whatever I ended up paying them, but would also lead to some scary bugs that would take more time on my end to fix than doing the actual coding myself. Basically, more hours would probably lead to less progress and I just can’t have that. Ultimately, I wrote the professor and explained that I did not feel that any of the students she had sent were qualified for the project and thanked her for her time.

Did you take Computer Science? Did you get any practical training if you did? I can be reached on Twitter or Google+.

Also, if you are a student who knows some Java and is looking for some freelance work contact me on Twitter or Google+.

Picking A Project Stack pt 2.0: The Java Space — Grails

When I set out to create a new project that would  need a web-service, Java was on my short list of tools to use for the project. It’s a great language / platform and I am pretty familiar with it and there is a lot of knowledge out there that I can leverage when I run into trouble.

Going in, I knew I had to  limit my options in regards to what frameworks / libraries I would look into, so I decided to look into MVC frameworks only, since I have a lot of experience with that type of architecture and prefer it for most of my development work. I’m not going to go into the relative merits and failings of MVC, nor am I suggesting that it is “the one true way.” It’s just a way of thinking about an application that works for me and that I am familiar with, so it makes a lot of sense for me to leverage that.

Given that, I quickly stumbled upon Grails; full disclosure: I have known about Grails for sometime and played with it in the past, so I didn’t really “stumble upon it per se….” Grails is definitely an attractive option for the project, since it combines some of my favorite things from the Ruby/Rails world (dynamic typing)  with the (usually, at least when compared to Rails) superior performance of Java.

Still, as I played with it again, I was reminded why I never really pursued in the past: every-time I Google something I find Grails devs complaining of bugs in the framework itself. That was a bit more troubling to me. If there are a significant number of bugs in the framework itself, then what will that mean for my application? Will I be spending a lot of time (time I won’t have) working around those bugs?   That seems to be the general consensus of the devs I chatted with and whose forum / blog entries I read and since I am not a Grails expert, I might end up spending a lot of times trying to work around bugs that I don’t even know exist.  I understand that is completely unfair.I am sure that some of this is over-hyped and obviously any significantly large project is going to have bugs.  So please if you are a Grails dev send me some positive experiences with it on Twitter or Google+ and also include why you chose it over competing tools.

With Grails out of the running, I went to what I feel is a pretty obvious choice for MVC with Java: Play. But more on that later. How do you choice your tools for the job? Is you thought process similar or radically different from mine? If you liked or hated what you read here, please get in touch on Twitter or Google+

A Month in Eclipse

As anyone who reads this regularly will know, I spend most of working day in XCode developing for Apple’s iOS and OS X platforms. However, I have had a long affinity for Java and am a fan of the Android operating system; I have a number Android devices including the fantastic Galaxy Nexus and the much less awesome Kindle Fire (more on those in another post) and have done some Android development both as a hobby and on a professional basis.

When I first decided to jump into Android I resisted Eclipse pretty strongly and ended up on IntelliJ. Things were going pretty well for a while. The code completion was nice and fast and the IDE had enough hooks into the Android tooling that I didn’t feel like I was at an efficiency disadvantage compared to Eclipse developers.

That all changed when  a friend gave a me a look at the built in user interface builder that had recently been added to Eclipse. Interface Builder is something that I sorely missed in my Android tool-chain and up until then I had been using DroidDraw to fill the gap. That was a passable solution, but I still needed to spend a good deal of time editing layouts in XML and eventually I ended up just coding all of them by hand; this felt inefficient, so I caved.

I downloaded the latest version of Eclipse, read some docs regarding the IDE’s Android specific functionality, and abandoned my trusty IntelliJ. Right off the bat I was disappointed in the layout tool. It is no Interface Builder and I still felt that working with the raw XML was easier than working with the tooling.

Still, I soldiered on for about a month and tried to get into the Eclipse mindset. More and more I became increasingly frustrated with Eclipse. One of the biggest issues that plagued me was the inconsistent code completion / suggestion;  most of the time the tool didn’t make any suggestions until after I had finished typing a line of code. I am not sure if this is to do with the Eclipse ‘content assistance’  engine, since the IDE was running pretty slow overall on my machine; I was running a 2011 Macbook Pro with an i7 and 8 gigs of RAM, which one would think would be more than adequate for running an IDE. I have been told but have not been able to confirm that these performance issues do not exist on Windows, so take that for what it is worth.

Of course, there are some things that I really like about Eclipse. To start, it is a great example of an extremely successful open-source project. I love that it is highly extensible and that additional functionality can be added at no cost; one of the reason that I wanted to evaluate Eclipse is that some of the additional functionality I wanted in IntelliJ requires the paid version. Eclipse make the Android Market submission process a matter of clicking through some simple wizards; on IntelliJ, I have to drop to Terminal and do the signing from there, which can be a little confusing the first few times that you do it and is not nearly as efficient as simply clicking a button. On the same line, Eclipse seems to keep track of your signing keys for you, however, it does not back them up, so be sure that you do that; if you are unlucky enough to lose the key that you signed a Market app with, then you will quickly find that you cannot update your app at all. Period. Probably my favorite aspect of working with Eclipse is the community. There are tons of tutorials and every community member that I have contacted in IRC  has been more than gracious in helping me get productive with the tool.

At the end of the day efficiency is what really matters to me, so I am going to revert back to using IntelliJ and I am going to be evaluating purchasing the commercial version of the product; stay tuned for a post on that in the coming month or so. Also, if you are interested in developing on Android and do not have your tool-chain set up yet, I recommend that you give Eclipse a look; this goes double if you are new to developing software or the Android platform, since most of the tutorials for Android assume that you are using Eclipse.

If you have feedback, drop me a line on Twitter (@dominucco) or Google+.