Posted tagged ‘Reusable Code’

The title is perhaps slightly misleading. I think overall that coding should be fun. Figuring out how to do something and getting it to work is a mental exercise that can be pretty enjoyable, especially when you finally have something finished that you can get other people to play with. However, when launching into learning a new language, platform, framework, or basically anything outside of your regular development comfort zone, you can lose your focus on doing things the right way. This is where some discipline comes in.

I don't know why, but the first image that came to my mind when I thought 'discipline' was Mr. T. So here he is.

By now, we should all be doing certain things whenever we code. Writing unit tests first is important, as is writing good tests that actually prove the working of things. Using version control is a given; even the stuff you mess around with should use version control since it’s hardly any work at all to add it. Building off of interfaces so that you can easily exchange implementations without messing with the code that uses those interfaces (this also goes well with testing). Decoupling your view from your controller from your business logic. These are all great things, but sometimes in the excitement of learning something new we forget about them.

Recently I began learning about Android programming. I started with their tutorials, and used them and the API reference doc to try to create my own simple program. The idea was to create a simple game, something that shouldn’t take too long but that other people could play and have some form of enjoyment from. I decided to create Zilch (also known as Farkle). Since the portion of android that is newest to me is building and manipulating the view, I ended up writing code that was very coupled between the view and the game logic. It reminded me of code I would have written early in my college career. Not my best code.

After the main gameplay was done so that I could see things on the screen and touched them I looked at my code and realized how bad it was. Events tied straight into business logic actions rather than calling a packaged up set of game rules that could be tied to any front end. This means if I wanted to modify my front end to use a different widget for a particular task I would have to change my business logic as well. Not very efficient, and very difficult to work with.

I think this sums it up about nicely. Link goes to the original creator.

It did however help me identify something that makes it difficult to learn a new language or framework: We don’t always port our knowledge across. I’m very able to utilize TDD, separation of concerns, and creating elegant designs that decouple the view from the model and controller, but when jumping into a new language or drastically different platform I tend to devolve to the most simple of programming practices (which aren’t good). Some practices like TDD can, and should, be applied to every project regardless of language. Having come to that realization, I’m going to restart the game that I had been working on by creating a pure backend first in Java and then tying the front end up with the Android specific stuff. I think it will both help in learning android, and in creating a decent implementation of a game.

So when moving to a new territory, try not to forget what you already know and see how it can apply to what you’re doing. There is great carryover between many languages, leverage your strengths and knowledge and strive to write good code, even in your hobby.

Almost all applications today deal with persisted data. The only rare exceptions are usually not very complicated such as a calculator, unit conversion tool, or minor utility. Let us assume that any application we’re working on is going to have some sort of persistant state that must be kept between executions of the application. Typically the state is stored in either a file or a database. File access is useful for many desktop applications used by a single user as the format can be created very easily from the data model, the data is easy to transfer to another user via email or some other file transfer process, and backups involve just storing the file somewhere safe.

Many applications that involve multiple users, including web applications, will instead employ a database. Even single user desktop applications sometimes use a database. Database access is often performed by a section of the code converting objects or structures into database tupils and storing them in tables. When the data is required again, select statements are made that call the data and turn it back into a structure. Usually this storage and retrieval of data is done in the same code base as the rest of the application.

There are a few problems with this approach however. For one, the database code can sometimes become tightly coupled with the business logic of the application itself. The application knows about the data being stored in a database and will often be changed accordingly to facilitate database access. Switching to a different database system can involve very large rewrites of not only the database code, but also application code as it can rely on database specific functionality. Think of functions that pass along snippets of SQL in order to construct the correct objects. Often that SQL will be database specific.

Besides being tied to a single database, the same coupling also ties applications to databases in general. If your application is expecting the data to be stored in a relational database, assumptions in the business logic will be made regarding that. This inhibits your ability to transition to a file store or other NoSQL solution if required. Because of these concerns, my topic for today is about abstraction and remote data sources.

If you code your database logic in with your application code, coupling can form. However if you separate them completely your application doesn’t need to know where the data comes from or where it goes when its saved. All the application has to do is follow a simple generic interface for storing and retrieving data. This not only elements coupling, but has some other scalability benefits that I’ll discuss a bit later.

To really appreciate interfaced based design and loose coupling, try removing your data access code from your application code base completely. Instead, use a language neutral format such as JSON or XML to communicate between your application and your data source, itself a small application. The application will send a request along with perhaps some data if it needs something stored. The data source will then transform that data into a format that can be stored and place it either in a database, file, or any other storage medium that you desire. Later if you want to modify how your data is stored, maybe a different DB system is more suited or you’re moving from a file-based system to a database, you can just modify the implementation of the data source application while not changing a line of code in your actual application. The loose coupling means that as long as the data source maintains a solid interface that the application can interact with, the application can be developed independently of the data source.

If each of your interactions between your application and datasource are atomic and independent of each other, stateless, you can horizontally scale your datasource using replication. Each data source can access a different replicated read-only data store for request information. Meanwhile write access will all go to a master data store that can be replicated to the read-only slaves. Read requests from an application can be distributed to multiple data sources, especially useful if the data source does any CPU intensive filtering or processing.

The main benefit however remains that by separating your data source from your application as a remote service, you can ensure that your code is loosely coupled and that your business logic will not rely upon the underlying method which your data is stored. This will lead to greater flexibility in your code, and a more agile platform on which to build.

JavaScript is such an interesting language in that it is both extremely popular and hated at the same time. It is the most used programming language in the world, thanks to its inherent involvement in web programming. It is the sauce behind AJAX, and creates the dynamic aspect of dynamic web pages. It’s easy to pick up and write, requiring no compiler and running on any system that has a web browser. Unfortunately this has generated a stigma of it not being a ‘real’ programming language. Often even professional programmers will treat JavaScript in a more backhanded manner than they would code written in Java, C, Perl, Python, Ruby, or one of the many other compiled and scripting languages.

JavaScript, or ECMAScript as it is technically known as, is often written in a very procedural fashion. If you’re lucky you may see it being used as a functional language, when a developer decides to write functions at all. Rarely will you see it generated in a true object-oriented fashion. This is unfortunate because JavaScript has support for great object-oriented programming. Objects can be created through prototypes of other objects, allowing you to create “classes” through merely building a base object from scratch and then cloning it via prototypes.

A lot of JavaScript is created as one-off functions or scripts for a single purpose. Many developers are rebuilding their same wheel multiple times in the same application or even web page. While there are great libraries that showcase how useable pluggable JavaScript can be (take a look at the fully open sourced YUI library some time), very few developers abstract their business logic in a way that is reusable.

I think the problem mostly stems from the ingrained thought of the coupling between JavaScript and the web browser. People tend to write JavaScript for a specific web page, rather than to perform specific functions. A reapplication of the MVC pattern can be quite helpful here to separate concerns and promote reusability. I think this shows greatest when dealing with AJAX/Web Services.

Many applications are using AJAX to create more interactive, faster, and user friendly applications (we’ll ignore the back button concern for now). Web designers love AJAX because it creates a great feel for the users due to instant feedback and the lack of page loading. Web programmers dislike AJAX because it makes writing programs more difficult and can cause a lot more work. However, by separating some of the JavaScript code into distinct units you can reuse common functions across many pages.

This file can be part of your base “AJAX action” javascript which provides the actual actions to perform your AJAX commands. You can then use another javascript file to declare custom versions of WIDGET.callbackDelegate which will overridden the already declared version, just make sure that your new file is placed in your HTML file after the first one. By declaring default visual response to be alerts you will know what methods you should override on each new page.

Douglas Crockford, a fellow Yahoo and a member of the ECMAScript standards group has done a series of webcasts that describe some additional best practices of JavaScript that many developers may not practice. He also wrote a book that’s valuable to check out.

Subscribe

Aspirations of a Software Developer syndicates its weblog posts
and Comments using a technology called
RSS (Real Simple Syndication). You can use a service like Bloglines to get
notified when there are new posts to this weblog.