Wayback Machine
102 captures
27 Dec 2014 - 20 Sep 2026
Apr MAY Jun
19
2019 2020 2021
success
fail
About this capture
TIMESTAMPS
loading
The Wayback Machine - https://web.archive.org/web/20200519071126/https://programmingideaswithjake.wordpress.com/

Programming Ideas With Jake

Jake explores ideas in Java and Python programming

Image
  • About
  • Book Reviews
  • Hamcrest Tutorials
  • Kotlin
  • Browse Old Articles
  • Python Descriptors Book

Advanced Creation of Hamcrest Matchers in Kotlin

Posted by Jacob Zimmerman on 2020-01-21
Posted in: General Practices, Kotlin, Testing. Tagged: hamcrest, kotlin, matcher, test. Leave a comment

This article is a rewrite of an older one done in Java. This one is done in Kotlin instead.

Intro

Last time, I went over what a Hamcrest Matcher was, how it’s used, and how to make one. In this article, I will explain more advanced steps in the creation of Hamcrest Matchers. First, I’ll share how to make your matchers more easily type-safe, then some techniques for stateless Matchers, then finally how to cut down on so many static imports on your test classes. I’ll also give some quick tips on naming your static factory methods.

Typesafe Matchers

You may have noticed in the matches() method that we developed last time, I put in a type check. Potentially, you’ll need null checks too, because the method accepts an Any?, which allows nulls. The type check should seem strange, since we inherited from a class that has a generic type that we specified to be a String. Continue Reading

How to Make Your Own Hamcrest Matchers in Kotlin

Posted by Jacob Zimmerman on 2020-01-20
Posted in: General Practices, Kotlin, Testing. Tagged: hamcrest, kotlin, matcher, test. 3 Comments

This article is a rewrite of an older one done in Java. This one is done in Kotlin instead.

Intro to Hamcrest Matchers

First things first, I should quickly explain what a Hamcrest Matcher is. When doing unit testing, the built-in assertion types that come with the testing framework are generally pretty limited. They make it very easy for a person to end up multiple asserts to essentially check one thing. Even if it doesn’t multiple asserts, those asserts aren’t the most fluent to read and don’t tell exactly what you’re checking.

That’s where Hamcrest Matchers come in (and other assertion libraries, but we’re looking at hamcrest right now). They allow you to define your own more robust and more fluent assertions, essentially. For example, if you were testing whether a method correctly returns an empty String, that test might look something like this:

@Test
fun testUsingMatcher() {
    val string = methodThatShouldReturnAnEmptyString();
    assertThat(string, isEmptyString());
}

Continue Reading

Better Unbound Python Descriptors

Posted by Jacob Zimmerman on 2019-05-18
Posted in: Descriptors, Python. Tagged: descriptors, properties, python. Leave a comment

Welcome back from another hiatus! This post is a facepalm post because I recently realized that I’ve been an idiot for so long. I have a tendency to make things more complicated than they need to be, as can be seen in my articles about instance properties.

I’ve briefly mentioned unbound attributes (Class.attr returns a function that you pass an instance into to look up the the value of that instance’s version of the attribute) with descriptors a time or two and they always ended up using a whole new object to represent the unbound attribute. In the example given, I returned a local function to use as the unbound attribute; in the descriptor-tools library that goes along with the book, I implemented it with an UnboundAttribute type, which allowed it to easily carry extra data (such as the descriptor object reference); then I discovered attrgetter in the operator module, so I substituted that in instead. But there was one big obvious solution I was missing.

Some Background

When implementing the __get__() method of a descriptor, the convention was to always return the descriptor itself if an instance was not given. When I started espousing using unbound attributes instead, I always had one caveat: since the convention for so long has been to return the descriptor, it can go against the Principle of Least Astonishment to return something else. So, I always advised using it with a grain of salt.

But I myself didn’t care; I had no real use for returning the descriptor. Really, the only thing that bugged me was that we had to create an object that had barely any use. I really love the style of having lots of small classes doing their things and letting the runtime largely deal with the repercussions, but it always hurt a little bit inside, since this object seemed like a waste.

Good News!

Well, after all these years, I’ve finally realized how much of an idiot I am and that none of these issues have to be issues at all!

The solution? Return the descriptor and give it a __call__() method that takes in the instance and delegates to the __get__() method, as shown:

 

class MyDescriptor:

    def __init__(self, …):

      ...

 

    def __call__(self, instance):

        return self.__get__(instance)

 

    def __get__(self, instance, owner=None):

        if instance is None:

            return self

        else:

          ...

 

This also finally gave me a good excuse for using the default value of None for the owner parameter!

But…

There is still one caveat to this version of an unbound attribute. If the descriptor has another use for __call__(), then using it for this either requires changing the unbound attribute to return some other implementation (one that allows the user to get access to the descriptor, or else having the __call__() method is useless) or you’ll have to use a normal method instead of __call__() for that use case.

Outro

As always, the KISS principle (Keep It Simple, Stupid) prevails. Not only is it simpler in almost every way, but it even makes it so you can ignore all the likely problems.

Updates

Remember how I said I’d rewrite a bunch of Java articles using Kotlin and/or Python? I haven’t even started that. And I probably won’t do that for a while, if ever. I feel bad, but my blog has simply not been a big priority to me for a while. I want to get back into doing it regularly, but that’s not likely. I have another article I’ve been wanting to do for a long time, but I really don’t feel like writing it because it’ll be a lot of example code, and example code always ends up being a hassle with my workflow.

I recently lost my job, so right now I’m focusing on padding my resume with projects and finishing all my planned updates to the descriptor-tools library (which is what inspired this article). Maybe the other projects will do the same thing. I also plan to work on a video for Apress (the publisher of my book) that take some of my book’s content and put it into video form. I may even touch on this article’s topic in those. I’m still not sure what it will be about, but some supplemental income will be nice.

Converting a Cyclic Dependency into a Directed Dependency

Posted by Jacob Zimmerman on 2018-11-27
Posted in: General Practices, Refactoring. Tagged: kotlin, OOP, python, refactor. Leave a comment

So, this came out over a month late… Woops.

This is definitely not my original idea in the least. I wish I knew where I originally found this so I could share that, but seeing that I can’t find it and I haven’t seen it anywhere else, I’d like to share this idea so it can become more well-known.

What is a cyclic dependency? It is one of mutual dependency, where one class depends on another that also depends on the first one, as shown below.

Cyclic Dependency

There can also be more classes in between as shown below, where it just eventually circles back to the beginning.

Indirect Cyclic Dependency

You probably know this, but in case you don’t, you should know that you don’t want these types of situations. They hurt the understandability of your system and make it harder for garbage collectors to clean them up when they’re done. There are probably more reasons, too, but I’ve never paid much attention to this, and it seems that as a whole, the community knows that they should avoid cyclic dependencies but doesn’t do much to avoid it.

Anyway, what you’re looking for is a nice acyclic directed graph of dependencies as shown below, where all the arrows point down.

Acyclic Dependencies

So, how do we go from this

Cyclic Dependency

To an acyclic directed graph? What would that graph look like?

Well, it would look like this!

Fixed Dependencies

You take the part of the class that is depended on by the other class and extract it. Do this for both classes, and your problem is solved!

With these super vague graph images, it may be difficult to really see how this can actually be done, so I’ll give you a really simple code example (written in Kotlin and Python!). It should help you get started when breaking apart your cyclic dependencies.

class A {
   var b: B? = null
   var _observed: Int = 0
   var observed: Int
       get() = _observed
       set(value) {
           _observed = value
           b?.alert()
       }

   fun alert(): Unit {
       println("A.alert")
   }

   fun doSomething(): Unit {
       alert()
   }
}

class B {
   var a: A? = null
   var _observed: Int = 0
   var observed: Int
       get() = _observed
       set(value) {
           _observed = value
           a?.alert()
       }

   fun alert(): Unit {
       println("B.alert")
   }

   fun doSomething(): Unit {
       alert()
   }
}

 

class A:
   def __init__(self):
       self.b: B = None
       self._observed: int = 0

   @property
   def observed(self):
       return self._observed

   @observed.setter
   def observed(self, value):
       self._observed = value
       self.b.alert()

   def alert(self):
       print("A.alert")

   def doSomething(self):
       self.alert()

class B:
   def __init__(self):
       self.a: A = None
       self._observed: int = 0

   @property
   def observed(self):
       return self._observed

   @observed.setter
   def observed(self, value):
       self._observed = value
       self.a.alert()

   def alert(self):
       print("B.alert")

   def doSomething(self):
       self.alert()

The two classes are almost exactly the same, but that doesn’t really matter. What matters is that the dependent parts can be extracted. What parts of type B does A depend on? And vice versa? Each class depends on the other’s alert() method. So let’s extract those out:

class AAlerter {
   fun alert(): Unit {
       println("A.alert")
   }
}

class BAlerter {
   fun alert(): Unit {
       println("B.alert")
   }

}

 

class AAlerter:
   def alert(self):
       print("A.alert")

class BAlerter:
   def alert(self):
       print("B.alert")

Now the other classes can depend on these

class A (var a: AAlerter, var b: BAlerter) {
   var _observed: Int = 0
   var observed: Int
       get() = _observed
       set(value) {
           _observed = value
           b.alert()
       }

   fun doSomething(): Unit {
       a.alert()
   }
}

class B (var a: AAlerter, var b: BAlerter){
   var _observed: Int = 0
   var observed: Int
       get() = _observed
       set(value) {
           _observed = value
           a.alert()
       }

   fun doSomething(): Unit {
       b.alert()
   }
}

 

class A:
   def __init__(self, a: AAlerter, b: BAlerter):
       self.a = a
       self.b = b
       self._observed: int = 0

   @property
   def observed(self):
       return self._observed

   @observed.setter
   def observed(self, value):
       self._observed = value
       self.b.alert()

   def doSomething(self):
       self.a.alert()

class B:
   def __init__(self, a: AAlerter, b: BAlerter):
       self.a = a
       self.b = b
       self._observed: int = 0

   @property
   def observed(self):
       return self._observed

   @observed.setter
   def observed(self, value):
       self._observed = value
       self.a.alert()

   def doSomething(self):
       self.b.alert()

You may notice that, due to the cyclic dependencies, there was no way to create instances of the original classes without null/None because each one would require an instance to exist in order to make it.

Now, it’s possible to create an instance where the constructor takes in all of the fields without any temporary nulls/Nones.

Outro

As I said before, I realize that this is a super simple example, and I don’t expect it to make you into experts on removing cyclic dependencies. What I do expect is that you now have your mind wrapped around the basics and can start trying to take apart some of these when you see them.

I will admit that there is at least one “kind” of cyclic dependency that this doesn’t fix: A child pointing back to its parent. For example, you have a FilingCabinet with a list of Files in it, and those Files also have a pointer back to the FilingCabinet they’re in if you ever need a way to traverse back up the tree when you don’t know the original already.

The advice I’ve seen on this is to lose the link going back to the parent and instead put in a method that does some kind of lookup to find the parent. This is silly; it still has the cyclic dependency; it’s just that the dependency is either one step further removed (for a fully in-memory, in-language lookup) or is pulled into a different kind of system (for something like a database lookup).

I recommend either trying to make it so that the code doesn’t need to go back up the tree or that the parent is passed in along with the child, possibly in some sort of custom parent-child pair type.

Python Descriptors 2nd Edition!

Posted by Jacob Zimmerman on 2018-10-15
Posted in: Books, Descriptors, Python. 1 Comment

The second edition of my book was just published and available at the source and on Amazon. To purchase, just click one of the links in the sidebar!

Also, I’ll be writing up a new article to be published on here this weekend, so look forward to that!

Updating Old Posts to Kotlin (and Other Updates)

Posted by Jacob Zimmerman on 2018-03-21
Posted in: Descriptors, Kotlin, Python, Uncategorized. Leave a comment

I was looking through some of my old posts, and started reading one that I wrote for Java, and I just didn’t like it. So, I’ve decided to go through and rewrite a bunch of the old posts (I’ll keep the old ones as they are), updating them to Kotlin. In some, I may even put the old Java code in just to show how much nicer Kotlin makes it.

Other Updates:

I’ll try to get the Java/Kotlin version of the DocRaptor article written soon. Also, I’m in talks with another website to write paid posts for their blog. If I get to, I’ll share links to the articles I post there.

I’m also in talks with Apress to write a second edition of my book, Python Descriptors. Changes will mostly be adding content on the __set_name__() method added to the descriptor protocol in 3.6 as well as a full chapter on my instance–level properties idea. Other than that, I’ll be going through and just cleaning up the writing in general if I spot anything. I’ll probably also simplify the flow charts. At the same time, I’ll be putting together a talk on Python Descriptors that I hope to give at That Conference this year.

Overall, I’m feeling the push to get back to writing. Hopefully, I can keep up with it.

DocRaptor and its Python APIs

Posted by Jacob Zimmerman on 2018-02-17
Posted in: Python. 1 Comment

First off, I’d like to thank DocRaptor for sponsoring this article. I’m pretty well off, but this money will be able to help my siblings out, who aren’t so lucky. It also got me to discover their service, which I may find myself using in the future.

What is DocRaptor?

DocRaptor is an online service that can be used to transform HTML documents into PDFs or even Excel documents. This is a paid service, but there’s a 7-day free trial so you can have a chance to try it out first. They have 8 different plans, ranging from 125 documents per month for $15 per month to 100,000 documents for $2250, plus a level for an unlimited number of documents, for which you need to contact them to set up a price. Continue Reading

Posts navigation

← Older Entries
  • Python Descriptors Book

    View RSS Feed

  • Check Out My Book!

    Image

    Find it at the Apress Web site (official location)

    Or purchase it on Amazon

  • Upcoming Posts

    No upcoming events

  • Upcoming Events

    No upcoming events

  • Want to Browse Old Articles?

    You can find them here!
  • Ads

    Free Trial of Audible for a Month!
    Image
    Image

    If you already have an Audible account and want to help me a little, you can use my affiliate link to go shopping on Amazon while leaving me a tiny cut automatically :)

    Pay for My Shave
    Image

    Join the Dollar Shave Club to earn me $5 to use on their site

    I don't really like ads, so you should know that I only post these ads because I'm a very satisfied customer of their products. I don't feed my ads in from some silly service.
  • Affiliated Aggregators

    Java Code Geeks
    Web Code Geek
    Planet Python

    If you know of any other blog aggregators that might be willing to add my blog, let me know by emailing me at jacobz_20 at yahoo dot com.

Create a free website or blog at WordPress.com.
Programming Ideas With Jake
Blog at WordPress.com.
Cancel
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy