Programming Ideas With Jake

Jake explores ideas in Java and Python programming

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

Don’t Mock Your Domain

Posted by Jacob Zimmerman on 2020-07-27
Posted in: Testing. Tagged: clean architecture, python, TDD. 1 Comment

Hello again, everybody! Today’s article is made possible by Leonardo Giordani. He wrote a pretty good book called Clean Architectures in Python which is pay-what-you-want. I’m not quite done with it yet, but it’s a pretty good book so far, especially considering its cost. 

He opens up by talking about TDD for several chapters in order to make sure you know what’s going on for the latter half, where he builds a simple Clean application from the ground up giving you his unit tests before the code. He didn’t go step-by-step, so it’s not tedious in that way. But there’s a problem I have with a part of the book that I’d like to address. To do that, I need to do the most basic primer on Clean Architecture first.

Continue Reading

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.

Continue Reading

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.

Posts navigation

← Older Entries
Newer Entries →
  • Python Descriptors Book

    View RSS Feed

  • Check Out My Book!

  • 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!

    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

    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.

Blog at WordPress.com.
Programming Ideas With Jake
Blog at WordPress.com.
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
  • Subscribe Subscribed
    • Programming Ideas With Jake
    • Join 41 other subscribers
    • Already have a WordPress.com account? Log in now.
    • Programming Ideas With Jake
    • Subscribe Subscribed
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
 

Loading Comments...
 

    Design a site like this with WordPress.com
    Get started