alan

programming

Really. Stop (ab)using just strings and integers!

Yes, they're the building blocks of whatever you do. But if you abuse them, you're not taking full advantage of your Object Oriented programming language.

Let me explain with some concrete example. For the sake of conciseness, I'll use Python here, but the concepts fit most OO languages. Classes are your friends.

Really. Classes and type systems weren't invented to make you feel miserable and add bloating to your code. They were invented to help you to write correct code, letting the machine verify you're doing things properly and consistently.

But if you don't use them, the machine can't help you. And no, dynamically (yet strongly typed) languages aren't a good reason to skip correctness and proper OO design.

Let's start with some examples:

def retrieve_web_resource(http_url):
    #[...]
    requests.get(...)

What is that http_url ? In many contexts, it will probably be a string. But this is not a best practice. Primitive types like strings carry very little semantics and probably do not enforce domain boundaries. What does that mean?

It means that somewhere in your code you have something like

    my\_http\_url = somewhere.create_url_from()

(with my_http_url still being of type str) and then you carry it around as a str. Maybe, at some point, you manipulate it. And, possibly because of some error or because some unexpected data was thrown in, at some point it ceases being a valid http url.

This might mean that, in many parts of your code, whenever you use such value, you may be tempted to check some preconditions:

def retrieve_web_resource(http_url):
    assert http_url.starswith("http"), "not an http url"

But then, you need to check those preconditions everywhere!

And, if you happen to pass your variable around, and at some point you pick a less-than-meaningful variable name, it may be hard to understand, when debugging or if a serious error happened that totally messed up the content, what that variable was supposed to contain.

So, what is a much better solution? Create the right type, always, and use those types in your application. Example:

class HTTPURL(object):
   def __init__(self, scheme, host, path, query=None):
       if scheme != "http":
            raise ValueError, "not an http url"
       # validate host
       # validate path
       # validate query - should be a param-value dict
       self._host = host
       self._path_parts = path_parts
       self._query = query if query is not None else {}

   @classmethod
   def parse_from_str(cls, http_url_as_str):
       # parse the url, then
       return cls(scheme, host, path, query)

   def add_query_param(self, param, value):
       # add param and value to dictionary, return a new
       # HTTPURL object with that additional value. Raise
       # an error if such value is already defined

   def append_path(self, additional_path):
       # properly append additional_path, checking for 
       # missing or duplicate initial slashes, etc, then
       # return a new HTTPURL object.
    
   def __str__(self):
       # create the url from current variables, and return it as
       # a str

(this is simplified – you might want to add auth data, port, etc)

See the point? You're making sure that no invalid http_url instance can exist, and you're providing proper methods to manipulate such instance. This way you're encapsulating your domain knowledge about URLs in a specific class, instead of scattering and duplicating it everywhere and you're making it really hard for users to commit accidental mistakes – they would be caught quickly.

The HTTPURL we've seen here is composite and this approach may make a lot of sense, but in Python you can even use Tiny Types in a very, VERY efficient fashion, when you just need to add some semantics and some validation without a full-fledged class because you just don't need that kind of manipulation:

class Angle(int):
    def __new__(cls, v):
        if isinstance(v, Angle):
            return v
        if v < 0 or v > 360:
            raise ValueError("invalid angle, must be within 0 and 360")
        if not isinstance(v, (int, long)):
            raise TypeError("invalid angle type, must be int or long")
        return super(Angle, cls).__new__(cls, v)

See? The instances you create are of type Angle, but they're still an int! So you can pass them straight to other apis/libraries that just don't support or know nothing about your custom types, and yet you get semantics and validation!

Of course, if you need more operations you'll need to redefine more methods:

class Angle(int):
    def __new__(cls, v):
        if isinstance(v, Angle):
            return v
        if v < 0 or v > 360:
            raise ValueError("invalid angle, must be within 0 and 360")
        if not isinstance(v, (int, long)):
            raise TypeError("invalid angle type, must be int or long")
        return super(Angle, cls).__new__(cls, v)

    def __add__(self, other):
        return Angle(int(self) + int(Angle(other)))

angle = Angle(10)
angle2 = Angle(2)
angle3 = Angle(angle2)

print angle+angle2
print type(angle+angle2)
12
<class '__main__.Angle'>

Do you think all that is too verbose, and you'd just prefer to stick to string and ints? Well... I suggest you try this approach, check how many bugs you prevent and/or how your code becomes more expressive and cohesive, and then think again about verbosity. If your code is more compact at the expense of correctness and automated checking, maybe that compactness isn't worth it.

#Ollivander #programming #TypeSystem

There's a practice of good programming which is often referred as One Assertion Per Test. In the opinion of some people, this practice would advocate the usage of a single call to xunit assert method for each test.

I think that idea is plainly wrong. Saying “One Test Per Test” would have been better, but implied an high tautology risk.

Let's take an old-and-trite shopping cart example; we have a cart which the user fills, then a checkout happens and we have a completed order, which holds things like a total amount for the order and a list of items.

Sometimes people will complain about this (Python is used throughout the examples, yet the concept applies to any language):


def test_successful_checkout(self):
    item1 = Item(price=10.00)
    item2 = Item(price=20.00)
    cart = Cart()
    cart.add(item1)
    cart.add(item2)
    completed_order = Checkout.perform(cart)
    self.assertEquals(30.00, completed_order.amount)
    self.assertEquals([item1, item2], completed_order.items)

(I know floats aren't good for currency. I just didn't want to make the example too long.)

and yet would find the following completely acceptable:


def test_successful_checkout(self):
    item1 = Item(price=10.00)
    item2 = Item(price=20.00)
    cart = Cart()
    cart.add(item1)
    cart.add(item2)
    completed_order = Checkout.perform(cart)
    expected_order = CompletedOrder(amount=30.00, items=[item1, item2])
    self.assertEquals(expected_order, completed_order)

Do you see? One assertion per test.

{% img center /images/download.jpeg %}

Frankly speaking, that's bullshit. One assertion per test does not mean that. One assertion per test means test ONE THING for each of your tests. You should begin thinking about whether your object does too many things and whether your test methods are properly named.

A possible example would be:


def setUp(self):
    item1 = self.item1 = Item(price=10.00)
    item2 = self.item2 = Item(price=20.00)
    cart = Cart()
    cart.add(item1)
    cart.add(item2)
    self.completed_order = Checkout.perform(cart)

def test_successful_checkout_order_amount_is_the_sum_of_item_prices(self):
    self.assertEquals(30.00, self.completed_order.amount)

def test_successful_checkout_order_items_are_items_from_the_cart(self):
    self.assertEquals([self.item1, self.item2], self.completed_order.items)

Here, since the checkout process is doing multiple things (and it probably should as it is a checkout – this is probably more an example of an acceptance test rather than a unit test), we test them separately. If either fails, we know why and can go straight to the issue – and yet consider rewriting the second test like that:


def test_successful_checkout_order_items_are_items_from_the_cart(self):
    self.assertEquals(self.item1, self.completed_order.items[0])
    self.assertEquals(self.item2, self.completed_order.items[1])

If the example above is good, that's good as well, and you may have reasons for doing things like that – maybe your test framework doesn't show you the differences in a very clear way and you want to be sure to quickly catch the wrong item. This is what Robert C. Martin calls Single Concept per Test in his own Clean Code book – a recommended reading!

So, “You're testing multiple things in a single test” can be a good remark. “You're using multiple assertions per test”, on the contrary, means nothing.

#Ollivander #programming #testing #bestpractices #software

I don't like php, and I've got my reasons. I've met a lot of people who dislike PHP and don't see how possibly anyone, anyhow, could think about ever using PHP in any real-world project out there, and simply dismiss PHP as a crap being created and used from and for incompetent stupid people around the world.

On the other side there're a bunch of PHP supporters which show you how wonderful is PHP, how many people use it and how widespread it is, and whoever says the contrary is just an enterprisey fool which spends nights at getting things done in Java or C#.

I disagree with both groups (of course!) and I think that PHP's got its unique set of killer features that make it still valuable, and those should be acknowledged.

First, it's not PHP by itself – there's the [LAMP stack](http://en.wikipedia.org/wiki/LAMP_(software_bundle%29), a de-facto pseudo-standard; interoperability of PHP applications on many different hostings work quite well. This is very different from most other platforms, where you must either adapt your development environment to what your hosting provides, like in Google App Engine, or you must find a way to tune your hosting environment to match your required dependencies. Not even Java, which heavily relies on standardized APIs, was able to reach a similar consensus on a standard stack.

And this sort of Platform-as-a-Service offering is widespread. This is catching on lately for other languages with things like Google App Engine, Jelastic, Engineyard, Heroku (while this last one is slightly more complex), but on PHP there's simply a incredible amount of really cheap and simple hosting. If you're willing to spend something like 50 EUR an year you can find out really good PHP hostings just everywhere, and you can expect to go down to 15 EUR per year and still have something that's pretty decent.

What's all this hosting good for? Do you create your own custom software in PHP and run on top of that? Of course not! Many experienced PHP developers go with their own infrastracture in order to have full control and tuning; the real bulk of PHP installations (IMHO – I don't have collected actual data on such topic, maybe one day I will) consists of existing free software installations. Existing software written in PHP makes the difference. There're a lot of people that simply don't care about PHP or programming at all, and yet they use PHP every day thanks to existing open source software.

Do you want a blog engine that you can customize and offers a variety of plugins that have nothing to do with a blog? Here's Wordpress. Would you like to manage a community? Drupal is your friend.

Please note that, more often than not, the available PHP software is not the “best of the breed”. Other software exists that is better, or faster, or offers more functionality, but PHP is usually “good enough”, allows “quick and dirty” customization, and it's free.

And doesn't require to be a developer to be installed – it's targeted at the slightly experienced user. I think that installation wizards in PHP are really well constructed (although they often require full manual intervention and it would be hard to automate them via command-line scripts or similar) and I sometimes miss them in other languages (like Ruby, Python, Java), where heavy command-line and config editing is required, many times in non-obvious way. Most PHP applications contain the application AND a web-based configuration tool for such application

  • that's an obvious thumbs up.

The “install your own web software” approach is getting less useful nowadays, with a lot of great services around that let you do almost anything you'd do with a php software, yet it was very common until mid 2000s to setup your own hosting and your own software instance, and it retains a lot of charm on users that want to feel empowered, that want to “own” their website and make modifications to it (and maybe they want to say they're PHP programmers because what they did) – php can be edited and new pages appear live on the server!

Then, don't forget there're many PHP developers around the world. It's not an exotic language – it's quite mainstream, if you need a custom feature you won't go in mancraft-starvation mode. Developer quality in such world may be a problem, but if you can find somebody who's not a PHP-only developer, you should feel safe.

And remember: most software for PHP is content-centered. There's very little business logic in it. PHP works well as long as your application only does only CRUD. Advanced usages, anything that would require a sort of application server or persistent, long-running process, should be avoided.

So, PHP is simply great for its target. If you want to have your own website, with your own domain, where you can do whatever you like, you don't care for quality, uptime, or security, PHP is simply the right tool for you.

You can even use it for learning some programming basics, but PHP is gotcha-intensive, and you aren't a real PHP programmer if you don't know at least 75% of such gotchas :–). Good luck!

#Ollivander #php #programming #web