Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Monday, 15 March 2010

Old MATLAB Improvements, Java Data Objects Primer

Matlab m-file (Download and run) 

Matlab Source Code (to view online)

For the most part I haven't changed the workings of this code. I did change one error dialog that told you the height needed to be between 0 and 20,000 meters when inputting an incorrect value for the height increments. Just a copy-paste situation where I forgot to edit the message. The big changes here are comments. It's quite thoroughly commented now and should be a bit easier to follow. I also commented-out the "Standards Selection" box, which was unusable, and centered the title information to make it look more natural. Finally I cleaned up a function call that was passing the constants array despite the fact that the other function had full view of the same array. Basically, unnecessary transferring of variables. Theoretically should have sped up the code. Considering the ambiguity of some of this code and the amount of time that passed between writing it last and doing this editing, I'm quite pleased with my ability to understand what was performing which actions throughout.

After finishing that I decided not to start the new assignment yet. Instead I started reading my book on JDO. The more I read, the more excited I get about the system. It really seems quite easy to work with and I'm excited for the implementation of it all.

I'm not sure I've talked much about JDO and why it's important to my application and Java in general, so here goes. Java code is run in a Java Virtual Machine. This is what enables it to be so universal... once the JVM is started up, one computer "appears" to be exactly like any other. At least in terms of executing the code. Unfortunately, every action the code performs is done in this Virtual Machine, and this means that everything that's been done is deleted when the code finishes, as the code finishing results in the JVM being closed. Saving in Java is done by file output during the execution of the code, by Serialization, or by storing the values of a class's variables in a database.

The first, file output, is mostly for saving a text file or similar. It's simple and useful sometimes, but it's simple and therefore not useful other times. In the case of my simulation, it's impractical due to the methods of parsing a text file back in (it would take AGES) and due to the ease of editing that text file between sessions to hack the game. Besides that, saving the file on your computer makes it tough to have an exciting multiplayer experience.

The second, Serialization, is complex. Essentially it converts the state of an object into a stream of bits and bytes, then on loading deserializes it back into its object form. These bytestreams can be large, but more importantly it's a bit unwieldy to program a class to be Serializable and program the Serialization and Deserialization across a full application like the simulation. There's also, again, the problem of things being stored on a client computer and making multiplayer a bit lackluster.

The third is storing values in a database. To start with, we'll ignore JDO. Storing values in the database means building a database (using SQL, most likely), linking the Java code up with it through the JDBC API, and programming in all the possible commands for editing the database that the client will ever use. While it sounds daunting, it's certainly doable and it had my vote for a while. Every time the client-side application is run, the user would log into the database and it would load all of his/her details, initializing all the objects necessary and setting the values back to what they are in the database.

Then comes JDO. JDO is a standard that allows me, as a Java developer, to program everything in Java code. I don't need to build my database with SQL to start with, I don't need to include ridiculous amounts of SQL hidden among the Java I'm writing, I don't need to specially format my classes. All I do is write the class as normal, enhance it with an automated tool (which builds into the class all of the methods necessary to view and edit it, automatically), initiate my database with a similar automated tool, and tell my program to make an object persistent whenever I need it to. Loading that object isn't always done per se, more often you just access the values in the database. It's just that those values are set within the Java application and without any complicated translation are plopped into the database in a Java-accessible structure.

It's really the easiest of the bunch I've seen so far. I can't wait to actually use it.

But first... I have more MATLAB to code.

Saturday, 13 March 2010

Contract for the Material class

Today's post is mostly organization for me, setting down guidelines for the Material class I'm working on. Still, this could also serve as an informative post as I'm using strategies set out in some of my books.

A contract is essentially what the name implies: a list of terms and conditions. In these particular circumstances, it's a list of things that the class is expected to be able to do. In the professional world, a contract is often what a programmer will receive. How the person works out the inner dealings of the code is unimportant, so long as they accept inputs defined by the contract and return outputs defined by the contract.

So, without further ado, the Material contract:
The Material class must be able to:
-Create a new instance, with String inputs name and matcode.
   -Verify the formatting of the input (11 characters, a-z only).
   -Convert the characters of the matcode to integer values 0-25.
-Include classes to set individual attributes with int 0-25 input.
-[OPTIONAL] Include classes to set/get attributes by name.
-Include a class to get the current matcode of the material.
-Include all classes to produce a GUI to view and modify the material.
   -Construct input panel.
   -Construct edit panel.
   -Construct output panel (display graphic).
-Include a list of market prices for the past 12 weeks (or more).
   -Method to set current price (saving old price as above)
   -Method to archive prices when they're removed from above list.
   -Method to get current price
   -Method to display a graph of past prices
   -[OPTIONAL] Display graph including archive.


I'm pretty sure that's all, at least for now. I think it's safe to say that everything except the market prices has been coded, though it hasn't all been migrated to be within the Material class.

Remember I said that it's up to the programmer to decide how to then code the inner workings? That's how I think I've come up with another class. And then from the fact that I'm also developing the whole thing, I decided on another still. Internally, the Material class will also host the MatCode class. This class will make it easy for a Material method to alter a specific attribute by calling methods within that class. It will allow for error checking, editing materials by supplying integer OR character values, and overall serve to be a convenience class for making the Material class look cleaner. That said, it won't be needed outside of the Material class and serves as a good internal class.

As an external class, I need Price. Basically all it does is store a price and the date that price was set. It will be used for a number of different objects and needs to be outside of the Material class. Mostly, it makes the eventual database more useful when the price is its own object storing pertinent information.

With these done in a day or two, I'll be able to move on to the next class, probably Planet. But also expect some work done on both my old MATLAB project (ISA Calculator) mostly in the form of adding comments, and my new MATLAB project.

Wednesday, 3 March 2010

"Bob" the Builder (pattern)

So, I've heard of Java constructors. These friendly little guys make an instance of an object when the program calls them, setting variables if necessary, making everything work the way you need to. Today, however, was the first time I'd heard of Builders.

Constructors can, sometimes, get really messy. "Setting variables if necessary" can get to the point where you have 20 variables to set and 18 of those are optional. It's nasty to program a constructor to properly handle optional variables and it's nasty to call a constructor with all of those variables. And who wants to print out a list of which variable comes when in the call to the constructor?

Hello, builders. Builders are like flexible constructors, but they require a bit more manipulation to set up properly. Basically a builder is a class placed inside the class you want to construct, and no constructor is made available for that class. Instead, you call the constructor for the builder (in Java syntax this means you call something like endgoal.builder() where endgoal is the thing being built), with any required values included in the () after builder. Then you continue calling optional values by adding .option1(), .option2(), and so on until the object is fully set up for you. All of the values that eventually go into your endgoal object are stored privately inside the builder class so as not to cause any funny business on the part of your outer class.

When you're all done, you call the endgoal.build() class to put it all together for you, as necessary.

What am I using this for? At the moment, validation on the text box used to enter Material Codes. Matcodes must be 11 characters long, consisting only of english alphabet letters. I convert the input to uppercase inside the material code interpreter's method, so it's not a big deal what case you use externally, but internally it does make a difference.

I realize that the matcode input is not the only text field I'm going to use, and in searching for the way to limit the maximum number of characters in a text field I've come to the conclusion that it requires making a so-called "Document" that tells the input box how to behave. This is easy enough, but why code a separate document for each text input when I can just create a builder?

For now I'm coding in the options to change the input to Upper/Lowercase depending on needs, to force the input to be alphabetical, numerical, or both, to set a maximum length onto the input, and finally to allow or disallow spaces in the input. In the case of my matcode text box, I'll call something like:


input.setDocument( new JTextFieldLimits.LimitBuilder()
.charLimit(11).toUpperCase().forceLetter()
.forceNoSpace().build() );

It looks a little nasty but for my sanity it's better than something more like:

input.setDocument( new JTextFieldLimits(true, 11,
true, false, true, false, false, true));

where I have to remember which position responds to which value every time I make a new input box. And that would be even longer if I come up with more options to throw in here. Don't forget that if all I want to do is disallow spaces, with the builder I can just do LimitBuilder().forceNoSpace().build() whereas with the other one I have to include all of the "false" values until the very end. And Java forbid I forget how many false values that adds up to.

The JTextFieldLimits class isn't quite finished yet, but it's progressing smoothly and I don't think I'll run into too many problems with it. Once that's done I'll get back to work on isolating the MatPolygonDraw class by having it build its own panels. I think I'll have both of those done before my next post.

Reference: http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html Thanks for the help!

Tuesday, 2 March 2010

Compartmentalization, Encapsulation, and Isolation, oh my!

I've been focusing a lot on these inheritance features today. I know, for instance, that I can create a class Planet, and that I can also create a class Moon extends Planet, so that the two are differentiated in name but don't need repetitive coding. I've been considering the pros and cons of making all of the attributes I've taken to calling low-level attributes (a planet's name, for exmaple... the things that the object stores that don't reference other objects) implement a custom interface.

Time for some explaining? I think so. In Java, a class (known as a child or a subclass) can extend another class (known as a parent or a superclass). This means that, unless an underlying method in the child overrides the parent's method (this is done simply by creating a method in the child with the same name as the parent's method), the methods defined in the parent are equally as applicable to the child. In the case of class Planet and class Moon extends Planet, as above, the method getSize() would return a number representing the planet's diameter, and would do the same for a Moon even without explicitly rewriting the code.

Now on to implementing interfaces. An interface is an abstract class, which means that it cannot be used directly. Instead, when a class implements an interface, everything written into that interface MUST be overridden by the new class. If I have attributes, to use the example above, which all have different variables within them (say, a description attribute holds text describing the object, an armor attribute holds a value representing the armor's strength), I can create an interface that defines getType() and getValue() as methods that MUST be overridden, therefore making the attributes universal in structure.

A Java class can extend only one parent lass, but can be extended by infinitely many children. A Java class can implement as many interfaces as it wishes, so long as all of the underlying methods are overridden. Because of the way these two aspects of "inheritance" work, they are known as two related but separate pathways of defining a new class. By making a new class a child of a parent class, you are inheriting behavior. That is to say, all of the 'hows' in the class are defined by the parent class, except for the occasional overriding method or additional method. By having a new class implement an interface, you are inheriting structure, because the layout of the new class must match the interface, but the specific algorithms used are specific to the new class.

There's my brief lecture on Java's inheritance. That out of the way, I haven't done coding work today, seeing as I instead attended a showing of "Willy Wonka and the Chocolate Factory" (that's right, the original) at the University. I did get a lot of (additional) thinking in and I realized one of the shortcomings in the current embodiment of the interpreter I showed yesterday. I have a button that is specialized for the window I showed you, not one I can place into just any window I place the graphic into. This also means that when I go to make a more capable "administrator" version that allows me to generate material codes on-the-fly, I'll have to completely reprogram that button.

Instead I can use some nifty features of Java's by including a specialized button subclass into the class that creates the material graphic. This subclass would be inherently tied to the material graphic that the button updates, and wouldn't require any coding except placement in the larger window.

Overall this would greatly increase the capabilities of the materials panel I've made, as well as the capabilities of any future classes I make. I consider this Compartmentalization (and I think the textbooks agree with me) because it means that any frame that uses the MatCodeInterpreter will, without extra work, be able to add the necessary buttons and fields to manipulate it.

I think tomorrow will see me working on making that a reality.

Tuesday, 23 February 2010

The Platypus: Object-Oriented Programming Primer

So, about that material decoder. Maybe tomorrow? I didn't have time for much coding today, but I have done some reading. Platty Pat apparently has been given the name Phyl by the author, but I like Platty Pat better so I'm sticking with it.

So what is Object-Oriented programming, anyway? According to this book (I need to give credit where it's due, so the book in question is: "Understanding Object-Oriented Programming with Java" by Timothy Budd. ISBN: 0-321-21174-X for my particular version), it's all about creating code in sections, called objects, which are essentially independent. Each object has its own responsibilities and its own way of accomplishing the tasks set out for it. In principle, there should be only a couple of interconnections between objects, and objects should be reusable from project to project without major restructuring. The program should also be separated such that major feature changes (graphical updates or saving to a different format or what-have-you) should only take updating one or two of the objects, as the other objects don't rely on what's in the other things, but what comes out of them.

I've been reading a bit about the class-oriented nature of Java, which, as I've said in the past, is the biggest part of what the book is about, and the biggest thing about Java I feel I need to understand more clearly. It's the reason there's a platypus on the cover of the book, because if you extend the class structure to real life, the platypus 'extends' the 'class' mammal but 'overrides' some 'methods,' primarily birthing. Anyway, basically a convenient metaphor that sums up a lot of the features of class-oriented programming.

Right now they're going through the design process behind it all, and it certainly is a lot different than what I've done so far--a kind of disappointing fact considering most of the books I've studied have been based around Java, so it would have been nice if it had started with Object-Oriented facets of the language. That said, given my as-yet limited experience with programming, it shouldn't be hard to switch to their methodology, which definitely seems like it would help.

It's interesting stuff and it's something I'm definitely going to take into consideration. Especially on account of the conversation I had today with a friend about my plans for the Simulation. He feels it'd be better for both sides if the administrator was cut out, to save time and all. I'm still intent on allowing complete customization though, which can't be done without the administrator. If I properly program this, I should be able to pretty easily try both. So I guess that's one of my new goals for the project. Keep in mind that one of my favorite things about PC games, and the reason I prefer them to console games a lot of times, is the fact that they can be modified. Mods can extend the life of a game quite astonishingly, and the customization is a key selling point to me. That's probably why I'm so set on making the simulation with the administrator-figure.

Also I managed to stumble upon Google Code, a resource for developers. Apparently a ton of Google's stuff is available for use by independent coders like myself. I might have a go at it sometime, but for now it's conveniently filed away that if I ever have a project that could take advantage of it, it's there to be used.