Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, March 20, 2018

Lets give Spring the Boot

Hi folks.  It's been a while since I've posted anything here.  Let's just say that life is complicated.

I was inspired to write this based on some recent experiences with Spring Boot.  This is a very powerful technology that relies on Spring and takes it to new and interesting places.  The bottom line is that while there are many ways to structure a system, if we pick one and stick with it we see some real benefits.  Productivity improves, communication between developers is facilitated, and some really cool automation can be brought to bear on the task of building a system.

So what IS Spring Boot?  It's really a few classes and conventions wrapped around Spring that frees the developer from a lot of the grunt work that used to be required.  For instance, the need for xml configuration files has been essentially eliminated.  Can I get an amen?  There is a lot more to it, but why don't we just dig in and create a simple application?

package com.oopuniversity.hellospringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class App  {
    public static void main(String args[]) {
        SpringApplication.run(App.class, args);    }
}

There you have it.  A complete application which does nearly nothing...  And yet it's really got a lot going on inside of it.  This will actually create an application server listening (by default) on port 8080.

If we run this program we will see output like this:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2018-03-19 20:08:06.184  INFO 248504 --- [           main] com.oopuniversity.hellospringboot.App    : Starting App on Razer-Laptop with PID 248504 (C:\Users\jd\workspace\basics\hello-spring-boot\build\classes\java\main started by jd in C:\Users\jd\workspace\basics)
2018-03-19 20:08:06.186  INFO 248504 --- [           main] com.oopuniversity.hellospringboot.App    : The following profiles are active: development
2018-03-19 20:08:06.225  INFO 248504 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6a01e23: startup date [Mon Mar 19 20:08:06 EDT 2018]; root of context hierarchy
2018-03-19 20:08:07.349  INFO 248504 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-03-19 20:08:07.386  INFO 248504 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-03-19 20:08:07.386  INFO 248504 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-03-19 20:08:07.398  INFO 248504 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_152\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Razer Chroma SDK\bin;C:\Program Files\Razer Chroma SDK\bin;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\PuTTY\;C:\ProgramData\chocolatey\bin;c:\bin;c:\bin\flyway-5.0.6;C:\Program Files\MySQL\MYSQL Server 5.7\bin;C:\Program Files\MySQL\MySQL Utilities 1.6\;C:\Program Files\Git\cmd;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Amazon\AWSCLI\;C:\Program Files (x86)\Graphviz2.38\bin;C:\Ruby24-x64\bin;C:\Users\jd\AppData\Local\Microsoft\WindowsApps;C:\Users\jd\apache-maven-3.5.2\bin;;.]
2018-03-19 20:08:07.500  INFO 248504 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-03-19 20:08:07.500  INFO 248504 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1277 ms
2018-03-19 20:08:07.606  INFO 248504 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-03-19 20:08:07.609  INFO 248504 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-19 20:08:07.609  INFO 248504 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-19 20:08:07.610  INFO 248504 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-19 20:08:07.610  INFO 248504 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-19 20:08:07.898  INFO 248504 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6a01e23: startup date [Mon Mar 19 20:08:06 EDT 2018]; root of context hierarchy
2018-03-19 20:08:07.967  INFO 248504 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-19 20:08:07.969  INFO 248504 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-19 20:08:07.993  INFO 248504 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-19 20:08:07.993  INFO 248504 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-19 20:08:08.024  INFO 248504 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-19 20:08:08.131  INFO 248504 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-03-19 20:08:08.162  INFO 248504 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-03-19 20:08:08.164  INFO 248504 --- [           main] com.oopuniversity.hellospringboot.App    : Started App in 2.244 seconds (JVM running for 2.621)

That's really am amazing amount of output for what appears to be a one-liner, isn't it?  One of the beautiful things about Spring Boot (and Spring in general) is that it is well documented internally and tells you what it's doing.  Perhaps more importantly it's really good about telling you what went wrong, which is pretty much an inevitability.

Since no URIs are defined, it won't actually serve up any pages as written, but you can tell it's doing at least something by hitting it with a browser.

Spring Boot is incredibly well suited to today's world of cloud-native applications built as micro-services.  An application such as this really doesn't need anything more than a functional JVM to be spun up as one instance or a hundred.  Everything it really requires to run can be bundled into a single .jar file and distributed where needed.  There's no more hassle with deploying application servers and the attendant configuration and devops challenges.

Let's add some functionality to this little program, so that it actually does a task for us.  We're going to build a RESTful calculator.  If you aren't familiar with RESTful services you can go look up what I'm talking about, but in short RESTful services are stateless web-based services that accept parameters in a URL and return usable responses to whoever calls them.  This allows for amazing levels of integration, and every task can be built using the technology best suited for it.

Since this is really just a technology demonstrator, I will not be building any of this using best practices for project layout and the like.  All of that is ultimately important but unnecessary for the purpose of this post.

Let's start with adding two numbers.  As this will be a RESTful service, everything needed to perform the math must be specified on the URL.  I will define it like this:

/add/number1/number2

That way, all I should really need to do to add 1 and 1 is call "http://localhost:8080/add/1/1"

Doing this is really very easy.  First, I need to inform Spring Boot that I want to serve up RESTful responses.  In the real world I'd create a new class (or several of them) for this purpose, but for now I'll just add it to the same little program.



That's straightforward enough.  Now we have to put in the code to do the math:

First we will need to add a couple of supporting imports:



And then we're ready to craft a working service:



The '@RequestMapping' annotation sets up a URI with embedded variables that will be used to invoke our new service.  The @PathVariable annotation ties the embedded variables to the parameter list for our method.

Believe it or not, that's all we need to get this working:



As you can imagine, it's as straightforward as can be to extend this to additional operations.

I will leave it as an exercise for the reader to add more operations to this.  It's very straightforward and you really shouldn't have any problems doing so.

That's about it for now.  Have fun!




Saturday, June 11, 2016

Basics: Just what IS an object, anyway?

This is a pretty long one by the standards of this blog.  Try to stay with it, though, the concepts are crucial.

Whether people are experienced developers used to procedural languages or newcomers to programming in general, really understanding objects tends to be a bit of a sticking point.  It's odd, because once you start to get it, everything seems quite natural.

An object is a representation of...  something.  Sometimes they represent fairly nebulous concepts, sometimes they represent very real physical things, but in all cases they're a kind of model.  Objects have properties, just like a flower has a color or a bee has [6] legs.  Objects have methods, which are really just things you can ask them to do, like 'release pollen' or 'sting someone'.  Finally, objects have events, or at least they can generate events.  That could be 'I've been pollinated' or 'I left my stinger in someone'.  Any particular object may make use of one, two or all three of these constructs.

Objects are based on classes in Java.  There is an all too human tendency to use the terms interchangeably and I've probably been guilty of doing that, too.  Technically, a class defines how an object should be built and an object is an instance of such a class.  Basically, after you write your code you compile it to create a .class file, and then when you run your code you can make a new object from said class. Making objects is easy enough, most of them get created (or instantiated) by using the new keyword like this:

    SimpleObject myObject = new SimpleObject();

Let's break that down:

First, we have declared that we're interested in working with a variable of type SimpleObject.  In other words, someone out there has written a SimpleObject.java file that defined a SimpleObject class and you're going to make an object from that definition.

That variable will be called 'myObject'.  We have to name our variables or we'd have a really hard time referring to them in our code!

We're not referring to a previously existing SimpleObject, we're going to make a completely new one.  The actual creation is handled by a constructor inside of SimpleObject.java, and we need to rely on that constructor doing its job, correctly setting up anything within the new object that needs to be in place.

Some objects don't appear to have constructors at all if you read the code, but that just means that there is no need for a constructor to do any setup work, so the programmer was able to rely on Java creating a default constructor for them.  The code for SimpleObject may have been written either way.  We don't care at this point, we just know we can call it.  I'll get back to constructors a little later when we talk about actually writing a class of your own.

Defining an class in Java is straightforward enough.  You don't really have to do any more than create a .java file with a bit of correct syntax.  The following example is enough to make a SimpleObject class (which really can't do anything but exist):

package com.oopuniversity.simpleobject;

public class SimpleObject {
}

Of course, a class that doesn't do anything isn't very useful, but I think it's good to have a picture in your head of all the 'extra' stuff that absolutely needs to be in place.  Code can look a bit busy to new developers, and its best to know what is basically template stuff that you should make sure is there and then ignore.

Just to break it down, that 'package' statement up at the top tells the compiler where the generated class file should go.  It's basically specifying an output directory, but using periods instead of slashes or backslashes.   Packaging is primarily an organizational tool and it turns out to be an important one later on.

Then we have 'public class SimpleObject' which tells us we're defining a class called SimpleObject.  That public keyword is important, it controls whether other objects in a larger program are able to create SimpleObjects or even refer to them at all.  For now, just use 'public'.  The day will come when you start to use other modifiers for specific reasons, but if you're reading this to learn you don't have those reasons yet.

Then we have some curly braces.  Those are ubiquitous in Java programs, and basically set boundaries for chunks of code.  In this case, they are setting the boundary for the beginning and end of the class, although they don't actually contain anything.  Anything between those brackets will be considered an attempt at having something be a part of SimpleObject.

Man, four paragraphs to describe three lines...  I guess a fair amount of information is consolidated down into even that useless bit of code!  Fortunately, that stuff always stays pretty much the same.  Once you understand that structure, you can kind of stop worrying about it and move on.

I mentioned above that I would talk about constructors.  Well, that time has come.  The following code is (aside from being in a different package) precisely identical to the previous code:

package com.oopuniversity.simpleobjectwithconstructor;

public class SimpleObject {
    public SimpleObject() {
    }
}

The only differences are:

  1. We changed the package definition, which lets us have this version of SimpleObject sit in the same project as the previous version without any conflicts.
  2. Now we have something new inside the braces that define the class.

The package definition is needed because I'm keeping everything inside one big project.  Just like you can't have two files with the same name in one directory, you can't have two classes with the same name in one package.

The new stuff inside the braces is defining a default constructor for SimpleObject.  It's public which means other objects can use it to make a new SimpleObject.  It has nothing between the parentheses, which means you can create a SimpleObject without having to give it any parameters, which are nothing more than pieces of information you give it (we'll talk about those soon).  Then it has some more of those fun curly braces, which again define boundaries.  Anything inside this particular pair of braces belongs not just to the class, but to the constructor itself.

Why would you want to write a constructor like this, making your class busier?  Well, you wouldn't, and that's why you get this for free with any class you write that doesn't bother defining a constructor of its own.  However, you DO need to know about and understand this for one simple reason:  It is also possible to define a class using a constructor (or a whole bunch of them if you like) that has parameters.  If you do this, the compiler will *not* create a default constructor for you and you won't be able to use a default constructor unless you explicitly write one.

https://github.com/OOPUniversity/OOP_Basics

Sunday, June 5, 2016

Put a Spring in your step

I don't know about you, but when it came time for me to figure out Spring's Java Annotation based configuration, I found it difficult to know what I really needed to do.  Between well-meaning but outdated online tutorials, many different versions of the software each with its own quirks, and some guys who just plain got it wrong, I found the process far more confusing than it should be.

In fact, once I stripped a program down to its most basic elements (and I don't think there's much left to do here at all), it's kind of embarrassing to think I ever had a problem with it.  In short, it's short.  I found myself left with three classes, a few annotations, and a working program.

Then just to gussy it up a bit, I created a complete alternate implementation of the entire package tree, which you can cause the program to use by specifying the package name as a command line parameter.  You can create other implementations as well, link them in via separate jar files and run those, too, so long as the classes in question implement the interfaces in the 'resources' package.

Without further ado, here is the Spring Java Config Demo.  I may update it with a few additional features in the days to come, but whatever I do add will be done in the most minimalist fashion possible.

JSON? What is this, Friday the 13th?

JSON stands for "JavaScript Object Notation", and it is nothing more than a standardized format for pushing object properties around in text format.  This is handy for many purposes, especially for transmitting objects over networks.  I can create objects in Java, convert them to JSON, and then read them in Javascript on a browser.  That's all kinds of handy.

There are plenty of tools for working with JSON,  I personally like Jackson from fasterxml.com.  This package provides a great deal of functionality in an easy to use form.  It's not the only JSON library out there, not by a long shot:  But it's simple, quick, and widely used.  It's also one of the core technologies selected for the 'DropWizard' framework, which I'll be talking about in another post.

Have an object and want to make a JSON representation?  Then ObjectMapper is the tool for you:

First of all, let's create a simple object called 'Person'.  For the sake of simplicity, we'll assume that all we care about is the name.

public class Person {
    private String givenName;
    private String surName;

    // This object has to be a Bean, which means it needs a no-argument constructor    

    public Person() {}

    public Person(String surName, String givenName) {
        this.surName = surName;
        this.givenName = givenName;
    }

    public String getGivenName() {
        return givenName;
    }

    public void setGivenName(String givenName) {
        this.givenName = givenName;
    }

    public String getSurName() {
        return surName;
    }

    public void setSurName(String surName) {
        this.surName = surName;
    }

    @Override    public String toString() {
        return "Person{" +
                "givenName='" + givenName + '\'' +
                ", surName='" + surName + '\'' +
                '}';
    }
}

This import statement is important, and of course you'll have to get the .jar file to support it.  I would suggest just using maven to deal with that.

import com.fasterxml.jackson.databind.ObjectMapper;

...
    ObjectMapper objectMapper = new ObjectMapper();
    Person p = new Person("Doe", "John");
    String jsonRepresentation = objectMapper.writeValueAsString(p);
    System.out.println(jsonRepresentation);

Going back the other way is even easier:

Person p2 = objectMapper.readValue(jsonRepresentation, Person.class);
This works very well within a single project of course.  Let's say you  need to persist your objects to disk for later use.  Well, the JSON representation gives you an excellent way to do this without running into the various issues that straight Java object serialization can raise.  Your files will be human-readable, human-editable, and they're much less likely to become unusable because you changed an object definition.  What's not to love about that?
In fact, reading and writing files is an extremely simple operation with Jackson.  The ObjectMapper does most of the hard lifting for you and turns basic (or not so basic) persistence into one line operations.  If you wanted to take that Person object up above and stash it in a file on your hard drive for later use all you'd need to do is this:
objectMapper.writeValue(new File("JohnDoe.txt"), p);
Reversing the operation is almost as easy:  You just need to use one special little piece of syntax to tell ObjectMapper what kind of object you are creating:

Person p2 = objectMapper.readValue(new File("JohnDoe.txt"), Person.class);
We've basically now recreated what we did in the first couple of examples, but we're able to run one example today and the next one tomorrow after restarting the computer if we want, since instead of just sitting in a String in our program's memory the important information is now sitting on your hard drive.  The file looks like this, by the way:
{"givenName":"John","surName":"Doe"}
JSON is also great for transmitting data over networks.  In fact, if you take a look at RESTful services (which I will visit in a future post) JSON is a standard way of communicating with them.  You don't even have to care what language the remote system uses.  Just so long as you both agree on the set of properties to be sent, the other end could be written in C, .NET, JavaScript (hey, look at what the 'J' stand for in the first place) or any other language.  Maybe the other end is also written in Java, but it was developed by someone else who doesn't have access to your library with your definition of Person.  That's perfectly OK, they can roll their own very easily and so long as the properties in your JSON are all supported everything will just work:
Let's pretend we are on the other side now, and the file created above was sent to us.  We want to bring the data into our system using our home grown "AnotherPerson" class.  For demonstration purposes, the class is exactly the same as the "Person" class above, except for the property names.  So it contains code like this:
public class AnotherPersonNoAnnotations {
    private String firstName;
    private String lastName;

    // This object has to be a Bean, which means it needs a no-argument constructor    

public AnotherPersonNoAnnotations() {}

    public AnotherPersonNoAnnotations(String lastName, String firstName) {
        this.lastName = lastName;
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    ...

When we try to read the object, we do this:
AnotherPerson p = objectMapper.readValue(new File("JohnDoe.txt"), AnotherPerson.class);
And it fails spectacularly!
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "givenName" (class com.oopuniversity.json.model.AnotherPersonNoAnnotations), not marked as ignorable (2 known properties: "lastName", "firstName"])
 at [Source: {"givenName":"John","surName":"Doe"}; line: 1, column: 15] (through reference chain: com.oopuniversity.json.model.AnotherPersonNoAnnotations["givenName"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:62)
...
The actual error will be followed by a whole bunch more stuff, but the important information is right at the top.  And notice:  This is an extremely useful error message.  It tells you exactly what went wrong and why.  It's an "UnrecognizedPropertyException" which means exactly what it says:  Jackson did not recognize a property it found.  Then it flat out tells you that 'givenName' is the problem.  It also tells you which properties it can recognize.  Then to top it off it shows you the exact JSON it was trying to read.  I wish all libraries were this good at telling us what went wrong.
So now we know that our object supports "lastName" and "firstName" but the data contains "givenName" and "surName".  Fixing this is quite simple.
Not to worry, even though we have different names for our properties we'll be fine.  This is far from an uncommon situation and Jackson has it handled.  All we need to do is add a couple of  'annotations' to our code.  Annotations are a clever addition that was made to Java years ago.  Classes, properties and methods can be annotated in order to add new behaviors.  In this case, we'll use them to inform Jackson that we are expecting different field names.  We change our 'AnotherPerson' class so that the declarations look like this:
public class AnotherPerson {
    @JsonProperty("givenName")
    private String firstName;
    @JsonProperty("surName")
    private String lastName;
I think that's pretty self-explanatory.  We're telling Jackson that when it's processing our file, it should think of our 'firstName' field as though it was called 'givenName', and of course the same thing applies to 'lastName' and 'surName'.  These annotations affect both reading and writing and now our class, while it uses our preferred variable names internally, looks to the outside world exactly like the Person class listed above.
Now our attempt to read the file works beautifully:
AnotherPerson{firstName='John', lastName='Doe'}
This is not all there is to say about  JSON processing with Jackson, but it is certainly a good start.  I'm sure I'll be talking about it more in posts to come.  I mentioned but did not talk about using this stuff to communicate between running systems (via RESTful services) and that's a key area that many developers will want to understand.
A code repository with working examples can be found here.
https://github.com/OOPUniversity/JSON_Basics

Friday, June 3, 2016

Super basic object stuff

I am not going to rework this right now, I think it gets the main points across as is.

From a recent Reddit post:

What you are asking about is quite basic to object oriented programming. Let's start with the first point I'd like to make: PersonA and PersonB are exactly the same thing, except the data is different. However, they cannot be simple methods that return integer values, that will never fly. The values you're setting up are lost as soon as the methods end.
Instead, you want to create objects of type Person. You do this by creating a class called Person and setting up variables to represent the values you want. At its absolute most basic (and this isn't correct, it's just showing the idea) it would look like this:
public class Person {
    public int x;
    public int y;
    public int range;
}
This is more akin to what we used to call a struct in c. Ordinarily you'd have a lot more stuff in there, but adding that right now could inhibit understanding so I want to take this slowly.
With the above class you could do this in the class you've posted:
public static void main(String [] args) {
    Person a = new Person();
    a.x = 200;
    a.y = 100;
    a.range = 160;

    Person b = new Person();       
    b.x = 100;
    b.y = 400;
    b.range = 170;
After that, you could use 'a.x' or 'b.range' the same way you were originally trying to use 'xA' or 'rangeB'.
Remember when I said that I was just showing the basics? Well, objects are a lot more powerful than just bags of variables. Let's use just another couple of features.
First, let's make a 'constructor' for Person so you can slim down your code:
public class Person {
    ... //What you already have
    public Person(int newX, int newY, int newRange) {
        x = newX;
        y = newY;
        range = newRange;
    }
}
Now your main can do this:
Person a = new Person(200, 100, 160);
Isn't that nicer?
Next, let's add 'accessor' methods to Person. Accessors are also called 'getters' and there are good reasons to use them. Trust me on this, I'm on the train and don't have time to fully explain:
public class Person {
    ... //What you already have

    public int getX() {
        return x;
    }

    //Do the same thing for 'y' and 'range'
}
At this point, you could still do 'a.x = 5' or 'range = b.range'. We can prevent that by marking the variables as 'private'
public class Person {
    private int x;
    private int y;
    private int range;
    ... //what you otherwise already have
}
But wait! Now when I try to write a.x=5 I get some horrible error and everything is broken and the world is ending!
No, you just need 'setters', also known as modifiers to do the job for you:
public class Person {
    ... //Everything you already have
    public void setX(int newX) {
        x = newX;
    }
    // Follow the same pattern for y and range
}
Now the equivalent to 'int range = a.range' is 'int range = a.getRange()', and the equivalent of 'a.range = 50' is 'a.setRange(50)'.
There's a LOT more to OOP, we've really just scratched the surface. But just encapsulating your data in this way will go a long way towards making your programs more readable, maintainable and robust.
I have no doubt that questions are coming up in your mind. I tried to make this clear and left out a few niceties in the interest of getting it written quickly and not overloading you, but it's a lot to absorb. Please ask questions when you need clarification.

Sunday, November 15, 2015

There's a loop for each of us

This is one of the really useful additions to the Java language specifications.  It greatly simplifies many loop structures, eliminating a bunch of verbiage that we long thought was just part of the deal when writing code.

Let's meet what I hope will become a good friend of yours:  The enhanced for, also known as the 'for each' loop.

The for each loop structure is an enhancement that can be used to replace many of the standard for or while loops you would otherwise be writing.  It is extremely common to have to, for instance, go over the elements of an array or a collection, extract one element at a time, and perform operations on it.  Let's pretend that we have an ArrayList of Person objects, and we want to print a list of first and last names.

In the old days we might have written this (and if you don't understand why I use 'List' instead of 'ArrayList' see 'Good Practices: Coding to the Interface'):

public static void printPersonList1(List personList) {
    System.out.println("Using a 'while' loop the JDK 1.4 (and earlier) way:");
    Iterator iter = personList.iterator();
    while(iter.hasNext()) {
        Person p = (Person) iter.next();
        System.out.println(p.getFirstName() + " " + p.getLastName());
    }
}

Now, one improvement was the addition of 'Generics', which allowed us to simplify the code a bit by informing the compiler that our List and Iterator had to be of type Person:

public static void printPersonList2(List personList) {
    System.out.println("Using a 'while' loop with generics:");
    Iterator <Person> iter = personList.iterator();
    while(iter.hasNext()) {
        Person p = iter.next();
        System.out.println(p.getFirstName() + " " + p.getLastName());
    }
}

Now, you might be wondering why I did my demonstrations of old style code with while loops to demonstrate a better for loop.  This is mostly because the while loop syntax is better suited to running over an Iterator than an old style for loop was.  It could be done, but frankly it's not as clean.  You'll note I had to leave out the third term of the for loop because it only gets executed after the body of the loop is complete and I had to pre-seed with the first value:

public static void printPersonList3(List<Person> personList) {
    System.out.println("Using a 'for' loop with generics:");
    Person p = null;
    for(Iterator <Person> iter = personList.iterator(); iter.hasNext(); ) {
        p = iter.next();
        System.out.println(p.getFirstName() + " " + p.getLastName());
    }
}


Alternately, we could have skipped the Iterator altogether, which is really more in keeping with the natural usage of the old style for loop:

public static void printPersonList4(List<Person> personList) {
    System.out.println("Using a 'for' loop with no iterator:");
    Person p = null;
    for(int i = 0; i < personList.size(); i++) {
        p = personList.get(i);
        System.out.println(p.getFirstName() + " " + p.getLastName());
    }
}


OK, here's the actual example I'm trying to get across to you.  This is the 'enhanced for' loop, also knows as the 'for each':

But the for each loop construct went a lot further and made things much better:

public static void printPersonList5(List<Person> personList) {
    System.out.println("Using a 'for each' loop:");
    for(Person p:personList) {
        System.out.println(p.getFirstName() + " " + p.getLastName());
    }
}

Note how concise it is, with no extra stuff.  Get Person objects from this collection and run with it.  Using the enhanced for loop simplifies our code, letting us get on with the conceptual task at hand and saving our fingers from some typing.  It's extremely common to go over a collection of data and perform some task on every element, so why should we have to write it all out explicitly every time?  You can use for each loops on classes based on Collection and on arrays equally well, which means we're more likely to use it and get the code right the first time.

private static void printStringArray(String[] aList) {
    System.out.println("The enhanced for can also work on array types:");
    for(String s: aList) {
        System.out.println(s);
    }
    System.out.println();
}

It actually took me a while to get used to using this loop structure, because I spent so much time supporting code that had to run in 1.4 level JREs.  In order to ensure the best compatibility I was also compiling with a 1.4 JDK so I didn't have access to this feature.  I'll tell you what, I was really missing out.  My fingers are probably a couple of millimeters shorter than they should be because of all the wear and tear from the extra typing I did.  I for one am glad we have this loop available, and you probably should be, too.

View Code


Friday, November 13, 2015

Design Patterns: Singleton

The word 'singleton' is used to describe a design pattern for objects where only one instance of the object is allowed to exist.

It would technically be possible for you to use nearly any Java class as a singleton by being very, very careful to only create one instance and use it throughout your application.  But why do you want to work that hard?  It's pretty easy to force a class to act as a singleton with a few lines of code.

First of all, we make sure that there is no constructor available to the public.  This means we must create at least one constructor and mark it with the keyword private.  This will keep random objects from just creating their own instances of the class you wish to protect.

    public class MySingletonClass {
        private MySingletonClass() {}
    }

Of course, that means you can't create your single object either!  Never fear, we can get around that.  After all, the singleton class itself can still invoke the constructor.  Since we can't make an instance, though, it will have to be a static method.  I prefer to call it 'getInstance' because that's a good description of what it does.

Of course, it's not safe or desirable to have getInstance just create a new object each time it's called.  So instead we'll store an object reference of the classes' own type inside it and use that:

    public class MySingletonClass {
        private MySingletonClass() {}
        private static MySingletonClass singleton = null;
        ....
        public static MySingletonClass getInstance() {
            ....
            return singleton;
        }
    }

And the rest is just the work that needs to be done to make this function reliably:

     public class MySingletonClass {
        private MySingletonClass() {}
        private static MySingletonClass singleton = null;
        ....
        public static MySingletonClass getInstance() {
            if (null == singleton) {
                singleton = new MySingletonClass();
            }
            return singleton;    
        }
    }

So what have we done here?  We've created a class that can't just be instantiated by anyone.  Instead, we've enforced a contract on client classes, one that states they can only create one copy of this object.  Whichever object attempts to obtain the singleton first will (unknowingly) be responsible for creating it as well in a case of lazy initialization.  The getInstance method is our gatekeeper for this, handing out the same object reference whenever asked:

    MySingletonClass aSingleton = MySingletonClass.getInstance();

As you can see, using it is pretty easy.  You could of course provide parameters to this method and pass them on to the constructor if needed.

Wednesday, November 11, 2015

Stop giving me so much static

Let's talk about the keyword static for a moment.

There are two different uses for this in our code.  It can be applied to methods or it can be applied to variables.

When static is applied, it disassociates the item being declared from any specific instance of the class.  For methods, this means that the method can be called by anyone at any time without creating a new class of that type.  This can be particularly handy for utility functions, initializers, or any other chunk of code that wants to run without caring that it's about a particular person, bill, or list of stocks.  For variables, it mostly means that the value is shared across all instances of the class.

Static Methods

Static methods can be called without making a new class.  For instance, it could be used for a factory method, which is a design pattern that calls for objects to be built by calling a function to do so.

public class Person {
    ...
    public static Person createPerson(firstName, lastName) {
        ...
    }
}

You can call createPerson without having a Person object, like so:

Person.createPerson("John", "Doe");

Many utility functions are declared as static, and as a general rule they will need to operate free of any context supplied by objects.

Static Variables

Static variables come from the same basic idea of being disassociated from any specific instances of the class.  They're useful for maintaining overall context, for instance, if we want to keep track of how many Person objects we've created we could write something like this:

public class Person {
    ...
    private static int numberCreated = 0;
    ...
    public static Person createPerson(firstName, lastName) {
        ...
        numberCreated ++;
        ...
    }
}

Now, every time we invoke createPerson, we'll also be incrementing the value of numberCreated, and it will always be available as a statistic our programs can check.

Many times, inexperienced programmers will overuse static methods, because when they first start creating methods and functions, they just call them from main.  Your main method has to be static, and if you try calling non-static methods directly from it, the compiler complains.  So the path of least resistance is often seen as just making those other methods static too.  This does seem to work, but it goes against object oriented design principals, and it's best to nip this in the bud.  So they start with this:

public class OutputTest {
    ...
    private PrintStream outputStream = ...;
    ...
    public static void main(String [] args) {
        print("This is a test");
    }
    ...
    public void print(String message) {
        outputStream.println(message);
    }
}

But that fails because you can't call 'print' from a static context, so they change it to this

public class OutputTest {
    ...
    private PrintStream outputStream = ...;
    ...
    public static void main(String [] args) {
        print("This is a test");
    }
    ...
    public static void print(String message) {
        outputStream.println(message);
    }
}

That fails, too, because outputStream isn't static, so they change the code again:

public class OutputTest {
    ...
    private static PrintStream outputStream = ...;
    ...
    public static void main(String [] args) {
        print("This is a test");
    }
    ...
    public static void print(String message) {
        outputStream.println(message);
    }
}

And they're satisfied.  Everything works now!  I call this the static cascade, and I recommend avoiding it.  If you did not originally intend for these items to be shared and free of binding to specific objects, then don't go changing them to act that way.  

Get used to writing object oriented code.  Do this instead:

public class OutputTest {
    ...
    private PrintStream outputStream = ...;
    ...
    public static void main(String [] args) {
        OutputTest test = new OutputTest();  //The key!
        test.print("This is a test");
    }
    ...
    public void print(String message) {
        outputStream.println(message);
    }
}

While it might be a bit more of a conceptual leap, it's actually a far smaller change to the original code, and it opens your class up to being more adaptable to use in other systems.  It's also a necessary step towards object oriented thinking, so you might as well get it over with now.

It's the final countdown!

Many times we declare a variable that we really ought not to change, at least in some particular spot.  We can just remember not to change it, and that might work.  A better solution is to let the language keep us from even trying, and Java offers us the final keyword for this purpose.

A variable declared as final cannot be changed, so maybe the word 'variable' does not even really apply, so we can call them 'constants' if we like.  This has a couple of different purposes.  First off, we might want to set up a constant like an approximation of pi for use in a class that does geometric calculations:

static final float pi = 3.14159;

Now any code that tries to change pi will be flagged by the compiler as a problem.

Another use for the final keyword is to make sure that methods don't modify parameters we've given them:

public void calculateValue (final int quantity) {

This would make sure that we don't accidentally change quantity somewhere inside the calculateValue method.

The compiler is able to simplify the code that it generates for variables declared as 'final', so we get that benefit, too.  In short, it's a good idea to declare things as final whenever it's reasonably possible to do so.

Tuesday, November 10, 2015

I tried to print my array but all I got was gobbledegook!

This is inspired by a post at /r/javahelp.

A user posted that they were trying to print a sorted array to the console with System.out,println, and that instead of anything that made sense they got [I@4969dd64...  So clearly something was wrong and the array was not being sorted.

But that's faulty troubleshooting, as one could tell by just trying to print the array before sorting.  You would see basically the same thing.

The reason for this is that when you do a System.out.println on any object, what you're actually doing is calling 'toString()'.  If you are printing your own objects for which you've created nice methods that override the default toString, you get nicely formatted output.  If you're using an ArrayList you get a nice, comma separated list enclosed in square brackets.

Arrays are more primitive than that.  Their default toString is just the one from Object, and it does nothing more than tell you where in the heap the object is located.  This is good for verifying that something isn't null, but useless for determining the content.

If you want to see the contents of the array, you've gotta do the work yourself, my friend.  And it's not difficult at all.  This, for instance, will work for any array of Objects that themselves support a reasonable version of 'toString':

public static String arrayToString(Object[] theArray) {
    StringBuilder output = new StringBuilder("[");
    for (Object o:theArray){
        if (output.toString().length() > 1) {
            output.append(",");
        }
        output.append(o);
    }
    output.append("]");
    return output.toString();
}

View code

Tuesday, February 10, 2015

It's a SERIES OF TUBES!

I've been struck in recent days by a number of posts over at /r/javahelp, all with the same basic theme.  They've got some code, and it references a variable name that is declared elsewhere in the program.  These nascent developers don't yet understand that just because you mention a variable in one place, that doesn't mean it's available elsewhere.

It is fundamentally important to understand the issue of scope if you ever hope to write programs well.  Where you declare things, and what keywords you use when you do so, have a huge effect on the visibility of your variables.

For instance, I often see issues that boil down to an attempt at doing this:

void multiplyTwoNumbers(int numberOne, int numberTwo) {
    int numberThree = numberOne * numberTwo;
}

"It doesn't work" they say, or "it doesn't do anything".  My friends, it does exactly what you told it to.  It's just that you didn't tell it to do anything particularly useful.  When this method is finished, it will have multiplied numberOne by numberTwo and assigned its value to numberThree.  Then it's done.

Some folks go a bit further:

void callingMethod() {
    int numberThree;
    multiplyTwoNumbers(5,10);
    System.out.println("See?  It didn't work! " + numberThree);
}

And they're right, it didn't.

The reason is that the two variables named 'numberThree' are entirely independent of each other.  One of them is really 'callingMethod->numberThree' and the other one is 'multiplyTwoNumbers->numberThree' and they have never met.

Naming things the same is meaningless.  It might help us to understand our code better, but as far as Java is concerned the variables might as well be called Ben and Jerry.  Mmmm, Ben and Jerry.

If you really want callingMethod->numberThree to take on the value you calculated in 'multiplyTwoNumbers' you need to explicitly lay it out.  Just as you can't expect your sink to drain properly into the sewer system if you don't actually provide a continuous connection, you can't expect what one method does to just be known by another method.

So make sure you declare multiplyTwoNumbers as an int.  Make sure you actually return the value of numberThree at when it's done:

int multiplyTwoNumbers(int numberOne, int numberTwo) {
    int numberThree = numberOne * numberTwo;
    return numberThree;
}

That will help.  You've now installed the pop-up drain thingie in the bottom of the sink bowl.  Let's finish the job:

void callingMethod() {
    int numberThree;
    numberThree = multiplyTwoNumbers(5,10);
    System.out.println("It verks! " + numberThree);
}

This is so important to understand.  Local variables go away as soon as the local block (code between { and }) comes to and end.  If you don't provide a method for the value to escape the block, it's going to go to the big heap in the sky.

Perhaps part of the problem is that people get confused by the fact that they can do this:

public class Wizz {

    int wizzLevel = 0;

    public void bumpWizzLevel() {
        wizzLevel = wizzLevel + 1;
    }

    public void displayWizzLevel() {
        System.out.println("Current level: " + wizzLevel);
    }
}

Yes, that's perfect valid.  In this case, 'wizzLevel' is an instance variable of the class Wizz.  Every copy of Wizz you create has its own wizzLevel, and all methods within Wizz can reference or change it.

The key of course, is to look at the brackets.  Note that 'int wizzLevel' is inside the brackets for the class as a whole, so it's in scope everywhere within the class.

The key takeaway is that when you want to understand where  a variable is available to you, you need to understand that so long as you are still inside the same set of brackets where it was declared you should be good to go.

{
    int outside;
    {
        int inside; //outside is still available
        {
            int wayInside; //inside and outside are still available
        }
        //wayInside is gone
    }
    //inside is gone
}
//outside is gone