Python Web Server

As a software developer, I often write HTML files or JavaScript code that I would like to see in my web browser. I could just open the file in my browser, but if I’m testing JavaScript I would rather run from a real server. I could start up an Apache server, or create an instance of NGINX using Docker. But both of those options require too much effort for simply testing an HTML file.  What I really want is just a command that will allow me to start an HTTP server in the folder where the HTML or JavaScript files are saved. Well, thanks to Python, such a option exists. Simply go to the directory where you want the server to run from and execute the command:

python -m SimpleHTTPServer 8080

This will start up a simple HTTP server running on port 8080. Now, point your web browser to localhost:8080 and you can see your web page! Nothing could be simpler for quick testing of web pages or websites!

Why I Write Simple Code

Simplicity

As per Kernighan’s law: “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”

Brian Kernighan, the author of the above law, is among the most famous of all computer scientists. He, along with Dennis Ritchie, authored “The C Programming Language”, one of the most well known of all computer programming books. As such, Brian Kernighan’s ideas carry a lot of weight.

Kernighan’s law sounds simple, but it carries a profound truth – that clever code is bad code. When I was a younger programmer, I thought writing clever code was a great idea. I loved writing code that made me appear to be a wizard of coding. Of course, when you write complex code, you realize the first time you try to fix a bug that the code isn’t maintainable. Now, after 20 years of programming, I aim to write simple code – the simpler the better. I want any programmer – today or in a decade – to be able to look at my code and figure it out without any effort. Simple code is maintainable code.

Do you write simple code? Do you hire programmers that write simple code? More importantly, when you hire contractors do they write simple code? Contractors are notorious for writing ‘clever’ code so that you have to keep them onboard long-term to maintain the code they wrote.  For a business, this is a huge – and costly – mistake! Clever code will cost you far more than you think over the lifetime of an application!

 

Slow and Steady Wins the Race

Giant Tortoise

One of my hobbies is game development. I have been tinkering with Unity for several years now; and I’ve also experimented with  Java, Android, C++, and a few other platforms. Unity is, without a doubt, my favorite. The ease of developing 3D games coupled with their outstanding framework makes it an easy platform for developing games. So, when I was asked to help teach a Unity game development class at the high school a few years back, I was excited and gladly took the opportunity. I teach C# scripting to the students every Friday, and it’s great fun.

This last week, I was going over some simple code on creating projectiles and applying the scripts for their movement and destruction. I had started a project a few weeks before, and most of my code was there. However, when I went to continue the project I found that my code was no longer on the computer. Given that the class is only 50 minutes long, this was a real showstopper. I frantically tried to recreate the project I had before and get it to a point where I could continue with my lesson. Unfortunately, circumstances worked against me and my presentation was less than stellar. This experience reinforced two important lessons from computer programming that I will be sharing with the class next week.

First, I have been busy the last few months with my own business and have not been doing as much game development as I would like. This kept me from being on top of my game at class. I made some noob mistakes, and was unable to perform at my peak since my skills were a little rusty from months of under usage. In the tech world today, this is easy to have happen. The world of software development has so many tools, frameworks, languages, and platforms. Developers are increasingly expected to know countless technologies, and it’s almost impossible to be an expert in them all. For example, I have written plenty of Python code over the years, but I still have to pull up my sample code when I need a new script. Why? Because I don’t use python on a daily basis and I quickly get rusty. To stay up-to-date on skills requires constant effort.

Second, rushing to complete something will cause errors. This is as true in software as it is in any other endeavor in life. As I rushed to complete my code by the end of class, I caused more errors. And, in the end, nothing worked the way I wanted. Had I slowed down, I would have been better able to ensure that what I was doing worked the way I wanted.  However, the imposed deadline made me work without paying attention to the details. This happens in real world projects too. Unrealistic deadlines force programmers to pound out code without paying attention to the details. Errors are made, code is left undocumented, test cases are not written. Then, when the code is released, it doesn’t work as desired. Of course, deadlines are a part of the real world. But if we are rushed to meet unrealistic deadlines, we can be certain that the result will be less than desirable.

In the end, this experience shows some very real truths about software development. Much like the story of the tortoise and the hare, we see that slow and steady wins the race. We have to constantly reinforce the skills we want to use, we can’t let them get rusty. And, we need to take our time to ensure that the code we produce meets more than just timelines – it must be developed so that it is solid and stable.

Code Warnings

As a developer, I often look at someone else’s code. It may be a coworker, an open source project, or a code snippet on Stack Overflow. No matter the source, I often look at the code and wonder why something was done the way it was. That’s ok – that’s just part of being a developer. But some things make you seriously question the original developer’s technical prowess. For example, I was looking at some code today that was annotated to ignore all warnings. That’s a pretty brave move, as it assumes you know better than the computer does where problems may be. Reality is, you don’t. And when you ignore all warnings, you set yourself up for failure. For example, today I saw a piece of code with countless variables that were all context-specific in Android. When I removed the ‘hide warnings’ annotation, I saw countless warnings about how these variables would cause memory leaks. That’s pretty serious for a long running application, and it negatively impacts the user experience. Certainly some, in fact many, warnings can be safely ignored. But ignoring all warnings is a recipe for disaster.

Stored Procedures

Of all the technologies out there today, databases are among the most important. Boring as the idea may be, the storage of data drives the information age. Indeed, databases are as ubiquitious as the webpage itself. Order information from Amazon, posts on Facebook, content from WordPress sites – all stored in databases. Because of this, database management is hugely important – so much so that people work full time jobs in database management.

One of the technologies that databases provide is what’s called a stored procedure. Stored procedures are code that runs on the database to aggregate data, calculate information, perform business logic, etc. Many people love to put all kinds of logic in stored procedures so that they don’t have to rewrite the business login on multiple platforms. And, indeed, they can be useful at times. However, during my career I have grown to despise stored procedures.  Why? While stored procedures give the promise of simplifying logic on your application code, what they also do is increase the complexity of deployment and circumvent source control systems.

Since stored procedures are external to the application code, deploying an app is more complicated than simply placing an application on a user’s computer. Now, you have to first upgrade the database functions and then upgrade the application. No big deal, of course, since applications often require database updates. However, unlike table structure, stored procedures are more likely to change frequently in order to fix or tweak the logic. Thus, you end up with different versions of the stored procedure on different databases. Now, the same application will behave differently when running against a different database. This becomes a support nightmare. Is the issue a software bug, or is it a problem with the stored procedure? This leads directly to the second problem – no source control. Traditional application code is managed by source control systems. Every change is logged, and the history of the project can be observed for the entire lifetime of the project. Stored procedures are code applied directly to the database, and tweaks are often not entered in source control. Thus, you can’t easily revert back to a previous version since you have no record of it. This lack of history means we can’t see what other developers did and you have no idea why something was changed.

In my opinion, stored procedures often become the wild west of software development. For all the value they can bring, what I’ve seen them bring is additional bugs and confusion to the software process. When I work on projects, I will fight against the use of stored procedures unless an incredibly strong argument can be provided for their inclusion.

REST Tools

REST services are everywhere now. Long gone are the days of RPC and other horrible tools for running functions on a remote machine. This is great news for developers as older frameworks were very cumbersome and far less useful than REST services. What makes REST even more important is that they are used along with JSON to enable all kinds of slick functionality on the internet. Indeed, countless web applications and mobile applications now use JSON-based REST services. And just as there are numerous applications using JSON and REST, there are countless ways you can test REST services and create mockup services. But not all tools are created equal – particular for lightweight, simple testing. For example, a colleague recently said he was using Java and JAX-RS to mockup REST services. Certainly you can do that, but the amount of code you need to write and the frameworks required make it anything but simple. What tools do I use for REST testing? I like to use Python and Flask for mocking up REST services. For example, I can create a simple REST service in Python to return the sine of a number with the following snippet of code:

from flask import Flask
from flask import jsonify
import math

app = Flask(__name__)

@app.route('/sin/<num>',methods=['GET'])
def trig_sin(num):
  rad = float(num) * (math.pi / 180)
  sin = math.sin(rad)
  dict = {'input':num,'sin':str(sin)}
  return jsonify(dict);

if __name__ == '__main__':
  app.run(debug=True)

This is a full service, not a mockup. A mockup would be even simpler – just create the route and return the JSON you want. Nothing could be simpler for mocking a service.

For testing services, I use Visual Studio Code and the REST plugin by Huachao Mao. To test the above service, I can enter the snippet below into a file with a .http extension, and the REST plugin will create a button for me to call the service.

###
GET http://127.0.0.1:5000/sin/60 HTTP/1.1

I can create countless test calls as well as supply headers and JSON POST data. Even better, the .http document creates a documentation that is concise, clear to understand for anybody who develops REST services, and can be interacted with to see the output of the service. These two tools are my default choice for any type of REST testing.

The Importance of Source Control

While professional programmers always submit their code to a source control system such as git, svn, or tfs; most hobbyists and learners do not. This is a huge mistake. I always encourage people to check their code into a source control system. But why? For the learner or hobbyist, there are a few big reasons to do so. First, as developers we often realize we’ve solved the exact same problem before. But when? Where? How? Having a repository of your own demo code gives you reference material for future projects all neatly stored away. Second, as that repository grows, and you mature as a developer, you may want to pursue a job in software engineering. A growing number of companies ask to see your GitHub account – this is a great way for an organization to see what your code really looks like. Start building that portfolio of code now! Third, source control serves as a backup for your code. When the project you spent months working on is destroyed because of a hard drive error, what do you do? If you have your code on committed to a source control system, you download your most recent copy and move on. Very little is lost. There are countless other benefits to source control, but these are some of the simplest benefits an up-and-coming developer can realize quickly. If you don’t have an account, go to BitBucket.org or GitHub.com and set one up!

iOS Development Horrors

This past week, a client asked me to write a mobile application for both iOS and Android. I don’t do much native iOS development, so my first choice is typically Cordova – particularly for simple applications that don’t require native support. As I started setting up my client’s new project, I decided to go back and update some of my old iOS apps. They don’t get near the attention my Android apps do, and this seemed as good a time as any to do some needed updates.  I have three iOS apps on the iTunes store – one is native and the other two are Cordova. I got everything setup for the Cordova apps, then went into Xcode to build the final release. Xcode started by telling me  my icon resources were invalid. No further information was given – just that they were invalid. It appears that Cordova doesn’t generate all the right icon sizes, so I had to generate my own. This is great because you need 30 – that’s right, 30 – icons for an iOS app. You need to generate all thirty icons and then assign them to their associated spot in a giant tree of devices. Of course, the spots where you place the icons don’t say anything useful like 60px – no, it says 20px 3X – or 57px 2x. So, first I generate the maddening amount of icons and then I have to do math to figure out where to put each icon. Next, I try to change the splash screen from the Cordova icon to my company logo. Of course, Xcode provides even less information for that. Simply a heading like “iPhone 6s Landscape”. The only way to get any help is to stick an image with the wrong size in the spot and see what the warning message says – which includes the desired dimensions. This process took an hour just to get the splash screen and icons working. Why? Every single icon is square. Can’t I just provide the highest resolution and have Xcode figure out the rest? For my splash screen, can’t we find a more elegant solution? For instance, I provide an image and tell you the sizes to use it for – just crop, I don’t care. I would need to provide a few different images to account for smaller sizes, but it should be an hour just to get such trivial work done. After that, I tried to build but received errors about my signing certificate – so I had to redownload and jump through some more hoops. Finally, I uploaded to Apple only to receive an error message that my build included images with an alpha channel. (It’s 2017, Apple, why can’t you support transparent images yet?) Almost there…. I add my text to describe what I’ve changed, and hit submit. I get an error on my text saying there is something wrong with my internationalization. Another half hour of trying to figure out why my text is wrong, and then a trip to Google only  to find out that the problem was that I didn’t have enough screenshots. More image fun – I need to post pictures for 5″ devices. I’m not exactly sure what devices are 5″, so I have to try various emulator settings until I figure it out. And, finally, my app is off to Apple for approval. Then, on to the second Cordova app for more fun!

After that, I move on to my native app. Already knowing what to expect, I gather the necessary images and prepare for the new build. But wait – my storyboard is all messed up. Apparently, during one of the more recent Xcode updates, they changed everything. No problem – I’ll go into their interface builder and fix it. Or not. The interface builder is so slow it’s unusable. Back to Google, I find everyone complaining that Xcode 9’s interface builder is horrible. Their experiences mirror mine – minor changes taking 10 seconds to be reflected, spinning beach ball, CPU pegged, etc. I have an utterly trivial interface – just a series of labels and text inputs for logging ham radio contacts. But after an hour, I was no further then when I started. Apparently, I’ll be waiting till the next version of Xcode to fix my app since the current version of Xcode is unusable.

And that brings me to my real frustration. During my career, I’ve used countless development environments – everything from Delphi to Borland to Visual Studio to Eclipse to Lazarus. And in all my years, I have never seen an IDE as bad as Xcode. Apple – it’s time to move into the 21st century and create an IDE that’s as amazing as your laptops. Stop forcing us to use an environment that should have been abandoned decades ago.

React Native

Most of my mobile development is in creating native Android solutions. However, I sometimes need to create iOS apps as well. I have done native iOS development, but if I need to have a cross platform solution, it obviously requires twice the effort (and cost) to create native apps for both versions. And, when you’re done, you have to maintain two different apps as well as deal with bugs on two different versions. Throughout the years, a variety of solutions have been made available – and with the continued growth in the mobile market, I expect to see more tools available in the future.

During the past week, a colleague recommended that I look at React Native for creating cross-platform apps. Then, yesterday, a customer asked me to create a mobile app for them on both iOS and Android. So, I decided to investigate React Native.  The website for React Native talks about how you can use JavaScript to create native apps – not hybrid web apps, but real native apps. That sounded very exciting! I installed their framework without much trouble and began tinkering around. While I am not a fan of JavaScript for larger projects, I realize that it has become the language of choice for a growing number of tools because of it’s widespread acceptance. I used Visual Studio Code as my IDE, connected my demo app to a REST service, and had a trivial mobile application running in minutes. The most awesome part of React Native development is that the test app on your phone is always in sync with the changes you make on your development computer – without a USB cable – so long as you are on the same WiFi network. Now, the next step – create an actual Android APK to push to HockeyApp for distribution to my software testers. Wait… there is no easy way to do this. I have to ‘eject’ my project from React Native – a process which I am warned is not reversible – and then use native tools to build the APK. So, I can start the project in React Native, but then have to export the project to a native form to actually deploy. This was a show stopper to me – I don’t want to have to export to native tools as that invalidates the entire purpose of a cross-platform project to me. I dug through the documentation trying to see if I was missing something, and others had asked the same question. As I dug further, I saw numerous users complaining about how out-of-date the documentation was. That concerns me – if I want to learn the framework, I need to be able to rely on the documentation. Having found no way to easily create an APK, I gave up.

In the end, for this project, I think I will stick with Cordova. It may not be as exciting as React Native, but I can chose whatever frameworks I want to use – be it a high-tech Angular app or a simple HTML5/JavaScript application. The tools work well, and – maybe one of the most important things to me – the project can be maintained by anyone who knows HTML5.

 

 

Visual Studio Code

Anyone who knows me knows well that I am not a huge Microsoft fan. I’ve been a Unix user for over 20 years, I’ve been using Linux for nearly as long, and my current laptop is a Mac. I prefer Google Docs to Microsoft office, I never run Internet Explorer (Or Edge), I don’t like IIS, and I would never run SQL Server. So, it comes as a shock to most of my tech friends that I am a huge fan of Visual Studio Code. In fact, I would have to say that it’s probably one of the best general purpose development environments ever created. What makes it so great that I, a Unix user would endorse it? I think there are two main factors that made me fall in love with Visual Studio Code. First, it’s cross platform – Visual Studio Code runs on Windows, Mac, and Linux. This is a big deal for me. I prefer tools that I can run on a variety of platforms. While I typically work on a Mac, I do have a Windows machine too. Having an environment that runs on both means that I can easily transition from one machine to another without having to adopt different tools. Second, and probably even more important, is the wide variety of plugins available. Whether you need to create or edit HTML, C# .NET applications, JavaScript, Python, XML, there’s a plugin available for you. There are also plugins for Docker, git, and a REST client. Furthermore, the IDE is pretty simple and easy to work with. Where I used to use text editors such as UltraEdit or TextWrangler, I have now come to rely on Visual Studio Code as my default choice for editing code when I don’t have a more specific IDE installed. Kudos to Microsoft for a creating such an amazing cross-platform code editor!