Tag Archive for java

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

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.

Object oriented programming is one of the most common and widely used programming paradigms on the market today. In fact, if (like me), you code for a living, then it is likely that you have to deal with OO concepts on a daily basis; in fact, they have probably become something of a second nature to you. Still, maybe you are just dipping your feet into the wide world of Pokemon… err I meant Java… err I mean programming. Well, this post and its follow up posts are for you.

Before we begin, take a look at this fast code snippet:

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

If that seems foreign to you, don’t worry, we will be going over it right now!

OK so what we have there is a simple but boring class that represents Pokemon. Bascailly, we are defining the basic attributes (or properties) of a Pokemon. Taking it from the top, all Pokemon need to have an id so we can store them in our Pokedex (which is basically a fancy database), they all have names, they all all have hp or hit points, and they all have attack points. Of coure, we are likely over simplifying what Pokemon are but we will look at that issue in future posts.

At this point we have a Pokemon class, but no actually Pokemon objects. We need to create an instance of our Pokemon class. To do this we are going to use Java’s ‘new’ operator like so:

Pokemon pikachu = new Pokemon();

Our resulting “pikachu” is a little lame… he has 0 hp, 0 ap, and his name and id are null. Let’s try that again but take it a step futher:

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

That’s it you have a very basic Pikachu! Sure it can’t do much right now and is a little boring and has some data encapsulation problems, but we will address some of those issues in the next post.

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.

Programming Pitfalls: Android Keystore Files

Programming Pitfalls is a series that aims to help new and seasoned developers avoid common and at times terribly painful programming errors and other missteps.

Ever submit an Android app to the Market… er I mean Play Store? If you haven’t I hope you do (mobile development is a lot of fun), but if you have do you remember that .keystore file Eclipse had you make? You don’t? Well, you’re in trouble. If you don’t find that file you will never be able to update your app. Poor design on Google’s part? That argument could be made, but the point of the system is to ensure that no one, other than you,  can submit an update to your app; imagine what would happen to mobile security if a malicious entity were able to submit a virus laden update to Angry Birds?

My recommendation is that you back up you key to a remote service, such as Dropbox or even GMAIL works. Just make sure that it is something that is in the cloud and have mutiple copies of your keystore in multiple places.

Hope this saves you some pain in the future.

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+.