Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Saturday, January 23, 2021

Dynamic Typing in Python

Python is an extremely powerful language, but with great power comes great capacity to really screw things up.  Overall, Python is an extremely well designed language, but there are a few aspects of it that get attacked a lot.  Using style for control flow is a big one, though some of us actually really like this feature.  Another common complaint is with Python's dynamic typing.  Dynamic typing allows programmers to really screw things up in ways that can be really hard to debug.  Supposedly, it is common for less experienced Python programmers to accidentally have variable naming collisions, and because Python has dynamic typing, there is no type safety system to warn the programmer (though, I should note that no one has ever presented me with any evidence that this is a common problem, and even when I was new to Python, I never encountered this problem in my own code, and when I taught Python to undergrad students none of them ever reported having problems or frustration with this).  Some opponents of dynamic typing even suggest that the ability to change variable types has no practical value and thus should not exist in any programming language.  As someone who has made extensive use of Python's dynamic typing, to great advantage, I would like to present some highly valuable applications of it that have saved me enormous amounts of time.

The one that always comes to mind for me, is the ability to dynamically change objects.  Wait, objects?  How do objects have anything to do with it?  Objects are (composite) variables.  They have a type, that is defined by their class.  Wait, so you can change the class of an object dynamically?  Not exactly, and this is the wrong way to think about it (in this context...).  Most programmers think of types in terms of primitives, which is why many opponents of dynamic typing see no value in it.  If you see objects as collections rather than variables with their own types (defined by the names and types of their contents), it's easy to miss this.  (In Python, functions are also variables, so objects in Python are literally types defined by the variables they contain and their names.  Classes are merely formal definitions of those types, but it's trivial to create undefined object types as well.)  What does it mean to change the type of a primitive?  It means you are storing a value of a different type in it.  If you have a variable containing a string, and you store an integer in it, the string is completely replaced.  Objects are not primitive types though.  They are composite types, that can contain both data and code (or, to be more precise, pointers to code, in nearly all implementations), and multiple elements of each.  While writing a primitive type to a variable containing an object will overwrite the object (or rather, the pointer to it), dynamic typing is more than just overwriting the existing data with data of a different type.  Changing the data type of a primitive, without overwriting it with new data doesn't make a lot of sense.  Changing the type of an object, without overwriting it, does make sense, so long as you don't think in terms of changing the class of the object to another fully defined class.

In Python, most objects (excluding built-in objects) can be dynamically changed, by adding methods and member variables.  Thus, if you have created an instance of a user defined class (aka, an object), and it needs to have an additional member variable and/or method, in Python it is easy to just add it.  Now, it might be tempting to think even this is useless, but in Python it is incredibly powerful.  It allows for macro-like ability in the language, and it is fairly well known that macros are what makes Lisp such a powerful language.  Python's dynamic typing isn't quite as powerful as Lisp macros, but it allows for many of the same kinds of advanced metaprogramming.  In addition, because it is also possible in Python to create empty objects, by instantiating objects that inherit only from the object() class (object() itself is built-in and thus its direct instances are not dynamic), it is also possible to build completely arbitrary objects at runtime.

One of my favorite uses of dynamic typing in Python is adding methods to existing objects, to give those objects additional abilities.  In the context of video games, this means I can add a "render()" method to existing objects, if I want.  Of course it is more practical to just include render() in the original class definition, which is what I actually do.  The practical value of this is much greater, when I am using 3rd party libraries with objects that I want to change, without changing those libraries.

Another handy use of dynamic typing in Python is to assign extra metadata to existing objects.  For example, say I need an identification system for a collection of objects.  I could easily add a universal identifier to all objects put into that collection.  If I need to find or verify a particular object by UID, I can easily do that now, without having to change the class definitions (which I may not even have access to) of all of the objects.  And, now my system can take arbitrary object types, tack on the UID, and use them, without having to know anything about the objects.  Since Python can have collections of different types of objects (which we will talk about in a moment), this makes certain kinds of dispatch systems really easy, and adding UIDs and other metadata to objects can facilitate very advanced security protocols far more easily than languages that don't have dynamic typing.  Sure, I could write a wrapper object, that holds an object being passed in, and contains all of the metadata, and in some cases, this would be the optimal approach, however, this is less efficient (more layers of objects), and it would be significantly harder to add to an existing system.  In addition, a special authentication wrapper could lead to increased coupling between the authorization model and other modules that would have to unwrap objects when accessing them.  If I need to add an authorization protocol to an existing system, or if I need a very cheap authorization protocol that takes minimal time to develop, taking advantage of Python's dynamic typing will easily allow it, with no risk of potentially harmful coupling between the security system and the other systems.

The most complex way I have ever applied Python's dynamic typing system was in automated web site QA testing with Selenium.  This is an especially complicated application, because each page has its own unique set of properties and actions.  Initially, I used a non-object oriented approach, but this proved problematic, as each test needs to be painstakingly created, entirely from scratch, often with complicated CSS selector strings to interact with all of the elements on the page.  Even with three other employees writing tests, we were only writing two or three tests a day, to test usage paths that would only take us a couple minutes each testing manually.  In addition, logging is problematic, as either each individual test needs a bunch of custom logging code, or a global logger only logs minimal data about test failures.  The company I worked for at the time had used PHP for Selenium testing a little before I was hired, and they had attempted to get around these problems by writing a framework to handle a lot of this, but it constantly needed modification, because everything was hardcoded.  Using Python, I wrote a semi-complicated program, using Python's metaprogramming capabilities to dynamically generate a custom object for each page, with methods for all of the actions on the page.  The initial iteration still required test developers to go through each page, adding actions and any input elements to a JSON file, that my program would generate the objects from, but the long term plan was for the program to scan the HTML, looking for interactive elements and their input fields, and generate the page objects from that.  The finished product also would have scraped the page for information to include in logs, when tests failed (the page title, error messages, and such).  This way, a test writer could go to a web site, get the first page object, and then navigate purely by calling action methods on page objects, and then using the returned page object (representing the new page), and when a test failed, the log would automatically include detailed error information, rather than just the URL, the assertion that failed, and whatever description the test writer put in the assertion.  If a dev got to a new page and didn't know what actions were available, Python's introspection capabilities could be used to see all of the actions associated with the page object, to see what options the page presented.  While I quit that job when they decided to migrate their automated testing to Java (making test development much slower and eliminating any metaprogramming capabilities), my program would have allowed amateur programmers (we hired a lot of interns in their first few semesters of CS undergrad studies) to write tests very quickly, without having to even know HTML or CSS, and without having to spend hours going through web pages to construct complicated CSS selectors.

The truth is, most Python programmers use dynamic typing quite often.  It is not typically used for changing data types dynamically though.  It is used in heterogenous lists.  Heterogenous lists (Python's default array/list/collection type) can hold objects of any type, in any combination.  This is really handy, because it means metadata can exist as type, rather than as an explicit part of a variable.  For example, say you are creating an event queue.  It needs to hold KeyboardEvent objects, MouseEvent objects, and a bunch of other event types.  In C or C++, you will have to make an Event type (object or struct) and then have the subtypes inherit (or use a union), and then you will need to hold metadata about what type each object is, within each object (or struct), and then you have to cast Events going into and out of the queue, and from there you need separate code for each type.  (The degree of run-on-ness of that sentence is a good indicator of the complexity of the work involved.)  In Java, type data is handled automatically, but you still have to inherit, cast, and handle each type separately.  In Python, I don't need to inherit from a common class (less coding and greater maintainability), and I don't strictly need to check type.  I can use separate code for each type if I want, but I can also just check if properties exist directly and act appropriately.  For example, if I get an event, I might check if it has a "keydown" property, and if it does, I can check which key it was.  I don't need to know that the object is a KeyboardEvent object, and I don't need to cast objects coming out of the queue to their original type.  And in fact, say I want to use the event system to control an AI opponent.  I can make an AIEvent object with keyup, keydown, and whatever I am calling mouse event parameters, and toss that onto the queue, and so long as I have some way for clients of the queue to tell what events belong to them, I can use the same code I am using for the playable character for AI units!  Now, my AI units can take only AIEvent objects off the queue (yeah, they have to check type for that, and that's fine), and then they can feed the event into the same unit control code the playable characters use.  If this use sounds similar to Java's interfaces, it can be used similarly, to add similar capabilities to a collection of otherwise completely different objects.  So sure, this can be done with other object oriented languages (indeed, this is a common game programming design pattern), but with Python, I can do it much faster, in far less code, because I don't need a special queue, type casting, or as much type checking.  For comparison, SDL, a video game programming library, uses structs and unions, with type metadata variables (that the user must check), to achieve similar behavior.  (C unions are really powerful, and they can be used to create fully dynamic types in C, but with more hazards than Python, because it's easier to overflow a memory location using unions.)

The fact is, dynamic typing is far more than just being able to change the type of a variable at runtime.  It's being able to dynamically redefine objects.  It's being able to store elements with different data types in the same list construct.  It's being able to use objects of different types with related functionality with the same code, without having to do any complicated type casting.  Sure, dynamic typing increases the potential for bugs, but it also decreases potential for bugs, by making code simpler and shorter.  The hazards of dynamic typing are generally far outweighed by the benefits of increasing simplicity and decreasing code volume.

Wednesday, May 29, 2019

Why I Hate Frameworks

While most of the software development world has been rushing headlong into mountains of awesome frameworks over the last decade-and-then-some, I have been quietly reinventing the wheel.  At least, that is how a lot of developers often see me.  I do not like frameworks.  I avoid using frameworks.  When I am forced to use frameworks, I do not enjoy it.  I find frameworks only cause me pain and suffering.

Reusable code is not a bad idea.  I am a big fan of well written libraries that save me significant time and energy.  That is not what frameworks are though.  I have seen well written frameworks, but the truth is, it tends to be a toss up.  Your odds of getting a well written framework are not better than your odds of getting a poorly written one.  While I have rarely had to peak into the guts of a framework (a distinct benefit of avoiding them), those that I have had to dive into have not been good.  On one occasion, a family member offered me a decent bounty to find and fix a bug in a popular framework.  I spent a few hours trying to get familiar with the code of the framework, but in the end, I realized that I would have to charge several times the bounty offered to make it worth my time.  Over the course of a few hours, I was unable to trace the path through the code that the program was taking.  It was not that the framework was particularly complex.  I can handle complex code.  It was just poorly written.  It might have looked like a nice framework for people who would not have understood what was under the hood regardless of quality, but for an experienced software developer, it was absolute garbage.  On another occasion, I was doing some QA work for a corporation, and I needed to get a little bit more information out of their automated testing system.  Of course, they were using a reasonably popular framework for the automated testing.  It took me days of combing through the framework to figure out where everything was happening, so I could add the critical code to provide the required data.  Again, it was not a matter of complexity.  The problem was that whoever wrote the code was doing things in the most roundabout way possible.  There was a massive amount of coupling.  Everything was touching everything else, and consequently, to understand one thing, I had to understand everything.  Other frameworks I have used are often buggy, and the generally poor design and code quality make it not worth the effort to try to fix the bugs myself.  I have also had a few occasions to look inside general purpose libraries, and I typically find them to be of much higher quality.  This is not always the case, but when I discover a bug in a library, I do not feel the same anxiety when considering whether to try to fix it myself or not.  So the problem is not that reusable code is just a lousy idea.  It is a great idea.  The problem is that frameworks specifically tend to be low quality.

There are a lot of reasons I avoid frameworks.  The worst is the fact that most frameworks require a lot of effort to do even the simplest things.  The theory is that frameworks make everything easier.  The reality is that they tend to make hard things significantly easier and easy things much harder.  For example, the straw that broke the camel's back (and pushed me over the edge, into writing this article) is the ESP-IDF framework for programming the ESP32 micro-controller.  I would not have used the framework voluntarily (I actually prefer manipulating the hardware directly), but it turns out enough of the ESP32 is proprietary, and the FreeRTOS real-time operating system only has the framework implementation available, so I have no other option.  The ESP32 is an excellent micro-controller, with built in wifi and a lot of other really nice features for its price.  The framework, however, is a disaster.  For a previous project, I used I2C on an Arduino, which I programmed entirely in C.  Because I did not want to write my own I2C driver, I took Arduino's driver and ported it to C.  This was mildly challenging, but despite excessive complexity, Arduino's code was written well enough that it was not too much of a chore.  Now I am writing the same program for the ESP32, and the ESP-IDF framework's I2C driver is a nightmare.  I do not even have to port it to C.  It is already in C.  Somehow though, it is actually more work to use than it was to port Arduino's driver to C and use that.  The fact is, I2C is trivial.  It is not a complicated protocol.  (It is not terribly well designed, but it is not complicated either.)  The most difficult part of porting the Arduino driver was eliminating all of the unnecessary object orientation.  ESP-IDF is written for C, so it does not even have object orientation, and yet it manages to be several times more complex.  The fact is, I2C is such a simple protocol that the most difficult part of using it should be setting up the pins on your chip and configuring the clock speed, if your chip has a built in I2C controller (the ESP32 does), but that is not how it works with ESP-IDF.  No, setting up the I2C device is fairly simple (though, the documentation does nothing to help, and the provided example code is stupidly complex).  The first step is setting up a struct to tell it which pins to use, how to initialize them, what mode to use, and what clock speed to use.  The second and third steps are a pair of function calls that really could have been rolled into a single function call.  One extra function call is not a disaster though, and maybe it is somewhat justified, if you need to enable and disable I2C frequently.  That is where the simplicity ends though.  With the ported Arduino I2C library, once you have the thing the initialized, you can call a single function to read and a single function to write.  You give the functions the address, the command, and a few other parameters, and you are good to go.  With ESP-IDF, I2C reads and writes are major productions.  First, you have to tell it that you are starting an I2C transaction.  Next you have to tell it to start accepting data for the transaction.  Then you have to do a pair of write function calls to tell it what you want to write (it may be possible to roll them into one, but all of the examples show it as two).  Then you tell it you are done giving it the transaction data.  Do not think it has actually sent the command though.  After that, you tell it to send the command.  Once that is done, you have to tell it to delete the transaction.  In Arduino, this is all a single function call.  In ESP-IDF, it is a disaster.  I2C is a simple protocol!  ESP-IDF manages to take something incredibly simple and turn it into something extremely complicated.  This is perhaps the biggest reason I hate frameworks.  This is not a one time thing either.  Even Arduino's I2C driver is overly complicated to use.  In the process of porting it, I eliminated a significant amount of setup cruft caused by using an object oriented approach where it is entirely unnecessary.  In my experience, every framework has places where it takes something almost trivial and makes it more complicated than it has to be.  Libraries sometimes do this too, for example, most high level languages built in libraries make pipes prohibitively hard to use (one of the few places Python really biffs it), but frameworks do this all over the place.  Threading libraries tend to do this as well.

Compared to this, most of my other issues with frameworks are trivial.  The worst one is that when a framework has a bug, it is a lot harder to fix than a bug in code you wrote yourself, even if the framework is well written, because you are not familiar with the framework's code.  I have legitimately abandoned frameworks because they had one critical bug that would have taken me more time to fix than just writing the code myself, from scratch.  Now days, I generally just skip the part where I use a framework in the first place.  Another is that, in my experience, frameworks often take more time to use than writing code from scratch anyway, because learning a framework takes time.  Unless I am going to use most of the features offered by the framework, it is not worth my time to learn it.  I have written AJAX functions from scratch many times instead of using JQuery, because it is actually faster to do that than it is to setup JQuery on my web site and look up how to use its (admittedly high quality) AJAX stuff.  Frameworks also consume unnecessary space, leading to memory bloat, performance costs, and unnecessary bandwidth costs, unless you are using almost 100% of the features provided.  These things may seem trivial, but when you consider the scale on the server side instead of at the individual client, it adds up surprisingly fast.  Frameworks also tend to come and go, especially in web development.  This means that the framework you are learning today probably will not be worth much to you in a couple of years.  It might help you advance in your current company, but most promotion in the software industry is not internal, and that other company you really want to work for probably does not use the framework you are learning for your current job.  This is further aggravated by the fact that there are so many frameworks out there that there really is no point learning one that you do not have an immediate application for.  Lastly, and this is really more important than the last few issues, frameworks are almost never as general purpose as libraries.  Nearly all frameworks are designed with a fairly narrow set of use cases in mind, but then they are advertised with a focus on one design element that is not closely related to those use cases.  For example, responsiveness is a popular feature of web frameworks that dynamically load data.  Most such frameworks are designed for point-of-sale and inventory management, and they tend to be janky or even downright lousy for anything else.  They do not tell you that you should not use them to make a site that needs good quality real-time interaction though.  They do not tell you that the responsiveness comes at a heavy performance cost.  So you decide to use a framework like AngularJS, because "responsive" sounds like exactly what you want for your browser game, but halfway through, after you have spent many hours learning the framework, you discover that while it might work well for business applications (if you are willing to tolerate the making-easy-things-excessively-complicated problem that it also has), it is a horrible choice for games, because what they mean by "responsive" is not the same as what you thought it meant.  (No, I did not actually try to use AngularJS for a browser game.  I did use it for an inventory management system though, where it worked fairly well but where the performance costs occasionally reared their ugly heads in ways that do not matter to an inventory management system but that would make a game unplayable.)

There are a lot of problems with frameworks.  Their popularity makes it clear that a lot of people are willing to put up with those problems, for the perceived benefits, but in my experience, most of those benefits are ethereal.  Recent research suggests that system and development architectures make a much bigger difference in success rates than development stacks anyway.  This means that any benefits gained from using a particular framework will almost certainly be dwarfed by improving team communication and spending more time on quality design work.  My personal experience supports this conclusion.

What it all comes down to is that if you really want to use a framework, pick one with features you are going to use, and know what you are getting yourself into.  Personally, I find it easier and faster to code the features I want myself, and I find that the time spent finding and learning a suitable framework ultimately costs me more than just writing the code myself.  You might say I am reinventing the wheel, but the fact is, when there are a million different kinds of track, you need a million different kinds of wheel if you want all of your trains to run smoothly.

Monday, October 16, 2017

Ideological Programming

Today I was following what is actually a very good tutorial on SDL2, in C (despite it being written for C++).  I came across an excessively complex section of code.  The tutorial has me writing an initialization function.  This is an excellent idea, as it groups a bunch of related actions together.  Unfortunately, it is both hard to read and hard to write, and as far as I can tell, it is purely because the writer subscribes to a particular programming ideology.

This function starts by initializing a return variable, used to indicate failure or success.  Then it initializes the video subsystem.  If it fails, it sets the return variable to false, otherwise it goes into a nested conditional, creating a window and then testing for success, then it goes into another nested conditional for starting up the image loading subsystem, and only then does it get a surface to draw to.  This is nested three levels deep.  Each level tests if some initialization worked, and if not, it prints an error message and sets the return variable to false.  The nested conditionals make the code hard to read and hard to write.  There is a reason the writer of the tutorial did this though.  It is an ideological reason.

There is this programming ideology that says a function should only have a single return point.  In other words, it should not return anywhere except at the end.  Programmers who subscribe to this tend to use return variables and nested conditionals to avoid returning in a conditional before the end.  What is the benefit of this ideology?  There is none.  It is based on the idea of mathematical functions.  Mathematical functions can only have a single return point, and some programmers believe that this should be applied to functions in programming.  The fact, however, is that the word "function" means very different things to mathematics and programming.  Programming functions are loosely based on mathematical functions, but they are not, by any stretch, the same.  There is one exception: In functional programming languages, functions are analogous to mathematical functions.  As such, pure functional languages don't allow multiple return points in functions (this may not always be obvious though).  C is not a functional language though.  There is no benefit to adding this artificial programming constraint.  In fact, in the worse case, it will result in inferior machine code.  While a well designed compiler might be able to optimize away most of the extra work for nested conditionals to get to the return point when a failure case occurs, it will never end up better than a set of conditionals where a failure just returns inside the conditional testing for failure, instead of using a return variable and nesting.  In many cases it will end up worse though.  Intermediate return points avoid unnecessary work, especially in a case like this.  More importantly though, the flattened version of the code is both more readable and easier to comment.  The ideology might sound good, but it is applying pure math principles to a more complex and flexible discipline, and in doing so it produces worse outcomes.

This is not the only programming ideology that is expensive and wasteful without producing any benefit.  Object orientation as a programming paradigm is founded on the ideology that everything should be an object.  Following this ideology results in hard to read code that uses significantly more memory than necessary and performs poorly on modern computing systems.  Programming to a particular ideology might have some academic value, but in real life situations, it generally just causes problems.

When writing a program, these should be the primary goals, starting with the most important:
  1. The project is completed within acceptable margins for cost and schedule.
  2. The program produces the correct output for every possible input.
  3. The program is cheap and easy to maintain.
You can add other goals after these, but most will be dependent on the particular project.  Aesthetics might be important for one client, while specific features may be important to another.  Notice, however, that none of these three include anything about following a particular programming paradigm or ideology.  Unless it is a critical requirement of the project (which is almost unheard of outside of academia), maintainability always trumps adherence to a particular paradigm.  Following a particular constraint for something that happens to have a similar name from a related field is not an excuse for writing code that is hard to read, hard to comment, and hard to maintain.  Sometimes performance or correctness is more important than maintainability, but few of these ideological programming constraints improve performance or correctness, and many times they actually hinder one or both of these.

Ideological programming can be fun as a hobby or a purely academic pursuit, but in the real world, following abstract rules that have no practical value is a waste of everyone's time and money.  Effective programming is about using your tools efficiently and effectively.  When you eliminate a tool from your toolbox for a purely ideological reason, you artificially limit your skill and the quality of your work.  Just say no to ideological programming.

Monday, June 19, 2017

Why Are Pipes Hard?

I learned something amazing today.  I have done a few small multi-processing tasks in the past, some using Python and one using Java.  The most appropriate form of interprocess communication for these was pipes.  The experience was always very painful.  I had to figure out how to cobble together the right objects to produce a usable communication system.  I had to learn some special uses of objects to allow the parent process to continue executing, instead of waiting for the child to finish.  Working out the bugs was very difficult, because it was hard to tell if the problem was my communication protocol, if I had connected my objects wrong, or if maybe I had given an advanced function or method some incorrect parameter.  Of course, I expect this sort of difficulty.  I had heard from others just how hard interprocess communication is, especially with pipes.  That is just the way it is, I guess.

Today, a friend sent me a link to this.  That document discusses several types of interprocess communication.  There is one chapter on pipes, and the author starts the chapter, "There is no form of IPC that is simpler than pipes."  I found this rather amusing and slightly confusing, as this was not my experience.  Shortly following that, he adds that the document will not spend much time on pipes because they are so easy.  This was confusing.  By the end of the section, I knew two important things.  First, the author is right; pipes are incredibly easy.  Second, everyone else is doing pipes wrong.

In Python, you have to create and pass pipes into the function call that starts a new process.  I forget the exact details, but I seem to recall having to use a different function or at least put some obscure parameter into the regular one to get it to return before the child process was completed.  Then I had to use some method of the pipe object to interact with the child, and this was rather difficult to get right.  In one case I did have some issues with my communication protocol, but I thought it was yet another issue with how I was trying to use the pipe.  It took half an hour to figure out that the problem was some trivial thing with how was formatting the data I was passing through the pipe.  In short, the system was completely opaque and very difficult to use.  Java was not much better (in fact, I think I gave up on communication while the child process was still running, and just made the program call multiple times).  The friend who sent me the link told me he had the same experience when he read that section, except with the Go programming language.

Now, that document describes how to use pipes in C.  First, you create a pipe.  This requires merely making a single function call, passing in a two integer wide array.  The array is populated with a pair of file handles for the reading and writing end of the pipe respectively.  Then, you treat those file handles like you would any regular file!  The main difference is that they are more like standard in and standard out than a file on disk, but any programmer worth his or her salt should know how to deal with that!  The document goes on to use read and write calls to send and receive data, but you could easily use any function that reads or writes files for this.  If there is anything complicated about pipes, it is only that they have limited space, but 10kb is a pretty big limit.  Once you have a pipe, you just fork the process, which will provide the child process with copies of the file descriptors to the pipe.  Now the two processes  can communicate with read and write calls (or other file I/O calls) on the pipe.  Of course, if you need two way communication, you will need two pipes, but that is trivial.

The fact is, pipes are incredibly easy!  For some reason though, only low level languages can manage to get them right.  I don't often have something bad to say about Python, but this is one place where Python got it totally wrong!  I have plenty of bad things to say about Java, so it does not really surprise me that Java missed the mark on this one.  So why are pipes so hard in language that are higher level than C or C++?  In fact, I am almost certain that pipes are easier in assembly language than in higher level languages (and I know what I am talking about here).  Clearly the operating system has it right.  Why can't high level languages get it right?  They are supposed to make programming easier if I am not mistaken, but when I start considering writing a C module for Python, because that would be so much easier than just using the built in, you know something is wrong.

The problem is not terribly difficult for me to identify, but much of the programming world is so in love with Object Oriented Programming that they don't want hear anything bad about it, let alone admit that it might have a serious problem.  The problem here is that the OS gets it right in the first place, so it does not need complicated wrappers to make it easier.  At the OS level, pipes are about as simple as it gets.  C is wise to just leave it alone and let it do its thing.  Python, Java, and other languages, however, feel obligated to wrap everything of objects, because hey, object oriented.  The fact is pipes don't need objects.  They are perfectly fine just as they are.  Wrapping them in objects makes them absurdly more complicated and difficult to use, without adding anything of value.  I was actually stunned when I saw the C code in that document.  I had a hard time believing that it was correct, because my experience did not support that conclusion.  Using objects where they are unnecessary is bad design, and we really need to teach programmers to stop doing it.  There are good reasons to use objects, but there are also good reasons not to.

I have talked about this before, but the problem here is OOP, and that is just as absurd as Integer Oriented Programming (or Bit Oriented Programming, as a friend suggested).  When we decide to orient all of our programming around a single data structure (or metadata structure, in this case), we limit ourselves.  We destroy our ability to make good decisions about what tools will be the best for each problem.  Objects are a great tool, but we don't use a chain saw to screw in a screw or hammer in a nail.  Honestly, I feel like multi-processing in Python or Java is just like following some really complicated instructions for how to push a peg into a hole with a table saw without ever touching the peg or injuring yourself.  It would be really nice if those languages would just let me pick up the peg and push it into the hole with my finger, instead of trying to build a huge complex machine around such a simple process.

Thursday, June 1, 2017

Reusable Software Design

I just wrote about reusable software, and I figured reusable software design deserves its own article.  Perhaps the biggest problem I identified with reusable code is that if it is has problems, the time required to learn the code just to fix it largely negates any value in using it in the first place.  If we could easily understand reusable code enough to consistently adapt it to our own use cases, it would be perfect, but that is not how code works.  Code is inherently hard to understand.  Often, we even have a hard time understanding our own code after a few weeks of separation.  Isn't there some way we can consistently benefit from existing work, without the risk of having to spend so much time learning how it works that the cost is greater than the benefits?  It turns out that there is, and in some ways it may even be able to mitigate the costs of choosing not to use reusable code.  The solution is reusable design!

Design patterns have formally existed since object oriented programming became a thing.  Most design patterns are built around OOP.  They don't have to be though.  Things like loops and coherent if statements are primitive design patterns.  Functions are a kind of design pattern as well.  We often don't recognize this, because these have become integral elements of programming, but it is true.  These are all examples of design patterns that don't rely on object orientation.  In fact, very few design patterns require OOP.  Around a year ago, I wrote an event handler that uses the Event Queue design pattern, in C, and I have used the Observer pattern in C as well.  Any programming style or language can use design patterns (even assembly language).  Design patterns are not limited to OOP languages.

Design patterns are superior to concrete code for reuseability, because they are more abstract and flexible.  Design patterns don't specify implementation.  They merely provide a template.  For example, the "for loop" design pattern does not specify the exact number of iterations, the data type of the index variable, or the iteration step.  We can use it to do simple counting, to step through a string one (or two, or five...) character at a time, or to traverse an array.  These are flexible implementation details.  The if statement may or may not have an else or if-else clause.  The expression used to generate the boolean value used as the conditional is not defined for us.  We can use if statements for all kinds of things, because implementation is not defined for us.  Design patterns are flexible enough that it is trivial to adapt them to a particular application.

Good design can save a lot of coding time.  A friend of mine likes to say, "Hours of coding can save minutes of design."  Reusable code is generally endorsed for how much time it can save developers, but it comes with potentially serious costs.  Good design may take longer than crummy design, but it always pays for itself many times over.  Good design can save more time than using reusable code can.  Reusable design (design patterns) can save significant amounts of design time.  This is a double win, because judicious use of reusable design comes with no additional costs, and time spent (or saved) on design is generally more valuable than time spent on implementation.  When we save design time, we also save significantly more coding time.

Good design can reduce the need for reusable code, by finding ways to make coding from scratch faster than learning and using an external library or framework.  When reusable code is the best option, good design can optimize its use to reduce the costs.

Reusable design is, in my opinion, of far greater value than reusable code.  Design patterns are generic enough to solve a large number of problems, and they are easy enough to understand to customize them to a particular application.  Because design time is more valuable than coding time, they also have the potential to save far more time than reusable code.  Reusable design is probably something we should spend significantly more time and effort on.

Reusable Software

Ever since the invention of modular programming, reusable software has been a huge deal.  Nearly ever programming language comes with build-in reusable parts or some kind of standard library.  A great number of articles have been written, extolling the many virtues of reusable software components.  Enormous repositories of reusable parts have been created.  Most problem spaces have complex ecosystems of frameworks, libraries, and sometimes even just short snippets of code or individual reusable functions.  Anything this good has to come at a cost though, and the costs of reusable software are almost universally ignored.

First I want to say that reusable software is awesome.  I am not trying to bash it here.  Reusable software has many great benefits.  It saves a ton of programming time.  Popular reusable components tend to be fairly high quality, because they have already been tried, tested, fixed, and improved.  Reusable components are typically fairly easy to learn and use, because no one wants to use something that is more expensive to learn than writing it fresh would be, and no one wants to use something that takes more effort to use than it would take to roll fresh.  Reusable software can be used to make reasonably high quality software far faster than writing it from scratch most of the time.

Reusable software is a two edged sword, and most programmers cannot see the edge that is facing them.  Reusable software is so good that it is often difficult to see the costs, and even when the costs are known, they are often ignored.  Most of the time, the costs of reusable software are acceptable, but occasionally they can cause serious problems.  For example, recently a large number of web sites stopped working because a trivial piece of reusable code was removed from a popular nodeJS repository.  The time savings for using the code was probably between 1 and 5 minutes for a single developer.  The total cost in web site down time was probably in the hundreds of thousands or millions of dollars.  This is not a common scenario, but it is one that could have easily be avoided by spending a few minutes to write a trivial piece of code, instead of relying on an external source to remain available forever.

Perhaps the most obvious cost of reusable software is fitness of a particular purpose.  To be useful, reusable code must be usable for a variety of applications.  This means it must be generic.  On cost of making something generic is that it becomes less suitable for nearly every application, especially very specialized ones.  For flexible applications that are not critical, the application can generally be adapted to the reusable code.  This will almost certainly affect design, but it rare affects the utility and usability of the application.  Sometimes, however, it does.  Some specialized applications have strict design requirements that a generic component would violate.  In these cases, reusable software just cannot be used.  Occasionally, reusable software will seriously limit the design choices of even more mundane software in ways that are unacceptable.  In these cases, reusable software should not be used.  If using a particular framework or library feels like trying to fit a square peg in a round hole, it may be time to consider alternatives, including writing the code from scratch.

Another fairly obvious but deliberately ignored cost of reusable software is performance.  Making something generic means making it suitable for a wide variety of use cases.  This means a lot of features and a lot of "just in case" elements.  These use memory and processing power, whether you actually need the features or not.  In many applications, this does not make a huge difference.  In some though, it can make an enormous difference.  In applications that are performance critical, reusable code in bottlenecks can be a major problem.  Even in applications where performance is not critical, bloated or slow reusable code can be a problem.  Modern computers never run just one application at a time.  The typical computer is running 10 to 50 processes at any given moment, and all of those processes have to share resources.  While it might seem fine to waste a few megabytes here and there, when there are 50 processes wasting a few megabytes each, memory use can become a serious problem.  Similarly, processor time also must be shared between processes, and a process that is wasteful can affect the performance of the entire machine.  For many kinds of applications, this is rarely a problem but for some (web pages, for example, where a user may have anywhere from 5 to 100 tabs open at a time), a little resource hogging can go a long way.  In general, it is a good idea to keep in mind that reusable code is consuming resources for all of its features, even those you are not using.  A good rule of thumb is that if you are not using more than one or two features of a framework, it might be time to consider looking for something lighter or writing the code from scratch.

Reusable software makes code less maintainable.  This is very counter-intuitive.  There is a general assumption that using a framework or library takes some of the maintenance burden off of the programmer, and this is true.  Reusable code can definitely reduce the burden of maintenance, but this is not about maintenance time spent or saved.  This is about being able to maintain the code in the first place.  Learning exactly how a piece of reusable code works takes enough time that it defeats the purpose of using it, so few programmers bother.  If the reusable code itself has a bug, however, the only options are either to ditch the reusable code and home brew a replacement, pay to have someone spend hours, days, or weeks learning how the code works and fixing the bug, or report the bug to the project and wait for it to get fixed upstream.  The second option is so expensive that it is hardly ever an option.  The typical solution is to sacrifice quality, utility, and usability by working around the bug.  In addition to this, because reusable code is significantly harder to change (because the programmers using it are not intimately familiar with its code), valuable design changes to a program may be impossible.  As with bugs, if a valuable design change is needed that does not work with the reusable software, the options are to ditch it and home brew a replacement, or pay someone for a lot of labor to figure out how to adapt the reusable code.  Of course, once the reusable code has been altered, updates from the original source become invalid, and the reusable code must be maintained entirely in-house, at additional expense.  Again, this is not necessarily a problem that will come up a lot.  Major design changes after delivery are not exactly common.  Reusable code does tend to be more well tested as well, so bugs in it will be more rare.  When they do come up though, they can be very expensive.

Overall, reusable software is very valuable, and nearly ever program uses it in some way.  It also comes with some costs though, and understanding those costs is important to get the most out of it.  Sometimes it is better to write the code from scratch.  Code written to the specific application will always be superior to reusable code.  Reusable code can ultimately be more expensive than coding from scratch.  Cases where reusable code costs more than writing code from scratch are generally uncommon, but determining this should be part of the cost analysis of any project.  In addition, there are different levels of reusable software that should be considered.  Using something like the C standard library or other build-in functions and features of a language is generally a given.  For any popular language, these have been tested and optimized more than anything else.  Libraries for hardware interaction are often necessary as well, though there may be multiple options.  These tend to have more testing behind them as well.  Convenience and aesthetics libraries (jQuery, for example) are typically far less critical, so they tend to have less rigorous testing, and the benefits they provide are less critical.  Less essential libraries that have been around for less time deserve the most scrutiny.  Very small pieces of reusable code also deserve scrutiny, because it may end up taking more time and resources in the long run than just writing it from scratch.  Despite its high value, reusable code is not a silver bullet.  It comes with its own costs, and sometimes those costs can be much greater than any benefits.  Our industry needs to spend a bit more time considering the options and potential consequences than it currently does, and if it did, things would work a lot more smoothly for everyone.