Wednesday, December 24, 2014

Decoupling Dependencies in JavaScript

Dependency Injection

The goal of dependency injection is to decouple objects from their dependencies as much as possible. This means to decouple how the dependencies are selected, but not how they are used.

How a dependency is used depends on abstractions: the client code expects a particular interface and does not care what the dependency object is as long as it provides the interface. This works particularly well in JavaScript where duck-typing is favored over class inheritance.

The solution for decoupling the selection is to move the responsibility of selecting the actual dependency to another piece of code. This decoupling of is the implementation of a principle that Martin Fowler calls "Inversion of Control," and Robert C. Martin titles "Dependency Inversion," the fifth of his SOLID principles of object-oriented development (Fowler, Martin). They have more to say about that than I do! What I will discuss here are the forms that decoupling can take in JavaScript.

JavaScript Mixins

Building a JavaScript Mixin


In JavaScript a "mixin" is to add the properties of one or more source objects to a target object. To be precise, there are actually two kinds of mixins: a shallow copy and a deep copy. A shallow copy simply copies the references from the source to the target, and a deep copy clones the references.

So why a mixin? Well, there are two really good examples and both of them revolve around prototypes. The first involves AJAX. When JSON data is returned from a web service call it only contains data, no methods. That is intentional; if instantiating a JSON object added methods to the local program that would be an opportunity for evil code to be injected into a program from a remote source. But what if the data returned really represents something like a bank account, where our design depends on methods defined as part of the object? The ECMAScript 5 (current) and earlier specifications do not allow a prototype to be assigned to an existing object (our JSON object), nor does the JSON.parse method provide a means for a prototype to be attached. A prototype can only be attached to a new object during creation. So our solution is to create a new, empty object with the right prototype and then mixin the data properties from the JSON object.

Sunday, November 30, 2014

Localizing Razor Views


The Problem

Occasionally it is advantageous to move beyond resource files to support localization in an ASP.NET MVC application. Resource files contain localized phrases, blocks of text, images, and other resources that may be referenced from a view. The advantages of resource files are that there is a clear structure for defining localized data, the views incorporate pre-defined functionality to reference a resource key (name), and the views rely on the framework to select the correct localized resource file.

The disadvantage of resource files with large chunks of localized text, images, and other resources is that the view becomes just a template referring to the data. It is not possible to see the data while working on the page and the feel for the information on the page and how it is presented is lost in both the source (HTML) and WYSIWYG editors.

Tuesday, August 19, 2014

Testing Wars

I am sitting in the back of the room during the last four weeks of a really intense twelve-week Java boot-camp, and this is the third time this question has come up: "if I make private methods how do I test them?" Encountering it once every two months is not bad, because it is a really, really good question.

Wednesday, July 30, 2014

AngularJS and Dependency Injection

Someone came to me lost on what "dependency injection" is and why we use it, and there is an easy explanation. Dependency Inversion is the the "D" in Robert Martin's SOLID principles of object-oriented programming (Martin). "Injection" is one implementation of dependency inversion. But what does it do for us? What does it mean when Angular folks talk about it? And how does it work?

Thursday, July 24, 2014

Eclipse Team Projects & Best Practices

Sometimes the metadata attached to an Eclipse project contain absolute pathnames to files on the local computer. That becomes an issue when the project is moved to a different location, to another computer or even on the same computer. It happens almost all the time with Java projects but potentially any Eclipse project has this issue. It is usually introduced by plugins that the Eclipse team has no control over, even though there are provisions for them writing relative pathnames. For example the Grails plugin always writes absolute pathnames into the file .project, even for files inside the project. What's up with that?

When absolute pathnames are included in a source code management (SCM) repository, such as Subversion or Git, then two serious problems occur. First when the project is checked out by another team member the first user's settings in the project do not correspond to the location of resources on the new computer, so the second user has to fix all of that. Even more important, when the second user checks the project back in and the first user checks it out the changes then first user's settings are all out of whack and have to be fixed again. Then the cycle of checking out new stuff and fixing project settings goes on forever.

A typical approach to handling these problems is to configure the SCM to ignore the .classpath and .project files, and all the files in the .settings folder. That is a simple approach, but it is not necessarily the best approach. So what exactly are the best practices in a team environment? After we investigate those we will look at step-by-step scenarios for Subversion and Git.

Tuesday, July 8, 2014

Type is a Property so Empty Classes are OK!

The first time I encountered the phrase "type encapsulation" it took a moment before I realized that it meant what I knew as "the type of a class is a property of the class." There is nothing quite like finding fancy names to label things, but I have to admit it is easier to say.

So the type is always a property of the class, albeit a hidden property. What if the type is the only property of the class? What if there are no other fields or methods in this class? One school of thought is very adamant that no class should ever be empty. The folks in that school will fight to the end that a design is wrong if it has an empty class.

Wednesday, June 25, 2014

Static is Evil

Well, static is not evil but how people use it sometimes is. My friend Susan has taught Java for years and will forever be remembered for the mantra that "static is evil." In an object-oriented boot camp Susan taught there was one group who named themselves "Static is Awesome" just to make her say it! Spreading the message is a good thing. Not because static is evil, but because when static is misused it leads to brittle programs.

The word static means "fixed in position," it cannot be moved. In a computer language we have long applied the keyword static to "fix" the location of something. The how and why of fixing that location has changed over the years. Regardless of the particulars, something that is fixed is contrary to the principles in object-oriented programming where dynamic and abstract structures create robust and adaptable programs! Let's take a look at why that happens...

Monday, June 2, 2014

The LSP in Dynamic Languages

A question was raised with me about the effect of dynamic languages on the Liskov Substitution Principle. If you are a little vague on the LSP it goes beyond the basic idea of substitution to include behavior. I have another article that explains why the LSP cannot allow a square to be a rectangle because of the expected behavior.

Java and C# are examples of strongly-typed languages that support both early and late binding. They will check at compile time to make sure that a class has the correct interface to support an operation (method overloading), and at run time a decision is made as to which method will actually be used based on the object type (method overriding). This is a class diagram that shows an AccountCollection can contain a group of Account objects and does not concern itself with the actual subclass that each object is:

Saturday, May 24, 2014

What's Groovy about Grails!

This post is a written version of my short presentation about Groovy and Grails. The advantage is that I can link to some external resources to give you more information to pursue. I expect that you have some computer programming experience, and you know what variables, statements, functions, and subroutines are. Many folks in my audience have a structured or procedural programming background so I am going to argue in favor of the object-oriented concepts that Grails depends on.

Tuesday, May 13, 2014

Grails & STS: Avoiding Build Problems

This post has been updated to reflect new information about how Java launches, the release of Grails 2.4.0 on May 21, 2014, and to introduce a section on using Grails in a team environment with a source-code management system.

I recently started to experience some very interesting issues with Groovy, Grails, and STS/GGTS while I was teaching some recent classes. I believe that most of them boiled down to idiosyncrasies on the computers in the classroom, and really most of them appeared when the students used their own computers.

So I decided to undertake a quest to find out what happens when you use Groovy, Grails, and then throw STS into the mix. Yes, I really did have to say "a quest." Anyways, it turns out that the rules are actually simple, but the folks at Apple, Microsoft, Oracle, and Pivotal (these are only ordered alphabetically) assumed that you would either not need them or learn by osmosis what they are. The good news is: you can manage multiple installed versions of Groovy, Grails, and most importantly Java, you just have to know what affects them!

By the way, even if you are not interested in the problems with Groovy and Grails, the first two sections are also very important for Java programming.

Monday, May 12, 2014

Really, it's Controller-Model-View!

We have all had our moments when folks are talking about some idea and treat it as such an obvious thing that we are too embarrassed to say that we do not know about it! Well, model-view-controller or MVC as it is called is one of those things that pops up in application development that we think everyone understands. Let's fix that here!

Friday, April 11, 2014

When a Square is not a Rectangle!

Or how the Liskov Substitution Principle extends basic substitutability

The square vs. rectangle problem is a frequently used example of a class inheritance problem found throughout object-oriented programming. If you are not familiar with the problem, it addresses the issue of deriving a square shape from a rectangle. Mathematically a square is a rectangle. On the surface, modeling that relationship in OOP is simple, but when you drill down it gets a lot more complicated.

Monday, April 7, 2014

The Right Tool for Every Job

My grandfather was a carpenter from the old world. He, and then my father taught me some carpentry when I was a youngster. They always told me to use the "right tool for the job." About once a year, maybe more, I catch an article in IEEE Computer or the Communications of the ACM by some college professor telling me that object-oriented programming is a bad approach to software development. First I have a "huh?" moment. Then I think about using a bigger hammer, because clearly that is the best tool for every job!

Seriously, I learned a long time ago in school that the computer vendors like Digital Equipment Corporation were practically giving away their equipment to universities. Why? Because when students learn to use their computers in school, then after they leave they push for their employers to use the same systems too. When you have a favorite tool you want to use it everywhere. It's the old adage: "when your favorite tool is a hammer, every problem looks like a nail!"

Friday, April 4, 2014

Protect the Melon, er, the Database!

Little Bobby Tables comic used with permission from xkcd.com
Little Bobby Tables comic used with permission from xkcd.com.

In the related article Encrypting JDBC Connection Strings I explored one technique to externalize an encrypted username, password, and connection string. Here I want to explore some advanced methods to protect the data source, starting SQL injection attacks and moving forward.

SQL Injection Attacks

Consider the following Groovy&Grails example (it's a lot like Java), where the user is prompted for a student id and an SQL statement is constructed to retrieve that row from the students table. In Grails the form fields arrive at the method as a map of name=value pairs, and Groovy has cool parameter-substitution in strings. It is pretty clear how the student ID ends up in the SQL string:

Encrypting JDBC Connection Strings

Authentication between an public-facing web application and a data source is always difficult because of the possibility that the information may be compromised at the application server. There are two primary approaches: simple user names and passwords or RSA public-private keys to identify the application. We are interested in the first case because it is commonly used.

Our assumption is that the application server has already been breached, so what can we do to protect the data servers behind the application? We need to use a defense-in-depth approach: multiple layers of security using different technologies frustrates attackers: that forces them to have exploits to circumvent every device used.

Defense-in-depth of the data includes protecting the database from SQL injection attacks and limiting access to the database from a small set of computers. These defenses are discussed in other posts, our immediate focus is on protecting the credentials for authentication.

Monday, March 17, 2014

The Big Deal with Big Data!

I pre-date the relational database management system world (RDBMS), having been weaned on things you may never heard of, like ISAM (indexed-sequential access method). So, I have to admit that I was a little skeptical about the NoSQL world. It sounded a lot to me like ISAM, and why go backwards? But it is not fair to dismiss something out of hand so of course I had to investigate these NoSQL databases. And while I do not believe at all that the days of RDBMS are numbered as some folks say, I do believe that NoSQL has its place. To understand why, you need to know the terrain.

Onwards to RDBMS

In a simple view of the early days we basically used a sequential table of records. Most of the time the records were fixed length, reading the whole set sequentially was fast, and we used indexes to quickly locate a record based on a key. Does any of that sound familiar? Need to look up records by more than one field? Add an index! When you need to sort the records faster you pick an index and sort that instead of the table itself. An example of a single-index product still prevalent is Ken Thompson's dbm, which was included with Unix in 1979. I would provide a citation, but it would be myself because I first came across it when I upgraded to Unix Version 7.

Thursday, February 27, 2014

Don't Get Wet: Stay DRY on SOLID Ground!

If you've been doing object-oriented programming then you know about inheritance, references, and so on. But are you ready to go full-throttle on application design? To achieve that we need a solid foundation in using the fundamental principles of design and design patterns.

A principle is a fundamental rule that we want to follow because it produces better results. Robert Martin (Uncle Bob) identified five fundamental principles and grouped them under the acronym SOLID (Martin). They started out as SOLDI, but Michael Feathers pointed out to Bob that if they switched the last two principles they would spell a cool acronym (Hansel). Andy Hunt and Dave Thomas identified another important one: Don't Repeat Yourself (Hunt). And underlying all software development I insist on recognizing that there is a general, unspoken principle of organization, which all of these principles are related to.

My interest is to explore what is behind these six principles, why they are so important, and how they relate to each other. I've spoken about these topics frequently, this is my chance to put some of those thoughts down in writing. I will try to be agnostic about whether we are using a class-based (C++, Java, C#) or prototypal (JavaScript) environment.

Friday, February 21, 2014

Custom Types in Object-Oriented Languages

C++ inherited a preprocesser command from C: typedef. It is a form of abstraction. Think about it: if I can assign a new name to an existing type with this, then I'm encapsulating that type behind an abstraction. If I need to change the definition I don't need to recode all the clients that use it. And in C++ it works with templates!

#typedef CustomerList vector<Customer&>;


The reason C gave us typedef is to simplify the type names used. Simplifying things reduces the mistakes that are made.

Thursday, February 20, 2014

There Can Be Only One!

Well, I want to talk about singletons but that title is a bit misleading because you can have more than one instance of a singleton. Say what? My definition of a singleton is "restrict a class or object to a single instance in a shared context." OK, I know my definition isn't exactly the Gang of Four's: "Ensure a class only has one instance, and provide a global point of access to it" (Gamma). But honestly, some folks take that book way to literally.

Those guys used "global" in the context of C++ applications mostly written for the desktop, and their point gets twisted by the choice of that word. When you move the management of the object into the class, as the GoF teaches us, then that could mean one object in a module. Or what about web-server applications: how about one per connection, or one per session? Such software wasn't really around in 1994, that is why almost two decades later the the word context is really a better choice for the description.

Friday, February 14, 2014

High Cohesion and Low Coupling

We don't often talk about cohesion and coupling at the same time but maybe we should. High cohesion is not a principle, it's a state that we try to achieve. Cohesion is a metric: a measurement of how closely related a group of things are.

We have been tasked with designing software for a bank. Here is our first shot at what an account should look like in the Unified Modeling Language. We are going to take this back to our customer and make sure that we are all on the same page about how an account works:


You may not like this example. Maybe you see some problems, or maybe it's just a feeling that something is wrong. So, let's pull it apart and find out exactly why!

Monday, February 10, 2014

In JavaScript Everything's an Object, Get Over It!

Today I am staying out of the philosophical discussion about whether JavaScript is truly an object-oriented language. FYI a lot of that discussion revolves around polymorphism and that because it is not strongly typed it does not have overload methods. That is true of other languages too, consider Groovy. But for the moment, let's just say that if we can actually create objects with properties then we can do some OOP with it.

In this article I am only interested in the tools that JavaScript has to build objects, and JavaScript is a bit schizophrenic about that. For example JavaScript defines the "new" operator so that creating an object looks more like programming Java. But we can also create objects literally or by using the grandparent of all objects: Object.

Let's take a tour of object creation and see if we can sort some all it out. First of all, we can define literal objects and properties using a comma-separated list of "name: value" pairs enclosed in braces. The property names should follow the identifier rules for JavaScript, and the value can be anything: a string, a number, an array, a reference to another object, or even a function. We can save a reference to the new object in a variable, and we can retrieve or assign new values to a property using the the variable and the . (dot) operator:

newline = '<br />';
Box = { width: 4, height: 5 };
document.write('The box is ' + Box.width + ' x ' + Box.height + newline);
document.write('The box volume is ' + (Box.width * Box.height) + newline);

Secondly, by default all JavaScript objects are extensible; all you have to do is assign a value to a new property and the object has it:

Box.depth = 6;
document.write('The box is ' + Box.width + ' x ' + Box.height + ' x ' + Box.depth + newline);
document.write('The box volume is ' + (Box.width * Box.height * Box.depth) + newline);


So, back to that new operator. It works with a function and builds a new object:

function Rectangle() {
}

var shape = new Rectangle();


Sunday, February 9, 2014

Collaboration

Including the answer to: "What exactly is the difference between aggregation and composition?"

One facet of the principle of Single Responsibility is that each class is responsible for one thing. Specifically, Robert Martin defines this as each class should "have only one reason to change" (Hansel; Martin, Agile). When you apply the idea of Single Responsibility to classes in an object-oriented design then the classes must work with each other to accomplish more complex tasks, and you just forced collaboration. There are several types of relationships that classes use for collaboration. We are going to look four: dependency, association, aggregation, and composition.

Saturday, February 8, 2014

XML Validation in Client-Side JavaScript

XML and JavaScript
This week Alan, a participant in an advanced JavaScript course, posed a question to me: "how can I validate the XML returned from an AJAX call against a DTD or Schema?" I have to admit that I hadn't really considered it before. In retrospect I've always been in the camp that figures the server is part of the greater application, the server is the source for the data, and we can safely rely on it. But what if we can't? Or we shouldn't? The good news is that at least one JavaScript library exists that can validate a document against a schema; the bad news is that it cannot validate a document against a DTD.