Design Patterns: Chapter 1

Scholar and hymnwriter Caleb T. Winchester described a classic as “something that everybody wants to have read and nobody wants to read.” For me, the Design Patterns book, by Erich Gamma and the rest of the “Gang of Four,” is a prime example. As an object-oriented software developer, unless you want to repeat the mistakes of the uninformed, you want to have read this book. There’s a reason it’s in its 40th printing! But it’s a daunting volume, full of abstract ideas.

My excuse for not having read it yet is that my “day job” programming (XSLT, Python, Javascript) has never involved object-oriented languages much. Until recently. Now, as I’ve been getting more into Android development, I have to make decisions about OO design all the time. The only question is whether I’ll do it well, or poorly. And in the Android API documentation, certain classes are described based on design patterns and principles from DP. So, now that my excuse is gone, it’s time to pick up a shovel, take the plunge, and generally mix metaphors as we sink our teeth into this classic.

Chapter 1 Terminology

Chapter 1 does not make it easy. The terminology is abstract, especially because it’s not tied to any one OO programming language. Where examples of languages are given, the authors don’t mention Java (the book was published in 1995, the same year that Java 1.0 went public). Terms like interface and class are familiar from Java programming, yet they don’t always mean the same thing in the book as in Java. The main reason for this post is to write down some key things I’m learning about Design Patterns (DP) terminology.

interface: If there is any key word to the book, this is probably it. DP is famous for the principle “Program to an interface, not an implementation.” The book defines interface as follows: “The set of all signatures defined by an object’s operations is called the interface to the object.” OK, this gives a rough idea, but it gets more complicated than that.

In Java, there can be Interfaces (using the capital letter to distinguish Java usage from DP usage) that never represent “the set of all signatures defined by [any particular] object’s operations.” For example, an Interface might not (yet) be implemented by any object; or, maybe all the implementing objects also implement additional Interfaces. In DP, we soon read that an object may have many types, where a type is a name used to denote a particular interface. And that “Part of an object’s interface may be characterized by one type, and other parts by other types.” The only way I can make sense of that is if an interface can refer not only to the set of all signatures of an object’s operations, but also to any specified subset. So a more general definition for interface (in DP’s usage) might be “A set of [some, not necessarily all] signatures of operations that might be implemented by certain objects.” However, the interface of an object does seem to mean the set of all signatures of that object’s operations, even if that interface contains several other interfaces (“subsets” in DP). DP often leaves the distinction to context, so you have to keep your eye on the ball in order to understand which is meant.

The same is true of the word type. E.g. when DP says “[a] An object can have many types, and [b] objects of different classes can have the same type [italics added],” what does that mean? Does it mean that [a] The (entire) interface of an object can have many names, and [b] objects might be instances of classes that are all different implementations of the same interface and only that interface? Or does it mean that [a] An object can implement many different interfaces (each with its own name), and [b] objects might be instances of classes that share a common interface in addition to other possible operations?

Admittedly, in some cases it doesn’t matter. But sometimes it does. When we read,

When inheritance is used carefully … all classes derived from an abstract class will share its interface.

the sentences after this in the book make clear that the derived classes share the abstract class’s entire interface, but that interface is not necessarily the entirety of each derived class’s interface.

DP also doesn’t say explicitly whether every interface has a type (i.e. a name), or can have more than one (presumably it can). You could probably say, at least in Java, that every object has a type: the object is an instance of a class, which defines an interface, and you could use the name of the class as the name of the interface. Of course, not every Java class has an Interface: some classes will implement multiple Interfaces, and others, none. (But see below about the term type.)

There’s another nuance here: DP posits that “Objects are known only through their interfaces. There is no way to know anything about an object or to ask it to do anything without going through its interface” (emphasis mine). In Java, classes can have non-private variables, through which a program can get information from an object, or even, in some sense, ask it to do something. The foregoing principle implies, then, that non-private (instance) variables are part of an object’s interface, even though they are not operations. No doubt this is why people say that “all of your instance variables (a class’s nonconstant fields) should be private” — because the interface of an object should not expose implementation details. Doing so breaks encapsulation. (They also say that even accessor methods carry a similar risk… but that’s another topic all its own.) DP goes on to say “An object’s interface says nothing about its implementation…”, which confirms that Java non-private instance variables violate DP’s principles of interfaces.

On the other hand, the above statement “Objects are known only through their interfaces” clearly has exceptions. An obvious one is that an object may know about itself (e.g. about the contents of its variables) without going through its interface. A more subtle one is that an object inheriting from an ancestor often has privileged access to the ancestor’s non-public members (methods and variables). The latter issue comes up later as DP discusses inheritance vs. composition as means of defining one class’s implementation in terms of another’s. It’s pretty clear from this discussion that DP doesn’t consider privileged inheritance-based access to be part of the interface of the ancestor class.

operation: a procedure that an object defines; i.e. a method. Some sources draw the distinction that a method is an implementation of an operation, in a particular class. In analogy form, operation is to interface as method is to class. But DP doesn’t draw this distinction.

type: DP defines type specifically as “a name used to denote a particular interface.” However, later usage suggests that type is used interchangeably with interface, even when an interface’s name doesn’t seem to be in focus. For example,

Of course, there’s a close relationship between class and type. Because a class defines the operations an object can perform, it also defines the object’s type. [italics added]

The latter would be strange if type meant one of possibly many, or zero, names used to denote a particular interface. Continuing in the same paragraph,

When we say that an object is an instance of a class, we imply that the object supports the interface defined by the class.

Languages like C++ and Eiffel use classes to specify both an object’s type and its implementation. [italics added]

Again, the latter would be an odd thing to say if type means merely a name for an interface. It would make more sense if type here was a synonym for interface. One more example of that:

Any object can be replaced at run-time by another as long as it has the same type.

Clearly, what matters here is not the name of the objects’ interfaces, but the (relevant subsets of their) interfaces themselves. So from here on I’ll assume that type is often used synonymously with interface.

(object) composition: “assembling or composing objects to get more complex functionality.” One object obtains a reference to another and makes requests of it through its interface, rather than inheriting implementation via inheritance. Composition may take the form of aggregation or acquaintance.

aggregation: “implies that an object owns or has responsibility for another object. … Generally we speak of having or being part of another object. … Implies identical lifetimes.”

acquaintance: “implies than an object merely knows of another object. … called association or the using relationship.”

delegation: “a way of making composition as powerful for reuse as inheritance.” Object A receives a request, and forwards, or delegates, the request to object B. As such, this is “mere forwarding,” while “true delegation” implies that object A (the receiver of the request) passes a reference to itself to object B (the delegate). This way, the delegate has access to the interface of the receiver during processing of a request, as a parent classes’ inherited method would have access to the child caller object via the this pointer. I had to reread that last part a few times to get it right. In comparing delegation to inheritance, the receiver corresponds to the child, and the delegate, to the parent. Note that delegation is often used loosely to mean mere forwarding, in which the delegate has no access to the receiver.

One more caveat, on delegation terminology: The DP book uses receiving object and receiver to refer to the delegator, while some other sources, like Wikipedia, tend to use the same words to refer to the delegate. Of course it depends on which method call you’re thinking about receiving … the original request, or the delegation request. To avoid ambiguity, we could use delegator vs. delegate (some even call it delegatee).

“Program to an interface, not an implementation”

Don’t declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class.

This famous “principle of reusable object-oriented design” shows up in section 1.6. The reasons for doing so make sense. But is it practical? Wouldn’t this mean that for every concrete class you define, you’d have to define another, abstract version of it (or an Interface) … except for the cases where you have multiple concrete classes extending the same abstract class?

I think it depends greatly on what you’re developing, and the level of reuse you expect. As is often the case, the specters of YAGNI and premature optimization loom over one’s shoulder as one contemplates how to achieve optimal code reusability. In creating Android Activities, you’re mostly using classes from an API that have been designed for you; the actual code you’re writing will not be reused much. But once you start creating other classes to represent real-world things to be used by multiple Activities, encapsulation and code reuse become more important. And if you’re writing a publicly available library, or even designing the Android app libraries themselves, it makes a lot more sense to spend time separating implementation from interface. DP talks about this late in chapter 1… the differing needs for reusability in applications vs. libraries vs. frameworks.

“Relating Run-Time and Compile-Time Structures”

Trying to understand one from the other is like trying to understand the dynamism of living ecosystems from the static taxonomy of plants and animals, and vice versa.

I liked that quote. I might have expected them to say “is like trying to understand the dynamism of a living organism from the physical structure of its body.” But I suppose taxonomy arguably has a special resemblance to static code structures like inheritance.

Anyway, on to chapter 2!

Categories: Android, OOP, software development | Leave a comment

Sending a client certificate during SSL handshake in Java/Android

My current Android development assignment has me implementing an SSL connection to a server. There are lots of good blog posts and documentation out there about how to do this in Android, or Java in general. The scenario I’m working on is a bit less typical in that the client app has to send a certificate to authenticate itself to the server. It took me a fair bit of trial and error to figure out how to get it to work, so this is one of those posts that you write in case it helps somebody in a similar situation, possibly even your future self. 🙂

The Android docs give some guidance on this scenario, but unfortunately they don’t tell how to set up the KeyStore containing the client certificate:

KeyStore keyStore = ...;

I had trouble getting it set up. I tried creating an empty KeyStore, and generating a certificate to put in it from a raw resource PEM file:

CertificateFactory cf = CertificateFactory.getInstance("X.509");
// use cert from our raw resource client.pem
InputStream certInput = mContext.getResources().openRawResource(R.raw.client);
Certificate clientCert;
try {
    clientCert = cf.generateCertificate(certInput);
    Log.d(TAG, "client cert=" + ((X509Certificate) ca).getSubjectDN());
} finally {
    certInput.close();
}

String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
// Put the cert into the new, empty keystore.
keyStore.load(null, null); // initialize
keyStore.setCertificateEntry("client", clientCert);

But I got parse errors on the cf.generateCertificate() call, such as “error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag”. Apparently the certificate’s PEM file wasn’t in the right format. What was wrong? Was it using DER instead of BER? How can one tell?

Skipping over tedious details, what eventually worked for me was this. My colleague, our server admin, had given me the client certificate in both .pem and .p12 formats. I read here that Java keytool “can treat a PKCS12 file as a keystore.” So instead of creating an empty keystore and reading in a certificate from a raw resource in PEM format, I tried loading the keystore directly from a raw resource in PKCS12 (.p12) format. It worked! Here’s the code:

KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
// We have deleted the raw resource client.pem and added client.p12 instead.
InputStream certInput = mContext.getResources().openRawResource(R.raw.client);
keyStore.load(certInput, "mypassword".toCharArray());

And now we can continue with the code provided in the Android documentation:

// Create a KeyManager that uses our client cert
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(keyStore, null);

// Create an SSLContext that uses our TrustManager and our KeyManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

URL url = new URL("https://www.example.com/");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());

As for the “BC” provider in KeyStore.getInstance("PKCS12", "BC"), I confess I don’t know much about it. I copied it from some examples I found. “BC” likely stands for BouncyCastle, but how do we know what providers are available, and what provider you need? No idea. But it works in this case.

Categories: Android, Lars, SSL | 3 Comments

Photo credit

Thanks to Dad Huttar for the beautiful header photo. He and mom took this and other great photos during their visit here last month. Photo is of our oak canopy with the sun shining on the fall leaves at the top. Gorgeous.

Speaking of beautiful photos, I have discovered Gilbert Lennox Photography in recent months, thanks to his daughter, singer and modern hymnwriter, Kristyn Getty. (We love Keith and Kristyn’s music! You can purchase it in stores or at their website). Keith and Kristyn post some of Mr. Lennox’s photography on the Keith and Kristyn Getty Facebook page. We also really like Kristyn’s Uncle John Lennox who is a mathematician, philosopher, and Christian apologist. Check out his books! Our favorites include God’s Undertaker: Has Science Buried God? and God and Stephen Hawking: Whose Design Is It Anyway? This is a family talented and gifted by God.

Categories: Kate | Leave a comment

Exploring XPath 3.0 with BaseX

I don’t know about you, but I get excited reading papers like Dimitre Novatchev’s Programming in XPath 3.0, and want to try some of XPath 3.0’s new features for myself. I also want to build upon some of the examples given there.

But to do that, you need an XPath 3.0 processor. And it turns out, they’re harder to find than XPath 2.0 engines. (Not too surprising, since 3.0 is more complex, and has just reached official Recommendation status in the last 3 months.)

Saxon HE, the free version of the definitive XSLT/XQuery processor, does not do XPath 3.0. Saxon PE and EE do. They are not free (starting at £50.00 at the moment), though you can apply for a 30-day trial license. My trial license arrived pretty quickly today after I requested it. However that does put you under a time limit, and if you’re like me, picking up projects and putting them aside all the time, the clock may run out before you’re done experimenting.

XmlPrime is listed on the QT3 Test Suite Results Summary for XPath 3.0, so it sounds like it implements XPath 3.0, right? But the version of XmlPrime listed there is 3.0.0.0, whereas the most recent version that seems to have been released publicly is 2.9. And that version doesn’t claim to run XPath 3.0 or XQuery 3.0. So where do we get our hands on the version that does?

However I found out (via Dimitre) that BaseX includes XQuery 3.0, which should by definition include XPath 3.0. (Why then is BaseX not listed on the implementations of XPath 3.0 in the QT3 Test Suite Results Summary? It’s listed for XQuery 3.0… Hmm.)

If BaseX does run XPath 3.0 (and yes it does seem to… but see caveats below), it also has the advantages of (1) being free, and (2) having a GUI front-end that makes it easy to experiment with different queries. A minor disadvantage is that it seems a bit daunting to be installing a full-blown XML database server, if all you want is to try some XPath. But disk space is cheap, and honestly, my low-end laptop didn’t have trouble running BaseX along with several other applications. Moreover, it wasn’t complicated to set up and start evaluating XPath.

So here’s the procedure, as I did it.

  1. Download and install BaseX. I’m on Windows, so I used the Windows Installer (v. 7.9).
  2. Following the Getting Started instructions, launch the GUI. I didn’t have the installer create desktop icons, so I had to type basexgui.bat in the Windows 8.1 Start menu. Windows found the .bat file and launched the GUI successfully.
    Alternatively, you can use the command line or the client/server scenarios, but I think the GUI’s ideal for experimenting and development.
  3. You can’t (AFAIK…) run XPath (or XQuery) without having an input document. So, following the GUI instructions, create an XML database. This consists of specifying an XML document to connect to as the database.
    There’s a suggestion to use BaseX/etc/factbook.xml as a sample, which is a substantial one (1.25MB) and good for many cases; but if your use of XPath tends to ignore the input document (like most of Dimitre’s examples), you may want a tiny document like the included w3-catalog.xml.
    The document structure pane in the upper right shows a really cool representation of the XML tree, to which a tiny document does not do justice.
  4. Try out a simple XPath (or XQuery) expression in the “XQuery Panel.” To do this, click on the dropdown that says “Find” and change it to “XQuery.”Then enter an expression in the text field next to it. E.g. try one of these…
    • 5 + 6
    • count(//*) (: returns 4, for w3c-catalog.xml 🙂
    • /*/*[2]
    • let $i := 3 return $i

    You should be seeing the expected output in the Result pane (lower left quadrant). screen shot of BaseX

    You also get some nifty profiling information in the lower right pane.

  5. Now you want to try more sophisticated queries? Type/copy/paste your query into the Editor window (below the XQuery Panel on the left). You can also open your XPath/XQuery files using the file browser on the left side. Caution: if your query code filenames don’t match the default filters (*.xml and *.xq*), you may get frustrated trying to find them, even though the file browser says it’s showing “All Files”. First go to Options>Preferences, check General>Use Simple File Chooser, and add *.* to Editor>File Filter. After I did that, I was able to find my files.Press Ctrl+Enter, or hit the green play button, to run your example. Again, the results appear in the Result pane below the Editor.

So now we’ve achieved our goal: a working XPath 3.0 processor. Right?

Basically, yes. I had trouble running some of Dimitre’s examples, e.g. when declaring recursive functions. I seemed to get an error whenever a function parameter was declared as function() without declaring the return type of the passed function. I’ll probably submit a StackOverflow question about that. But other examples worked well, e.g. using the simple mapping operator:

('London', 'New York', 'Paris') ! string-length()

or creating elements in XPath:

name(parse-xml(concat('<Person>', (//Author)[last()], '</Person>'))/*)

The examples on closures and partial application also worked fine.

Update: The spec has apparently changed for declaration of general function types. You have to declare them as function(*) rather than just function().

Categories: Lars, xpath | 1 Comment

Happy International Tatting Day!

Getting ready to celebrate with many tatting friends in the Online Tatting Class! Join us in tatting today.

IMG_3188

Info on tatting and International Tatting Day:

http://www.gone-ta-pott.com/international_tatting_day.html

http://www.altiusdirectory.com/Society/international-tatting-day.html

Categories: Kate | Tags: | Leave a comment

Yogurt success!

A few years ago I tried my hand at making yogurt. The first few times I met with great success. Then suddenly I had two or three tries that ended with a crock pot of whey with about a half inch of yogurt. 🙁 Thankfully, the whey was great in smoothies and soups and other things, but it wasn’t yogurt. But I gave up on making my own yogurt.

Have you noticed, however, that dairy prices are skyrocketing? The basic milk at the grocery store is $4 a gallon. And yogurt is also pricey, especially Greek yogurt. So when I found milk on clearance, I thought it was time to give yogurt making a go.

Time to search for a recipe again, and preferably a different one since my last attempts had failed. (I do think a lot of that may be due to a crock pot that heated too hot and too fast.)

I found a new recipe that advertised “fool-proof crock pot yogurt.” After my failed attempts, I was a bit skeptical, but thought I would try since the blog author said if you follow the directions precisely, it would work. Yesterday I began the process. I was surprised how long the milk took to heat up. Over five hours to reach 185F. Then it took another 3.5 hours to drop back to the ideal temp of 110F for adding in the starter and sticking it all in the oven.

The results were well worth the extra vigilance. It worked! This morning I had beautiful, creamy, white yogurt. Just had a bowl with a spoon of honey and it was delicious. One jar of it is already gone after all of us snacking on it. 🙂

Unfortunately, I was so excited to scoop out the thick yogurt, that I didn’t think of taking a photo, but I will take a photo of it in the jar and spoon and post it.

I am giving credit of the success to the blog author, “Granny Miller”! And the failure, at least in part, to the crock pot I used before. I did have to adjust the recipe a bit because I used my smaller crock pot, since I don’t trust the big one which failed me.

I am once again a happy yogurt maker!

Categories: Kate | Tags: | Comments Off on Yogurt success!

Book a month in 2014

Today I ran across this blog post which challenged me to come up with a non-fiction book list of my own for 2014. The blogger has some great books from last year as well as this year. When I first saw the post, I thought, “That should be easy, I read a lot of books in 2013.” Then I looked at my actual list of read books and realized that I had only finished reading 8 non-fiction books in 2013. 🙁 Granted, there are a lot of books in progress in the non-fiction category, but I did not finish them as I had hoped. So, here is the current list of books for 2014.

First the ones that I have started and need to finish (which is most of them):

  • A Mother’s Heart by Jean Fleming
  • A Place of Quiet Rest by Nancy Leigh DeMoss
  • Choosing Gratitude by Nancy Leigh DeMoss
  • Heaven by Randy Alcorn
  • Radical Womanhood by Carolyn McCulley
  • Streams in the Desert by L.B.E Cowman
  • The Bondage Breaker by Neil T. Anderson
  • The Core by Leigh A Bortins
  • The Mom Walk by Sally Clarkson

And the ones I would like to read this year:

  • The Quest for Meekness and Quietness of Spirit by Matthew Henry
  • Shepherding a Child’s Heart by Tedd Tripp
  • The Mission-Minded Family by Ann Dunagan
  • Instructing a Child’s Heart by Tedd and Margy Tripp
  • What Happens When Women Pray by Evelyn Christenson
  • How to be a Christian in a Brave New World by Joni Eareckson Tada
  • Angel Tracks in the Snow by Gary Sheperd
  • Bringing Up Girls by James Dobson
  • John and Betty Stam by Mrs. Howard Taylor

Yes, I realize this is more than 12. I couldn’t narrow it down more than that at the moment. 🙂 And many of them I am well into, so they only count as half, right? I also hope to sneak in during the summer:

  • Bonhoeffer by Eric Metaxas
  • The Question by Leigh Bortins
  • and a few others 🙂

One can dream, right? No, this is a plan, not just a dream.

I’ll update as I have read them. What are you reading this year?

 

20140106-223842.jpg

Categories: Kate | Tags: , | 2 Comments

In everything give thanks

IMG_1591

Crowders Mountain State Park with Grandma and Grandpa Huttar

Blessed Thanksgiving to each of you!

We are so grateful for our family, our friends, and most of all our Lord and Savior, Jesus Christ!

The Huttars

Categories: Kate | Tags: | Comments Off on In everything give thanks

Welcome, www.huttar.net!

IMG_5616

Field trip to the Schiele Museum in Gastonia, NC

IMG_5667

In front of the gristmill at the Schiele Museum

We finally updated our website to forward everyone here to our blog until we can rebuild our website. The website has been mostly broken for months. Sorry to those who have gone to our web address and found an

outdated photo and not much else.

We will try to get more up there in coming months, but until then, we will post some updates here, as well as a few photos now and then.

For starters here are some photos of the girls on a field trip with our CC community, and a few funny faces by Baby beans.

IMG_5602

Full of silly faces

Categories: Classical Conversations, Huttar Academy, Kate | Tags: , | Comments Off on Welcome, www.huttar.net!

Birth of Dogwood Designs

IMG_5814Last weekend we participated in our first Craft Show. It was a small one that a friend had organized near our home. Seemed a long shot that we would be able to find enough to show, but in the end we decided to go for it. I made some crocheted items, the older girls made potholders/coasters and scarves. Also on display were some lovely lip balms and lotion bars.IMG_5821

The night before the show, as I was working on tagging all the items, I was trying to design labels for things and Lars suggested “dogwood” being in the name. So we found clip art of a dogwood flower and thus, Dogwood Designs was born. We figure that it will work well for our crafting: crochet, tatting, weaving, woodworking; as well as Lars’s web app work. Perfect.IMG_5825

More on Dogwood Designs and photos in future posts. Maybe we will even get an Etsy store set up someday!

PS: Having done a web search, I see several other “Dogwood Designs.” Hmmm…not too surprising, but we will have to see if we can make it original. Any suggestions?

Categories: Kate | Tags: | 2 Comments