Application programming interfaces (APIs) are the building blocks of applications in all programming languages. An API contains code that performs specific functionality, and it defines the way in which other code can access and use its functions. In this unit, we will create our own API that can be used by other Java programs.
- [Instructor] In our final chapter of this course, we'll create our own API for accessing a website and returning a parsed response. I'm gonna start by talking about what an API is, and some of the considerations you should have for writing your own APIs. API stands for application programming interface. There are some pretty formal definitions of what that means, but I tend to think of an API as, simply, code that other code can use. Every time you write a class with public methods, you're creating an API, even if your code is the only consumer of that class.
In a formal sense, APIs tend to be packaged up as libraries to make them even more portable. But I also think that every public class I write is a little mini API that might grow up to be part of a real API some day. Why? Because that's happened to me more than once. Programmers borrow code all the time. We borrow it from the internet, from our co-workers, and even from old projects that we wrote ourselves. If you can put yourself in the mindset that every piece of code you write might get copied and pasted into another program, or called by a completely foreign class, you'll naturally write better APIs.
As an example, in the previous chapter, we wrote some code that can rotate an image. We specifically needed that as part of a larger piece of logic where a button was clicked, an image was retrieved, the image was re-sized and then rotated, and finally, the image was put back on the screen. Now, let's say we had jammed the image rotation code inside a much larger block of code that did all those things in a single method call, and say that Joe, from down the hall, comes by your desk and says, "Hey, you wrote some code that rotates images, right? "Can I have that code for this project "I'm working on for the CEO?" Well, if the rotation code is mixed in with all that other code, it might be pretty hard to disentangle just the rotation part and give it to Joe.
And even if you did, there might still be some pieces missing because of the way you declared variables or made information persistent. But because the rotation code was all by itself in its own method, as though you were writing an API, you could simply give that rotate method to Joe, and he'd have everything he needs. This brings us to rule number one about API programming. Methods should do one thing, and one thing only. If you find that you've written a method that requires you to use the word and when you describe it, it might be doing too much. For example, let's say your method re-sizes and rotates an image.
Then, you might be better off splitting into separate methods for re-sizing and rotating instead. Sometimes, there are good reasons not to, of course, but you should at least consider it. In fact, that brings us backwards to rule number zero. None of the rules I talk about here are really rules, they're just suggestions. It's just one person giving advice to another person. In fact, I'm gonna stop calling things rules at all in this section. No more rules. Instead, I'll just mention things as stuff that might be good to do. The larger point is that you should be deliberate as you write your code, and try to think about being consistent and easy to understand.
And always be willing to re-write your code to make it better. In terms of general code conventions, here are a few short documents that might give you some ideas. We have the official Java Code Conventions, originally written by Sun and kept on the Oracle website. Now, these haven't been updated since 1997, but they still have some really good advice about how to write your Java code. There's also the Google Java Code Style from 2014, and the Microsoft.NET Naming Guidelines. Now, obviously, those are not Java, but they still have some really good advice.
I'll be talking about several concepts that are mentioned in those documents because they have excellent advice. Unfortunately, sometimes, the style guides contradict each other. Some are very strict about what to do and what not to do, and others have more tone of suggestions like we have here. The choice of how you write your code is always up to you. Whatever rules or guidelines you choose to follow, probably the most important thing is to learn and follow the coding conventions used at your place of work. Some companies don't have formal coding conventions, and that's fine, but if yours does, then you should use them.
Even if there are things that informally are how everyone does it around here, try to write your code the same way as your teammates write theirs. Just strive for consistency. Another thing to keep in mind is that you shouldn't try to be daring and original in your own personal coding style. Make a lot of mental notes about how other people's code looks, especially large, well-established APIs, like the Java APIs, and then try to write code that follows that style. This will make it easier for other people to understand and use your code. As a simple example, it's normal for Java methods to begin with get when you're getting the value of a variable, and set when you're setting the value.
You should take a hint and use get and set for those types of operations. Don't get cute and use retrieve or assign, or something weird. Just try to write normal-looking code. Also, some people get very religious about code formatting, like where your curly braces are placed, or whether to use tabs or spaces in the source code. Don't get worked up over style issues like that. It's okay to have a personal preference about these things, but it's not something you should get in a fight about. Again, if your company or your programming team has standards, as far as that stuff goes, just use the company standards.
Otherwise, try to pick a normal way to format your source code, and let the IDE do the work. Eclipse has some very nice and customizable auto formatting tools you can use. Finally, the whole goal is to have code that's easy to understand. Keep an eye on that goal. Use names that make sense. Don't use cryptic abbreviations, and make sure your code looks and reads like code that people are used to seeing. The next few slides are naming conventions that are pretty widely used in Java. First, when you name your packages, use all lower case letters only. Normally, the format is going to be company.library, following by maybe a category or a subcategory.
For class names, use upper camel case and letters only. That should be a noun or a noun phrase that describes what something is. Now, an interface usually starts with a capital I, followed by upper camel case, but sometimes, there is no I, and that's okay. That's kind of up to you. In any case, it should be a noun or a noun phrase, just like a class name, but it could also be an adjective, because an interface describes, not only what something is, but it could describe what something does. For naming your methods, use lower camel case and prefer letters. Numbers are okay in moderation.
Also avoid two or more capital letters in a row, because that sometimes makes the methods hard to read. A method should be a verb or a verb phrase that describes an action. Avoid excessive abbreviations because they might make your methods hard to understand. And for methods that return Boolean values, you should prefer to use a prefix like is, or will, or has. You should also prefer to use positive phrases instead of negative ones. So, instead of having a method that says it will not do something, or it will not return something, have a method that says it will return something.
For variable names, they should be lower camel case. Again, prefer letters, numbers are okay in moderation, and avoid two or more capital letters in a row. This is just a readability thing. They should be short, yet descriptive, and avoid excessive abbreviations so that it's very easy to figure out what it is that variable is doing. Remember, using fewer letters doesn't make your code run faster, so use as many letters and as many words as you need to make your variables make sense. For static variables, like constants, these should be all caps, with an underscore as a word separator.
And finally, for method parameters, these have the same naming conventions as variables. Keep your parameter list short. If you find that you have too many parameters for your method, you can create a custom class, and then use a custom object to pass multiple related parameters as a single method parameter. Avoid Booleans that act as flags too, because these are confusing and they can limit future growth. Instead, you should be using int constants, or enums, or enum sets. I'm not sure who said this first, but I've heard it and read it in several different places, and I think this is excellent advice.
Code should read like prose. In other words, when someone's using your code, your classes and methods and general program flow should lend themselves to a sentence-like structure. Reading through your code should be like reading sentences, almost like reading a story. It should be easy to follow what's being done based on the names you've used. This requires you to be smart and thoughtful about your class and method variable names. There are no real hard and fast rules about how to achieve this. You just have to keep reading the code and changing things as you go along to make the words more meaningful and less confusing.
A good way to do this is to write some example code using your classes before you write the code for the classes. Sometimes, you'll find that you not only need to change what things are called, but you need to change how all the methods work together. You only figure this out by writing examples. Then, the more examples you write, the more you need to tweak and change your classes and methods until the example code all has good flow. I realize that the whole flow concept is kind of subjective and existential, but it's a you'll know it when you see it kind of thing. Sometimes, it's really helpful to read your examples to other people.
Actually read them out loud and see if it makes sense. If the name of something doesn't make sense, or you have to explain it to the other person in too much detail before they understand it, just change the name. Don't get hung up on the name of classes or methods because you've already written them. You'll rarely get the names right the first time, so don't feel like the first name you come up with has to be the final name you use. All throughout this chapter, we'll be renaming and moving things around, sometimes multiple times, to make everything as clear and logical as possible. Eclipse has some excellent refactoring tools that allow you to rename things on the fly, and it updates all your existing code references so you don't break anything.
It's so easy that you have no excuse not to change your code. If nothing else, remember this. If your code makes sense to everyone else, then other people won't have to bother you to ask how it works. That should be incentive enough to make you code clear and unambiguous. It keeps other people from bothering you. Seriously though, you're doing yourself a huge favor by spending some extra time upfront and trying to write class names and method names that are easy to understand. To close this discussion, and so we can get started actually writing code, here are some links to information about standard ways of writing and structuring your Java code.
The first two links are for Wikipedia articles on object-oriented design guidelines, called SOLID and GRASP. These are both acronyms for the list of design principles they embody, and they're a good place to start if you wanna put some thought into how your code is structured. The third link is a YouTube video of a one-hour presentation that Joshua Bloch gave at Google several years ago. It's called Designing a Good API. It has a ton of good advice and reasoning about how you should write your API code, and why you should write it that way. And he shares some great examples of APIs done well, and APIs that have gone astray.
He was the design lead for the Java collections framework, among other things, and he's written some excellent books on Java programming, and, in general, he just really knows his stuff. So, to recap, just be mindful of how your code looks and how easy it is to use. Spending extra time designing your code early on can pay huge dividends in the future.
- Creating a command-line application
- Building a graphical user interface
- Creating a Java API
- Parsing JSON data
- Refactoring and testing Java code