Tag Archive for coding

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.

 

The Best Feature…

Code Journal LogoI’ve been hard at work mapping out the future of Code Journal  and took some time to go through user e-mails that requested new features; the idea was that I would simply implement the feature that the most users had e-mailed asking for. That feature was a resizable UI.

The problem was that the people, my customers who I of course care a great deal about, were very passionate about this particular feature and the feature seemed simple enough to implement; after all, I’ve implemented resizable UI’s on a number of Mac OS X apps for clients, so why couldn’t I apply the same the techniques to Code Journal? Right? Wrong.

Code Journal started out pretty simple; it was an app that pulled and processed JSON data from the Github API; in fact, the most complicated thing in the private demo (think alpha) version of the app was Github’s OAuth. I was thrilled. The app was nice and simple.

Overtime and as it closer to the all important 1.0, compromises had to be made. There is no need to enumerate them here, but suffice it say that one current feature (Github Enterprise support) is responsible for a disproportionate amount of code and almost all of my support requests. Does that mean I’ll be pulling enterprise support? Absolutely not. The truth is that these request have more to do with customers having non-standard settings on their Github Enterprise deployment or the server that host them, rather than anything to do with Code Journal. Enterprise support is a slam dunk and I personally love being able to user Cde Journal with clients who have Github Enterprise servers; best part is that most of the time all I have to do is fill out the enterprise field in the app with my credentials and we are good to go — no need to bother a sys-admin at all.

In short, the complexity that supporting enterprise customers caused was a good thing. Back to the feature request: resizable interfaces.  I understand why some people might want this feature, but, to be honest, I don’t think it’s a good idea. Even on my 27 inch Cinema Display, I often find myself pressed for screen real estate when tacking some hairy memory management problem or am “in the zone.” Like many of you, I am not willing to compromise by putting my monitoring tools into a separate space and, again like most of you I imagine,  I only have the one screen. The other issue of course is that Code Journal is a Mac app and a lot developers that work on Macs work on 13” laptops.

Still, it’s hard to ignore your paying customers, so I went against my instincts and began coding.  I won’t bore you with the details, but it was doomed from the jump. I spent two weeks coding and agonizing over resizing table views and experimenting with Auto Layout. What resulted wasn’t terrible but had a number of rough edges and, more importantly, was not a feature that I could see myself using and believe would have been a major source of maintenance. The feature is not going to be released. At this point in the product’s life, it is more important to keep complexity out of the equation than to add every suggested feature; this particularly true of features that don’t provide any additional functionality. The best feature is the one you never have to maintain.

Comments? Questions? Share them with me on Google+ or Twitter. This post was made possible by Code Journal and Fingertip Tech, INC. If you are Github user please check out Code Journal and if you are interested in having an Android, iOS, or web app developed please contact me. Also, check out the new free version of Code Journal for iOS.

 

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.

Bad Synchronous Call! Bad!

Back in the dark old days of Commodore 64 and its brethren computers were pretty much all synchronous; instructions executed one after the other, one at a time. It was a simpler time. Users did expect a responsive UI during slow operations or so I have been told. Wondering what a slow operation is? Well, how about any sort of IO? or large data transfer? or how about just pretty much any data transfer over 3G? Of course, there are other cases of long operations but no need to open old wounds….

Now I can hear you already, arguing ‘the platforms today are so much more multi-threaded / multi-core by default I don’t have to worry about writing asynchronous code.’ Well sir (or madam), you are dead wrong. It is true that or more modern platforms have done a lot to run their internal operations in a thread safe / optimized way, but there are a lot of cases where YOU MUST make your code asynchronous. The platform is not going to waive a magic wand and make your operation run asynchronously. Need an example? Here you go:

UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:someURL]];

Looks reasonable, no? Wrong! That code though deceptively simple is actually very bad. Let’s take a look at what is actually happening in this little one liner:

NSData* imageData = [NSData dataWithContentsOfURL:someURL];
image = [UIImage imageWithData:imageData];

Still pretty simple, right? That’s the exact same functionality as the one linear above and the same problem. Take a closer look at that first line. Pretty simple, right? All it is doing is reading the contents of a URL (in this case an image) downloading the data, and creating an NSData object from it. See the problem yet? That is all happening in order synchronously. If the network is slow or the server is slow to return, the UI on your lovely app will lock for a second or so. Bad UX. Very bad. It is important to note that this code is using one of the most direct ways to create an image from an external service provided wholly by Cocoa. Not to hit this too hard, but the platform vendor’s framework (Cocoa in this case) is not doing anything magical to prevent this from happening. Your code is causing the problem and you have to fix it — yourself.

Oh? You actually want to see a correct version of this code? Well, ok. What needs to happen here is that the image needs to be dealt with asynchronously. I like to use the popular (albeit somewhat dated) iOS / Mac library ASIHTTP to accomplish this. For one request it is really easy:

ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:someURL];
__weak ASIHTTPRequest* _request = request;
[request setCompletionBlock: ^{
UIImage* image = [UIImage imageWithData:[_request responseData]];
}];
[request setFailedBlock: ^{
// handle failure
}];
[request startAsynchronous];

Not too bad, right? Just a quick walkthrough. If you are new to Cocoa you might not be familiar with the concept of blocks. It’s a pretty big topic and worthy of its own post (or series of posts) but they are similar to closures in other languages. Also, the “__weak” is to prevent a retain cycle for developers using ARC; if you are not using ARC in your new iOS or Mac OS X projects, consider it. Ok so what if you have to deal with a large number of images for something like a UITableView full images? Well check this out:

ASINetworkQueue* q = [[ASINetworkQueue alloc] init];
[q setDelegate:self];
[q setQueueDidFinishSelector:@selector(networkQueueDidFinish:)];
[q setRequestDidFailSelector:@selector(requestDidFail:)];
[q setRequestDidFinishSelector:@selector(requestDidFinish:)];
for (int i = 0; [someArrayOfImagesURLS count]; i++) {
ASIHTTPRequest* imageRequest = [ASIHTTPRequest requestWithURL:[someArrayOfImagesURLS count]];
[q addOperation:imageRequest];
}
[q go];

// delegate methods
- (void) requestDidFail:(ASIHTTPRequest *)request {
// something bad happened -- handle it!
}

- (void) requestDidFinish:(ASIHTTPRequest *)request {
UIImage* image = [UIImage imageWithData:[request responseData]];
// do something with the image
}

- (void) networkQueueDidFinish:(ASINetworkQueue *)q {
// do something magical when the queue is done
}

Ok so all that has changed is that we iterate through an array or URLS for the images, create ASIHTTPRequests based on them, add them to our operation queue, and deal with the delegate methods. One thing of note is that there are separate callbacks for when each individual request finishes and for the queue itself and if you fail to implement one of those required delegate methods your app will crash.

Hope this helps someone. I am going to be posting more about writing asynchronous code to best take advantage of the multi-threaded / multi-core nature of our favorite platforms. Stay tuned for a look at this type of thing on Android! Find me on Google+ or Twitter if you have feedback.


Objective-C Singletons

A singleton is a way for developers to keep one and only one object of a class in existence for the entire lifecycle of an application; the nitpicky among you will note that there are portions of an app that might not have any instances of a singleton object, since it is common practice not create the singleton until you need it. Some example cases that you would use a singleton include: a player object for a game, a user object for a social app, and a shopping cart.

Creating a singleton is pretty simple:

@interface User : NSObject
static User* userSingleton;
+ (User *) userSingleton {
  if (!userSingleton) {
    userSingleton = [User alloc] init];
 }
return userSingleton;
}

Let’s walk through this. You declare a static user object called userSingleton, then whenver [User userSingleton] is called you check to see if that object is not null and either returns the existing object or alloc/inits the object, then returns it.

Ok, so that’s all well and good, but how do you actually use it. Well it’s simple. Let’s say our User class has a name property. We could access that with our singleton via:

[[User userSingleton] name];

Need to set the name?

[[User userSingleton] setName:@”Luke”];

Not bad, right? Also, note that all other messages can be sent via the same syntax, so:

[[User userSingleton] someMessage];

For those of you coming from a Java background sending a message in Objective-C would be called calling a method in Java.


Now you may have noticed that the above user object will have null values for all of its properties when it is first created and might want to be able to set some default values. For this example let’s assume that User has a few properties (name, fathersName, and saberColor):

static User* userSingleton;
+ (User *) userSingleton {
  if (!userSingleton) {
    userSingleton = [User alloc] init];
    [userSingleton setName:@”Luke”];
    [userSingleton setFathersName:@”Anakin”];
    [userSingleton setSaberColor:[UIColor blueColor]];
  }
return userSingleton;
}

As you can see, if the object is null, then we create it like before, but now we set some default values to its properties. Naturally, these values will be overwritten when you call their respective setters:

[[User userSingleton] setSaberColor:[UIColor greenColor]];


That’s pretty much all you need to know to get started with singletons in Objective-C. One thing of note about my code samples is that they assume you are using ARC, but you are not they still work; you will just have to include the proper retain/release calls. Hope this helps, please get in touch on Twitter or Google+.

***Update: An eagle-eyed reader pointed out to me that my sample here does not prevent you from creating a new instance of the object. So, if you created the object as I recommend but did User* badUser = [User alloc] init] you would have a new user object.  To get a true singleton (ie only one instance allowed) you would have to override alloc and a few other methods; The eagle-eyed reader recommends you see: http://cocoadev.com/index.pl?SingletonDesignPattern. Also, a few of you have gotten in touch with me asking why I did not show the GCD / block pattern. The reason for that is that I feel that it is too advanced for beginners but will write it up shortly. Thanks for all the feedback.

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 Backend Software Stack pt1

If you have every been lucky enough to be able to pick the technology stack that you work on you know how exciting the process can be. However, it can also be a daunting task. Sure if you are developing an Android app or an iOS app you are pretty limited on what software stack you can use, so that makes your choice pretty easy. The real fun comes in when you are developing  a back-end service for an app.

Open-Source or proprietary? REST or SOAP? Windows or Unix? Dedicated hardware or cloud solution? These are  just a few of the decisions you will have to make before you can begin coding your web-service.

Before we get too far off the rails here, I should explain why I am writing this now. If it weren’t obvious enough I am writing  a back-end service for a mobile app and the best part is that I am the client. That’s right no worrying about a client’s IT staff not being familiar with UNIX-like systems (a lot more common than you’d think) or having a culture that doesn’t want to implement anymore services in their aging technology but is at the same time unwilling to look at any more modern solutions; believe it or not, there is a lot of VB6 code still running out there. I’m not bitter. I promise.

So, as the client, what do I want? Well, I basically need a web-service that will return JSON to mobile clients, interact with social networking services, store user data, be fast to implement, easy to maintain, and deploy-able to a number of possible cloud hosting solutions. I am trying to do this project as lean as possible. Meaning I want to fail fast and as cheaply as possible. Tall order, I know, but I think the developer (yours truly) is up to the task.

OK so where does this leave us? Well, we know what I want and now we need to take a look at the options. For the purposes of this series I am going to limit my choices to the following platforms: Ruby on Rails, Sinatra (Ruby), Play (Java), ASP.Net (C#), NodeJS(JavaScript), and CakePHP. From here, I am going to go through each option in its own post and discuss the pros and cons of each technology. Check back soon for part two].

Questions? Comments? Hate mail? Find me on Twitter or Google+.

Frauds and Other Impostors

Impostors. Frauds. We’ve all hear of them and we all go out of our way during the hiring process to avoid them, but do they really exist? Sure, there are those that might not do as good a job as others, but is there really anyone applying for programming jobs that they are certain that they cannot do? I think not. Instead, these imposter’s might be more accurately slotted into a number groups based on their predilections and development habits.

The Inexperienced:

We’ve all had our first job. If it has been a long time for you, think back on that first three months. How many mistakes did make? How many lines of codes did you write that you would never allow through a code review today? Would it be easier to simply count the lines that would pass? Does that make the you from the past a fraud?

You don’t just have to be a green developer to be inexperienced. Consider moving to a completely different stack or platform. Are you used to working in a garbage collection language? Good, try some C++ or Objective-C (iOS and no cheating with ARC). Are you a Ruby on Rails guys? Awesome, how about you boot up the Windows box in your closet and clone your awesome Rails app in MVC 3? My point is not to be snarky but to point out that we were all beginners once and can be again if forced to move out of our respective comfort zones; though I do feel that it is a good idea to constantly play with technology outside of your comfort zone just for the educational value.

The Stubborn:

We all develop particular coding styles, habits, and a level or comfort with the technologies we use everyday but what happens when these things become hindrances to our development work? Well, many of us become stubborn not wanting to change our ways; this becomes particularly troublesome when the ‘Jr’ is dropped from our job title or replaced with a shiny new ‘Senior’ or ‘Lead.’ Of course, I am not arguing that we should all ditch our proven methods and tools in favor of whatever is trending on Twitter. However, we should be open to evaluating these trends; even if technology X turns out to be just another fad, there is always an educational value in learning something new.

The Optimistic:

There is always learning to be done when starting a new job or project, but have you ever been tempted to say “I can just learn technology X before I start the job and be fine.” Well, if you have you have more likely than not picked up that technology fine and are happy with your new position congratulations. If not, you are part of the reason for the “fraud” scare. Basically, you mislead your potential employer or client and have now put them and yourself in the awkward position of having to deal with reality. I’m not one for judgments, but keep that in mind the next time you fudge a resume to get that next big project. More likely than not, if you have been guilty of this type of fudging, you meant well and truly believed that you would pick up what you needed to know in time, but were mistaken.

The picky among you will be quick to point out that what I call “optimism” is in fact a form of fraud. I would argue that fudging one technology or tool though misguided is not the same as claiming to know something as big as an entire programming language when you do not. Am I too soft here? Are these people really just outright frauds? Let me know what you think on Twitter (@dominucco) or Google+.