- Nick Burns, Client Object: (impatient) You're the Customer object, right? Tell me the average number of purchases per month, year-to-date.
- Customer Object: (confused) Er...but...I don't have a method for doing that. I know the customer inside and out, but you're asking for statistics about the orders. I suppose I have the ability to fetch all customer purchases for a time range...
- Client Object: (annoyed) Don't know much, do you? Give me all your data and MOVE! The Client Object .gets() all the information from the Customer Object, filters it, and finally calculates. THERE! Was that so hard?
- Customer Object: (defensive) Well, if someone had given me the capability to do what you were asking, or if you had gone to the right Object in the first place...
- Client Object: (dismissive) Don't worry about it. You're just one more do-nothing data container like all the objects in the hierarchy. I'm here to do your thinking for you. The Client Object starts to return to its caller, then hesitates and turns back to the Customer Object for one last bit of sarcasm. Oh, by the way, you're welcome!
Showing posts with label Software development techniques. Show all posts
Showing posts with label Software development techniques. Show all posts
Thursday, June 28, 2012
Nick Burns the Client Object
In 2009 I compared a lack of data encapsulation to a nudist community. Not long ago another metaphor struck me, but this one applies to the interactions among objects within that anti-pattern: Nick Burns, Your Company's Computer Guy. If translated to the form of skit dialogue, it might be like the following.
Thursday, February 24, 2011
reactions to unit test failures
I suspect that deepest dedication to a suite of automated unit tests isn't proven by having a test that touches each public class. Nor by a test for each public method. Nor by a test coverage tool that reports a proportion as close to 100% as is reasonable for that codebase. Nor even by strict test-first methodology.
The deepest dedication is only proven later in the code's life, when changes happen. Code changes of significance should lead to test failure or stark test compilation (or interpreter-parse) failure. That moment is when dedication takes effect. What will be the programmer's reaction? If it's a tiny test that broke, then a rapid and focused adjustment to the test or the code is likely to be the happy outcome. (Sidebar: this argues for not skipping trivial tests that probably are redundant to big tests. A failing trivial test is easier to interpret than a failing big test!) If it's a complex test or a large subset of tests that failed, then the reaction might not be as, er, placid.
The deepest dedication is only proven later in the code's life, when changes happen. Code changes of significance should lead to test failure or stark test compilation (or interpreter-parse) failure. That moment is when dedication takes effect. What will be the programmer's reaction? If it's a tiny test that broke, then a rapid and focused adjustment to the test or the code is likely to be the happy outcome. (Sidebar: this argues for not skipping trivial tests that probably are redundant to big tests. A failing trivial test is easier to interpret than a failing big test!) If it's a complex test or a large subset of tests that failed, then the reaction might not be as, er, placid.
- The worst reaction is to impulsively eliminate the failing test(s). Better but not by much is to turn the test(s) into comments or otherwise force a skip. A disabled/skipped test is always a temporary measure of compromise to reduce mental clutter during the thick of an intense task. It carries an implicit promise to enable the test at the next possible opportunity. Excessive distracting nagging is awful but permanently removing a safety net clearly falls into the "cure worse than disease" category.
- Assuming the motivation for the code change was a real change in requirements rather than code refactoring and improvement, then direct elimination may be correct. Before doing so, remember that unit tests act like executable specifications for that unit, and ask yourself "Does this test correspond to a code specification that still applies to the changed code but in a different form?" When the answer is "yes", the test should be replaced with a corresponding test for the transformed specification. Consider previous tests that caught corner cases and boundary conditions. If an object previously contained a singular member, but due to changes in the problem domain it now contains a collection, then the test for handling a NullObject singular member might correspond to a replacement test for an empty member collection.
- On the other hand, whenever the change's purpose is to improve the code while leaving intact all existing functions/interfaces of importance, elimination or fundamental rewrites aren't the right course. The test stays, regardless of its inconvenience in pointing out the shortcomings of the redesign. The right answer may be to rethink part of the code redesign or in a pinch to add on to it in some small way with some unfortunate adapter code until other modules finish migrating. Sometimes a big fat legitimate test failure is the endpoint and "smoking gun" of an evolutionary mistake of the code, and the professional reaction is to disregard personal/emotional attachment by cutting off or reshaping the naive changes. Never forget that to users the code is a semi-mysterious black box that fills specific needs. Sacrificing its essential features (rather than unused feature bloat) is too high a price for code that's more gorgeous to programmers. Granted, skillful negotiators can counter by pledging sophisticated future features that the redesigned code will support, in which case the pledges must turn out to be more than vaporware for the trick to ever work again.
- With any luck, the ramifications are not so dire. A confusing unit test failure may not be a subtle lesson for the design; it may be nothing more than a lesson to write more (small) tests and/or test assertions. It seems counterintuitive to throw tests at failing tests, yet it makes a lot of sense given that tests are coded expectations. In effect, confront the failing test by asking "What did I expect?" immediately followed by "Why did I expect that?" Expectations build on simpler expectations. Attack the expectation in top-down step-wise analysis. The expected final outcome was 108, because the expected penultimate outcome was 23, because the expected count was 69, etc. Write tests for those other, lesser expectations. Now the tests narrow down the problem for you at the earliest point of error, as if being an automatic debugger with predefined breakpoints and watch-expressions.
- It's a well-known recommendation to write an additional unit test for a bug discovered "in the wild". This test confirms that the bug is fixed and then reconfirms that the bug doesn't resurface, assuming frequent runs of the entire suite. After a few unsuccessful tries at passing this novel test, don't be too rigid in your thought habits to ponder the possibility that the untested test is buggy! In the prior items my encouragement was to not react by blaming the tests, since an unmodified test that passed before a code change and fails afterward logically indicates that what changed, i.e. the code, must be to blame. Philosophically man is the measure of all things and a unit's tests are the measure of the unit. Not so during the introduction of a test. At this special time, the test isn't a fixed ruler for measuring code errors. It's its own work in progress in a co-dependent relationship with the code it measures. Initially the code and the test are at danger of dragging the other down through bugs. A buggy test is a false premise that can lead to a false conclusion of fine code that appears to be buggy or worse buggy code that appears to be fine. Be careful to write tests as minimal, unassuming, and straightforward as is practical. Complex tests that check for complex behavior are acceptable (and hugely important!). Complex tests that are intended to check for simple behavior are less justifiable and trustworthy. Tests are miniature software projects. The more convoluted and intricate and lengthy a test becomes, the greater opportunity for bugs to sneak in and set up shop.
Thursday, February 17, 2011
information hiding applied to generic types
Over time, I have a growing preference for the term information hiding over encapsulation. Encapsulation communicates the idea of wrapping data in an object or protecting privileged access through managed methods. But design analysis shouldn't stop there. Information and/or knowledge can leak and spread through a design in more subtle ways. For instance, I previously wrote that the HTML page's DOM is an overlooked example of shared state in Javascript. When many code pieces, each meant to serve separate and independent goals, have accidental dependencies outside themselves, both code reuse and intelligibility suffer. A part can no longer be understood without understanding the whole.
The purpose of information hiding, interpreted in a more general sense than encapsulation, is to thwart the natural tendency for code to not only collaborate but conjoin into the dreaded big ball of mud. Information hiding preserves metaphorical distance between expert objects with well-defined responsibilities. Then whenever a question arises, there's one answer and that one answer comes from the expert. The opposite outcome is several answers, found by wandering through the system, and one can never be quite certain that all the right generalists have been duly consulted and cross-checked.
Generic types may be susceptible to violations of information hiding. For in order to concretely consume a class with a generic type parameter, the type for the parameter must be specified (of course). But the conscientious designer should frankly ask whether the type parameter information belongs in the consuming class. By including it, the consuming class must either be coupled to a type-specific instance of the generic class or itself become a generic class that requires and passes on the same type parameter. The first option makes the consuming class less reusable/flexible while the second option leads to greater implementation complexity and further propagation of the type parameter information.
The third option is to hide the generic type information from the consuming class altogether. Some possibilities:
The purpose of information hiding, interpreted in a more general sense than encapsulation, is to thwart the natural tendency for code to not only collaborate but conjoin into the dreaded big ball of mud. Information hiding preserves metaphorical distance between expert objects with well-defined responsibilities. Then whenever a question arises, there's one answer and that one answer comes from the expert. The opposite outcome is several answers, found by wandering through the system, and one can never be quite certain that all the right generalists have been duly consulted and cross-checked.
Generic types may be susceptible to violations of information hiding. For in order to concretely consume a class with a generic type parameter, the type for the parameter must be specified (of course). But the conscientious designer should frankly ask whether the type parameter information belongs in the consuming class. By including it, the consuming class must either be coupled to a type-specific instance of the generic class or itself become a generic class that requires and passes on the same type parameter. The first option makes the consuming class less reusable/flexible while the second option leads to greater implementation complexity and further propagation of the type parameter information.
The third option is to hide the generic type information from the consuming class altogether. Some possibilities:
- Have the generic class implement a minimal non-generic interface. Then couple the consumer class to this interface. Creating/obtaining new instances of the generic class for the interface would happen through a separate factory/service locator/dependency injector.
- If the generic class is part of an inheritance hierarchy, then move the non-generic portions into a superclass. It's permissible for a non-generic superclass to have generic subclasses. Now the consuming class can work with instances of the generic subclasses by typing them at the non-generic superclass level.
- Assuming the generic class doesn't have generically typed state, consider making the class non-generic with some methods that are generic only when necessary. In such situations the compiler probably can infer the methods' type parameter based on which types the consuming class passes to the methods, so not even calls to the remaining generic methods need to have the complexity of "looking generic".
Sunday, November 07, 2010
shared state is not hard to find in Javascript
...and it's called "DOM" (the webpage Document Object Model). State is shared between pieces of code whenever all the pieces may read and write to it, and that applies to the DOM. No declarations are necessary; neither reads nor writes require express permission or coordination. In this freewheeling land known as the "document", anything is up for grabs.
Yet why does it matter, given that dynamic changes to the DOM are a huge part of Javascript's appeal? It matters because any shared state, by its nature, can lead to problems for the unwary, especially as size and complexity grow.
- If various Javascript functions touch the DOM, then those functions may cease working properly whenever the page changes structure. One change, no matter how trivial, has the potential to mess up code in several places at once. For instance, say that two tabs switch order...
- Similarly, whenever there's an algorithmic adjustment, all the functions that affect relevant individual parts of the DOM must be spotted and redone. Rounding and displaying four decimal places, but only in inputs for numerical data of a particular category, means code changes for everywhere that those input values are set or read.
- My impression from some blogs is that people are feeling skeptical about the actual prospect of code reuse in many circumstances, but it's still a worthy ideal. As always shared state is a hindrance to reusability simply because it isn't parameterized. A function that includes an instruction to remove a style class from the element of id "last_name" is pretty difficult to reuse elsewhere.
- On the other hand, shared state opens up the possibility of no-hassle collaboration. Function A (assuming a better name!) can take on the responsibility of setting up the shared state in some way. Then function B can do some other task to the shared state, any time after A has recently run. But function C can run directly after either A or B. So function A must leave the shared state in acceptable configurations for either B or C, and B must also account for C. Of course, if there's a new special data value in the shared state that affects what C must do, one must be careful to modify both A and B to set it accordingly. Hence, although shared state makes it highly convenient to intertwine the operation of many pieces of code, the intertwining also greatly reduces readability! It's much easier to analyze separate pieces of code with well-defined connection points.
- Furthermore, implicit shared-state dependencies don't combine well with asynchronous execution. Javascript doesn't have concurrent execution (i.e. multithreading), but it's certainly possible for separate pieces of code, such as callbacks for clicks and timers and network requests, to execute in an unpredictable order. So while there won't be deadlocks in the traditional sense, unwitting callbacks that fire in an unintended sequence could leave the DOM in a useless or false form after the dust clears.
Many techniques could apply to mitigation of the shared state known as DOM. For information storage, rely on variables residing in purposeful scopes rather than DOM elements and/or attributes. Treat the DOM as an end, instead of intermediate, data format. Isolate the code that handles the DOM from the code that processes data. DOM modifications that always happen together should be collected into a single function with an appropriate abstract/semantic name.
Not all of the shared state in an application consists of variables. Whether log file, database, or DOM, access logic should be carefully considered to avoid maintenance headaches.
Not all of the shared state in an application consists of variables. Whether log file, database, or DOM, access logic should be carefully considered to avoid maintenance headaches.
Wednesday, July 14, 2010
persistence of private by the Nucleus pattern
The encapsulation of data by an object's methods is one of the foremost goals of effective OOP. Restricting exposure of the object's private information prevents other code from accessing it. The inaccessibility ensures that the other code can't depend upon or otherwise share responsibility for the private information. Each object has a single responsibility: a sovereign private realm of information and expertise.
However, this ideal conflicts with the reality of the need to give objects persistence because most programs require data storage in some form. And the required interaction with the storage mechanism clearly isn't the responsibility of the objects that happen to correspond to the data. Yet how can the objects responsible, often known as repositories or data mappers, mediate between external storage and other objects while obeying encapsulation? How can information be both private and persistent without the object itself assuming data storage responsibility?
The "Nucleus" design pattern, very similar to an Active Record, addresses this issue. According to the pattern, a persistent object, similar to a eukaryotic cell, contains a private inner object that acts as its "nucleus". The nucleus object's responsibilities are to hold and facilitate access to the persistent data of the object. Therefore its methods likely consist of nothing more than public "getters and setters" for the data properties (and possibly other methods that merely make the getters and setters more convenient), and one of its constructors has no parameters. It's a DTO or VO. It isn't normally present outside of its containing object since it has no meaningful behavior. Since the nucleus object is private, outside objects affect it only indirectly through the execution of the containing object's set of appropriate information-encapsulating methods. The containing object essentially uses the nucleus object as its own data storage mechanism. The nucleus is the "seed" of the object that contains no more and no less than all the data necessary to exactly replicate the object.
Naturally, this increase in complexity affects the factory object responsible for assembly. It must initialize the nucleus object, whether based on defaults in the case of a new entity, or an external query performed by the storage-handling object in the case of a continuing entity. Then it must pass the nucleus object to the containing object's constructor. Finally, it takes a pair of weak references to the containing object and nucleus object and "registers" them with the relevant stateful storage-handling object that's embedded in the execution context.
The object pair registration is important. Later, when any code requests the storage-handling object to transfer the state of the containing object to external storage, the storage-handling object can refer to the registration list to match the containing object up to the nucleus object and call the public property methods on the nucleus object to determine what data values to really transfer.
Pro:
However, this ideal conflicts with the reality of the need to give objects persistence because most programs require data storage in some form. And the required interaction with the storage mechanism clearly isn't the responsibility of the objects that happen to correspond to the data. Yet how can the objects responsible, often known as repositories or data mappers, mediate between external storage and other objects while obeying encapsulation? How can information be both private and persistent without the object itself assuming data storage responsibility?
The "Nucleus" design pattern, very similar to an Active Record, addresses this issue. According to the pattern, a persistent object, similar to a eukaryotic cell, contains a private inner object that acts as its "nucleus". The nucleus object's responsibilities are to hold and facilitate access to the persistent data of the object. Therefore its methods likely consist of nothing more than public "getters and setters" for the data properties (and possibly other methods that merely make the getters and setters more convenient), and one of its constructors has no parameters. It's a DTO or VO. It isn't normally present outside of its containing object since it has no meaningful behavior. Since the nucleus object is private, outside objects affect it only indirectly through the execution of the containing object's set of appropriate information-encapsulating methods. The containing object essentially uses the nucleus object as its own data storage mechanism. The nucleus is the "seed" of the object that contains no more and no less than all the data necessary to exactly replicate the object.
Naturally, this increase in complexity affects the factory object responsible for assembly. It must initialize the nucleus object, whether based on defaults in the case of a new entity, or an external query performed by the storage-handling object in the case of a continuing entity. Then it must pass the nucleus object to the containing object's constructor. Finally, it takes a pair of weak references to the containing object and nucleus object and "registers" them with the relevant stateful storage-handling object that's embedded in the execution context.
The object pair registration is important. Later, when any code requests the storage-handling object to transfer the state of the containing object to external storage, the storage-handling object can refer to the registration list to match the containing object up to the nucleus object and call the public property methods on the nucleus object to determine what data values to really transfer.
Pro:
- The containing object doesn't contain public methods to get or set any private data of its responsibility.
- The containing object has no responsibility for interactions with external storage. It only handles the nucleus object.
- Since the nucleus object's responsibility is a bridge between external storage and the containing object, design compromises for the sake of the external storage implementation (e.g. a specific superclass?) are easier to accommodate without muddying the design and publicly-accessible "face" of the containing object.
- The nucleus object is one additional object/class for each persistent original object/class that uses the pattern. It's closely tied to the containing object, its factory object, and its storage-handling object.
- The original object must replace persistent data variable members with a private nucleus object member, and the containing object's methods must instead access persistent data values through the nucleus object's properties.
- The containing object's constructors must have a nucleus object parameter.
- The factory must construct the nucleus object, pass it to the containing object's constructor, and pass along weak references to the storage-handling object.
- The storage-handling object must maintain one or more lists of pairs of weak references to containing objects and nucleus objects. It also must use these lists whenever any code requests a storage task.
- The code in the storage-handling object must change to handle the nucleus object instead of the original object.
Friday, June 25, 2010
watch out for a rebase of a merge
So, a while back I tried to publish some detailed foolproof instructions for using named branches and hgsubversion. I've been using Mercurial as a Subversion client for a little while now, and I figured that if I posted my discoveries and practices then others with an Internet connection could benefit as well. After revising the post multiple times, I finally decided to pull it (HA!) from the blog because it clearly wasn't as foolproof as anticipated - as proven by the mishaps of this fool, anyway. At this point I redirect you to the Stack Overflow question "How to handle merges with hgsubversion?" and parrot the advice there: don't bother trying to reconcile named branches to Subversion! To fork development, clone the repository instead.
(Normally, my personal inclination is toward branches since clones feel like a hack solution. Given that I'm doing the right thing by using a VCS, why should I need to have separate directories for separate lines of development? It's true that environment variables or symbolic links make switching between the two directories fairly easy, but having to do those manipulations outside the VCS then feels like a hack of a hack. More and more frequently I wonder whether I'll settle on git, which has its own well-known set of warts, in the end.)
One of the primary shatter-points of my confidence was a rebase of a merge. This is the situation in which the default branch was merged into the other branch in the past, and the time arrives to rebase the other branch onto the default branch. (During work on a branch that will be ended by a rebase, the better course of action would have been to update it by a rebase onto default with --keepbranches rather than merging in the default branch.) The root problem is that a merge duplicates changes on the default branch by re-applying to the other branch, so to rebase this merge is to attempt to apply the default branch's past state to its present state, although the default branch may have changed in numerous ways after that merge!
As you might expect, a rebase of a merge often produces conflicts, and the likely desired resolution is to choose the version in the tip of the destination branch, "local" or "parent1". I can only write "likely" because, as usual with conflict resolution, only the developer's judgment can determine the right mixture whenever significant feature changes are involved in the conflict too.
While all these conflicts can be irritating, hair-pulling may be a more proper response to the instances of no conflict; Mercurial dutifully sends one or more files in the default branch backward in time without comment. I know of two causes of this behavior. 1. After the merge from default into other, a later change in default undoes one of the merged changes, and through the rebase of the merge the undoing is undone (reviving the original mistaken change). 2. After the merge from default into other adds a new file, a later change in default modifies the added file, and through the rebase of the merge the added file's later modifications vanish.
Therefore, after a rebase, it's a good idea to run a diff --stat in the range of the default's tip before the rebase and default's tip after the rebase. And for any of the unexpected changes that have no relevance to the feature just rebased, revert those files to the version of the default tip before the rebase and check in. Constant vigilance!
(Normally, my personal inclination is toward branches since clones feel like a hack solution. Given that I'm doing the right thing by using a VCS, why should I need to have separate directories for separate lines of development? It's true that environment variables or symbolic links make switching between the two directories fairly easy, but having to do those manipulations outside the VCS then feels like a hack of a hack. More and more frequently I wonder whether I'll settle on git, which has its own well-known set of warts, in the end.)
One of the primary shatter-points of my confidence was a rebase of a merge. This is the situation in which the default branch was merged into the other branch in the past, and the time arrives to rebase the other branch onto the default branch. (During work on a branch that will be ended by a rebase, the better course of action would have been to update it by a rebase onto default with --keepbranches rather than merging in the default branch.) The root problem is that a merge duplicates changes on the default branch by re-applying to the other branch, so to rebase this merge is to attempt to apply the default branch's past state to its present state, although the default branch may have changed in numerous ways after that merge!
As you might expect, a rebase of a merge often produces conflicts, and the likely desired resolution is to choose the version in the tip of the destination branch, "local" or "parent1". I can only write "likely" because, as usual with conflict resolution, only the developer's judgment can determine the right mixture whenever significant feature changes are involved in the conflict too.
While all these conflicts can be irritating, hair-pulling may be a more proper response to the instances of no conflict; Mercurial dutifully sends one or more files in the default branch backward in time without comment. I know of two causes of this behavior. 1. After the merge from default into other, a later change in default undoes one of the merged changes, and through the rebase of the merge the undoing is undone (reviving the original mistaken change). 2. After the merge from default into other adds a new file, a later change in default modifies the added file, and through the rebase of the merge the added file's later modifications vanish.
Therefore, after a rebase, it's a good idea to run a diff --stat in the range of the default's tip before the rebase and default's tip after the rebase. And for any of the unexpected changes that have no relevance to the feature just rebased, revert those files to the version of the default tip before the rebase and check in. Constant vigilance!
Wednesday, June 09, 2010
DDD and intrinsic vs. extrinsic identity
Ask someone for an introduction to domain-driven design, and it will likely include descriptions of "the suggested building blocks". Two of the blocks are known as entities and value objects. The distinction between these two may appear to be pointless and obscure at first, but it's invaluable to a clearheaded and thoughtful model.
The difference turns on the meaning of identity, which philosophers have long pondered and debated, especially in regard to individual humans (i.e. the question "Who am I really?"). The answers fall into two rough categories: intrinsic and extrinsic. Unsurprisingly, the dividing-line can be fuzzy.
The difference turns on the meaning of identity, which philosophers have long pondered and debated, especially in regard to individual humans (i.e. the question "Who am I really?"). The answers fall into two rough categories: intrinsic and extrinsic. Unsurprisingly, the dividing-line can be fuzzy.
- In the extrinsic category, a thing's identity is tied to sensations and ideas about that thing. This would be like identifying my phone by its shape, color, model, and so on. Based on extrinsic identity, if any of these "extrinsic" propositions about my phone ceased to be true, my phone would therefore no longer have the same identity. The phone would not only appear but be a different phone. Its identity is dependent. When someone meets a new acquaintance, his or her identity is generally rather extrinsic. "I don't know this person, but his name is Fred and he works in Human Resources."
- The opposite of extrinsic identity is intrinsic identity, which is independent of sensations and ideas about a thing. A thing with intrinsic identity "wears" sensations and ideas but is "itself" regardless. This would be like disassembling my precious phone piece by piece and then continuing to call the pile of pieces my phone. Transformations of all kinds don't change intrinsic identity. When someone has maintained a long-term connection to another person, his or her identity is generally rather intrinsic. "She's changed her residence, weight, politics, and career over the last several years, but she's still Betty to me."
- If the object's identity consists of a particular combination of attributes, then its identity is extrinsic. Two objects of the class with identical attribute values are indistinguishable (for the purpose of the domain). These are known as value objects. Each instance is a "value" similar to a number or a string of characters. Since extrinsic identity is by definition fully dependent on a thing's parts, a value object never changes. But someone often creates a new value object using the attribute values of preexisting value objects. This is just like adding two numbers to yield a third number. Modelers and developers can exploit the unalterable nature of value objects for various advantages, such as avoiding the need for storage. Possibly, there could be a highly reusable "mathematics" of the value object in which all methods are "operations" that 1) operate on and return value objects and 2) are completely stateless (free of side effects).
- Instead, a domain object's identity could be persistent throughout arbitrary transformations, which indicates intrinsic identity. Instances of the class probably have vital "history" and might not represent the same physical domain item despite identical or near-identical attribute values. These are known as entities. Normally a nontrivial entity will aggregate one or more value objects but along with a mechanism of unique identification. That mechanism could be a GUID or something else as long as no two instances can contain the same identifier by accident. Unlike value objects, (long-lived) entities change and correspond more directly to physical domain items, so a storage strategy for the entity and its associated value objects is necessary. (The advice of DDD is to keep the entities' code as purely domain-driven as possible by abstracting the storage details in a repository object.)
Monday, May 17, 2010
DDD and pragmatism
The human brain can forge the unlikeliest of connections between disparate concepts. Domain-driven design (DDD) is a software development perspective which is described in a book and a website. Pragmatist philosophy answers fundamental questions about human existence through a framework which is described among other sources in a book of writings by William James (here I'll refer to it simply as "pragmatism" although the more accurate term is probably "Jamesian philosophy" as a whole). These two strands of thought resonate with one another in a few ways. Apologies up-front if I massacre either in my descriptions.
- DDD insists at all times on a domain model that matches up with how the code really executes. For instance, it advises 1) using the same domain language from analysis to design to code (i.e. "ubiquitous"), 2) unifying analysis and coding to prevent the accidental creation of impractical designs, and 3) starting out any refactoring by first inferring all the current domain models and contexts and the mappings in-between. In pragmatism, statements are also put into effectual, practical terms. A statement that has no consequences has no grounds for consideration. A pragmatic philosopher approaches a statement by asking, "If this statement were true, then what difference would it make, either to my experiences or to my actions?" Just as a domain model that isn't reflected in the code is worse than no model at all, a statement that posits an utterly immaterial idea is a waste of philosophers' time.
- Early on, DDD raises a crucial distinction between a domain model's truth and its usefulness. It's neither required nor recommended that the model be an exact replica of the domain. The model's purpose is to adequately cut through the complexity of the domain such that all participants, user and analyst and developer and code, can accomplish the work effectively. A model is one particular organizational scheme that cleanly breaks up the problem along natural contours, which is why the appropriate model for a domain depends on whatever problem is to be solved. Meanwhile pragmatism also distinguishes between truth and usefulness but by redefining truth as something known-as usefulness. That is, truth itself is a process. It's obtained neither by mere abstract logical argumentation nor by mere sense experiences but by the actions and decisions and reactions of people upon the reality kaleidoscope. As DDD practitioners select a domain model according to their needs based on relevant criteria and data, pragmatists select the truth of all statements based on a range of needs and constraints that are objective or subjective.
- In DDD, people "crunch knowledge". The software specialists learn from the domain specialists and attempt to summarize the salient factors and operations into a domain model of ordinary-named objects that "makes sense" and facilitates meaningful communication about the software. But everyone involved should recognize that the model will change. Whether the cause is a significant disruption within the domain, a realization that the model isn't suitable for implementation due to technological constraints, or a deeper level of understanding, successive pieces of knowledge are crunched into the model and ideally result in a breakthrough to the software applying greater power, simplicity, and/or flexibility to the problems of the domain. Therefore the sign of the domain model's maturity isn't eternal perfection; it's the model's suppleness, which is its relative ease of accommodating further improvements. This notion of continuous, ongoing improvement is reminiscent of pragmatism's preference for evolutionary truth. Pragmatic truth isn't found in universal conclusions reached by closeted skeptics. It's built bit by bit as people tango with realities (whether those realities happen to be "outside" or "inside" one's self). This theory of truth is "dirtier" and less "ambitious" than the confident pronouncements made by philosophies that presume that Truth stands alone. However, the total mound of individual pragmatically-obtained truths is arguably much more reflective of the reality in which humans actually live. A straw man of pragmatism is that it asserts that "all of reality is whatever someone likes it to be". However, this argument ignores the stepwise accumulation of knowledge portrayed by pragmatists. It should go without saying that it's not pragmatic at all to disregard the entirety of one's prior discoveries in one swell foop by a disembodied leap of one's imagination. "I reject your reality and substitute my own" is certainly allowable (where would we be if we never tried to falsify predominant hypotheses?) but only to the limited degree that the individual judges and then decides it to be sensible and rational in the present case.
- When I first read about DDD, the extent to which it emphasizes communication took me by surprise. DDD repeats the importance of communication throughout, whether from customer to analyst, modeler to developer, module-team to module-team. One of the justifications behind having a communal domain model is to "anchor" everyone's language to the same meanings. Otherwise, like when there are separate models for the purposes of analysis and implementation, potentially useful information and feedback won't flow as well and people must expend effort on translation rather than forcing the domain model into an understandable shape that intimately connects the software to the domain experts' expectations. The ideal code-to-model connection is so close that the unit tests for the domain objects are largely intelligible to the domain experts who know the model and the context. (This does NOT mean that ALL code objects in the functioning system need to be known by the domain experts. Proper layering, perhaps using techniques like dependency injection to transparently and loosely connect layers, should at least partially eliminate the need for someone to know the "gory details" to comprehend the domain layer.) The model objects are commonly-acknowledged referents for project communicators who refer to them by name. Similarly in pragmatism, any name of an objective entity is an operator. Keep in mind that an untested reference doesn't imply the reference is meaningless. Part of the meaning of a location's name refers to the proposition that I would be at that location if I traveled there. In principle, what makes a reality objective is an agreement between people about that reality's implications and verification. Of course, locations (or anything in plain view) are less arguable than generalized concepts like "chair". When I say "chair" I might be referring to a chair like the chair at my desk that easily adjusts its height and can spin, while when you say "chair" you might be referring to a chair like the one in front of your television set that's extra-cushy and has a reclining function. Clearly, since the operations and sensations that I describe about my "chair" are different than your "chair", we must pragmatically be meaning different things by the same term. Although my set of experiences differs infinitely from yours in any number of ways (I'm curious if I could prove the set of differences to be uncountable by the natural numbers), we can still cooperate and communicate on a pragmatic basis provided that we can keep our meanings sufficiently attuned for whatever end we are pursuing. In DDD, the purpose is the project, and the model of the domain objects' attributes and methods and relationships is the negotiated "agreement zone" between what the software experts and the domain experts jointly affirm about the domain's problem and solution. When I say "account", I mean the account class in our domain model whose properties, behavior, and interdependencies are all explicitly laid out; when the domain expert starts stating facts about accounts that aren't captured by the model, everyone can see that the model may need to change once more.
Tuesday, March 30, 2010
a balanced look at unit tests of internal classes
"Internal" C# classes are only accessible to other classes in the same assembly. One of the guidelines for unit testing is to test public interfaces because a unit test should simulate real usage of the class by other classes. So are unit tests of internal C# classes a good idea or not?
Yes, because:
Yes, because:
- Good OO design recommends smaller, cohesive classes of singular purpose. If someone has such a design but creates unit tests just for the public classes, isn't there a good chance in practice that the indirect test coverage will fail to fully check all the possible code paths of the internal classes?
- The members of internal classes still have separate private and public visibilities within the assembly. If a change to an internal class subtly breaks its "public" contract with other classes within the assembly and this goes undetected due to no unit tests, isn't that likely to cause problems whose ultimate impact could affect code outside the assembly as well?
- Efforts to write unit tests for the internal classes could motivate a programmer to reconsider the reusability of those classes. He or she might realize that, with a little redesign, the internal classes could be broadly useful public classes that other programmers can exploit. Isn't this a good outcome?
- Internal classes are designated internal for a reason. Test gurus often intone the mantra, "Listen to what the test is telling you." If someone ever needed to make unit tests for an internal class, then should the class really be public, not internal?
- Hidden OO elements like internal classes offer the freedom to change without breaking other code. But by writing unit tests for internal classes, a programmer forgoes this freedom and thereby accepts the tedium of keeping the unit tests up-to-date with each change. Doesn't this constitute "busy work" that's irrelevant by definition to all code outside the assembly?
- Efforts to write unit tests could motivate a programmer to change the visibility of one or more "utility" classes to public for the sake of testing. Later, another programmer searches across modules and assemblies in an attempt to complete a common task that should be already be implemented in one place. He or she stumbles on the test-enabled classes and happily starts to use it for his scenario. Unfortunately, the methods of the class have side effects that don't make any sense out of the original context for the exposed class. Customers start complaining about these side effects. Isn't this a bad outcome?
Friday, October 30, 2009
nudist community anti-pattern
A sure sign of a dysfunctional object-oriented design is the nudist community anti-pattern. The defining characteristic of this anti-pattern is that all the design's important objects don't have the mutual data privacy that's yielded by true encapsulation. (Still more care is required when working with an implementation that relies primarily on conventions to enforce data hiding.)
At first glance, the information has been properly separated and gathered into individual objects with distinct responsibilities. However, in practice, each object performs its single responsibility by direct requests for additional data from its fellow objects. Hence, when the shape of the data inevitably changes, not only the responsible object must change but also every other object that asks it directly for that data.
The remedy is to revise the nature of the interactions between objects to better respect individual privacy. Objects shouldn't need to openly publish members to accomplish tasks, but instead should send structured messages that demurely ask an object to produce a necessary sub-goal or intermediate result. If it's difficult to decide which object should be responsible for a role, that could be an indication that the design needs refactoring because requirements have changed.
When an object simply must have information from another, the package of information can still be suitably wrapped for handling by the outsider object, e.g. limiting the exposure to partial instead of full or restricting access to "look don't touch". Also, by putting it in a "box" before giving it, the interaction as a whole can be kept loose because each participant need only depend on a shared abstraction with semantic meaning (cf. "dependency inversion").
At first glance, the information has been properly separated and gathered into individual objects with distinct responsibilities. However, in practice, each object performs its single responsibility by direct requests for additional data from its fellow objects. Hence, when the shape of the data inevitably changes, not only the responsible object must change but also every other object that asks it directly for that data.
The remedy is to revise the nature of the interactions between objects to better respect individual privacy. Objects shouldn't need to openly publish members to accomplish tasks, but instead should send structured messages that demurely ask an object to produce a necessary sub-goal or intermediate result. If it's difficult to decide which object should be responsible for a role, that could be an indication that the design needs refactoring because requirements have changed.
When an object simply must have information from another, the package of information can still be suitably wrapped for handling by the outsider object, e.g. limiting the exposure to partial instead of full or restricting access to "look don't touch". Also, by putting it in a "box" before giving it, the interaction as a whole can be kept loose because each participant need only depend on a shared abstraction with semantic meaning (cf. "dependency inversion").
Wednesday, December 03, 2008
gleaning good design advice from unit tests
I'm a beginner to the rigorous usage of xUnit unit tests, which enable easy unit test creation, execution, and repetition through coded tests that a computer can run non-interactively. I'm well-acquainted with the concept, of course, but mostly from blogs. At work, I'm alone in writing such tests. My guess is that the typical programmer categorizes up-to-date, comprehensive, effective test suites like good documentation: "nice but nonessential". The comparison is apt, since both must be maintained in parallel with the code. And the test source can function as sketchy documentation (open source projects, I'm scowling at you!).
But as so many others have observed in practice, good tests are of sufficient value to merit the developer's scarce attention. The upfront cost of writing or updating a test produces benefits repeatedly thereafter. When the code is first written, the test confirms that it meets its function. When the code changes later (it will), the test confirms that it still functions as expected and therefore won't create problems in other code that uses it according to those past expectations (this is even more important if any points of code interaction are resolved at run-time). When the code has a bug, the test that is written to check for the bug confirms that the bug is fixed and remains fixed. When the code is reorganized through the wisdom of hindsight, the test confirms that the transition hasn't accidentally abandoned established dependencies. You don't need to trust TDD or Agile wonks to enjoy these results. Just trust your tests.
The trickier aspect of unit tests, the facial mole that everybody notices and newcomers should acknowledge sooner rather than later, is the all-too-likely possibility that a typical OOP program's objects aren't the neat, independent, well-defined, composable units that facilitate unit testing. To some degree this is unavoidable, as no object is an island. Objects that are excellent individually will need to collaborate and delegate in order to perform their own useful tasks; when asked for its price including tax for a specific political domain, a sales item should need to ask yet another object for the tax rate, because tax rates are not one of an item's responsibilities. A horrendous level of difficulty of writing unit tests for an object indicates that its design or the overall design of the entire set of objects should be reexamined.
For considered as one more design constraint, greater "testability" encourages: 1) cohesion - limiting each object to a fixed and bounded purpose, 2) loose coupling - limiting brittle dependencies between objects, 3) law of Demeter - limiting the number of objects an object interacts with directly, 4) referential transparency - limiting the tendency for methods to rely on a tangled web of tedious-to-establish object states.
However, like other design constraints, testability can be detrimental when misinterpreted or carried to uncalled-for extremes. This list of downsides is more applicable to statically-typed source code that strictly enforces encapsulation (although dynamic typing is no excuse for shoddy object design, of course).
But as so many others have observed in practice, good tests are of sufficient value to merit the developer's scarce attention. The upfront cost of writing or updating a test produces benefits repeatedly thereafter. When the code is first written, the test confirms that it meets its function. When the code changes later (it will), the test confirms that it still functions as expected and therefore won't create problems in other code that uses it according to those past expectations (this is even more important if any points of code interaction are resolved at run-time). When the code has a bug, the test that is written to check for the bug confirms that the bug is fixed and remains fixed. When the code is reorganized through the wisdom of hindsight, the test confirms that the transition hasn't accidentally abandoned established dependencies. You don't need to trust TDD or Agile wonks to enjoy these results. Just trust your tests.
The trickier aspect of unit tests, the facial mole that everybody notices and newcomers should acknowledge sooner rather than later, is the all-too-likely possibility that a typical OOP program's objects aren't the neat, independent, well-defined, composable units that facilitate unit testing. To some degree this is unavoidable, as no object is an island. Objects that are excellent individually will need to collaborate and delegate in order to perform their own useful tasks; when asked for its price including tax for a specific political domain, a sales item should need to ask yet another object for the tax rate, because tax rates are not one of an item's responsibilities. A horrendous level of difficulty of writing unit tests for an object indicates that its design or the overall design of the entire set of objects should be reexamined.
For considered as one more design constraint, greater "testability" encourages: 1) cohesion - limiting each object to a fixed and bounded purpose, 2) loose coupling - limiting brittle dependencies between objects, 3) law of Demeter - limiting the number of objects an object interacts with directly, 4) referential transparency - limiting the tendency for methods to rely on a tangled web of tedious-to-establish object states.
However, like other design constraints, testability can be detrimental when misinterpreted or carried to uncalled-for extremes. This list of downsides is more applicable to statically-typed source code that strictly enforces encapsulation (although dynamic typing is no excuse for shoddy object design, of course).
- Exhibitionist getters and setters. The abuse of getter and setter methods is one of the evergreen blog debates. In the context of pursuing testability, inappropriate getters and setters happen because setters make object setup less of a hassle and getters make verification of a test result less of a hassle. One of the key guidelines to remember when writing unit tests is that, as much as is feasible, the test should be treating the object the same way as actual client code, so the test checks scenarios that matter. Would actual code reach down through the object's throat in order to get a drink? The true problem, as always, is that all access points that an object publicly exposes are by definition part of its (implicit) interface. Details that an object doesn't hide now have the potential to cause cascading maintenance headaches when the details change later. (Please realize that this isn't an attack against dependency injection. Getters and setters for systemic "service" collaborators, abstracted behind interfaces, is different than getters and setters for the object's internal data.)
- Interface explosion. Since unit tests are meant for repetition, side effects are undesirable. A foolproof avoidance technique is to store objects with side effects as interface types and substitute fakes behind the interfaces during tests (this is also helpful for integration tests). The tradeoff is that interface types added purely for the sake of testing enlarge the code's size and complexity without enabling the code to do more (dynamic typing cheerleaders would say this is true of all static types). Although switching to an interface hypothetically prepares the code to work the same in the event that the class is swapped out for another, few programmers (not me) have the rare ability to exactly foretell just what common elements should be in an eternal interface. Moreover, including extraneous types, indirection, etc. conflicts with the principles of avoiding big up-front designs and stuff that's good but possibly inconsequential (gold plating). Programming to an interface instead of an implementation is good practice if an object is to accommodate frequent or dynamic replacements of its fellow objects, but this is not always the case. At this time my preference is a different strategy known as "extract and override": extract just the code that causes side effects, then override that code with a stub in a "testing version" subclass that matches the actual class as closely as feasible (similar to the Template Method OO design pattern).
- Ugly factories. Where many interfaces are present, factory objects may be nearby, hence testability can also lead to more factories. I appreciate the decoupling that factories make possible. I recognize that factories are essential sometimes. For example, the code needs an unknown instance to fulfill an interface or an unfortunately-written object that is a chore to initialize. But I dislike factories. It feels icky and hacky to create a concrete object via a different object, not by a constructor. When objects don't have sufficient contextual information to create the right helper objects - since the more an object must know about its environment to function, the less easily it can be reused - my preference is handing those objects in (through a constructor or setter method). I'll admit there's a limit to pushing out the burden of object creation because the objects must be selected and instantiated somewhere. Centralizing object creation in an overarching Factory or Configuration singleton is a simple option but it also fails modularity. A few uses of the Abstract Factory OO design pattern could be a happy medium between factory-per-object and factory-for-all.
- Bureaucratizing the simple. The balancing of design constraints is a cruel problem in which a compromise does what a compromise does: leaves everyone a little disappointed. After successfully dicing a jumble of concerns into testable object atoms that don't overreach, the way to accomplish a useful requirement is to...assemble an application from atoms. That's an exaggerated negative perspective, but bloggers have been mentioning or insinuating similar remarks about the standard Java APIs for a while (others might, but we understand the value of writing code with standardized stream and reader abstractions, as well as the necessity of not confusing bytes and characters in the Unicode world [Earth]). Like a UI, an API object design should have its knobs and buttons laid out understandably. Typical activities belong at front and center, with unobtrusive advanced flexibility/extensibility in the corners for heavy-duty users who know what they need. In terms of test coverage, convenience methods that straddle multiple objects are fine on the condition that the methods do nothing but delegate to fine-grained, unit-tested objects.
- Library insulation. Libraries complicate unit tests. Closed-source libraries can't be modified in favor of greater testability, and the cost of modifying open-source libraries for testability is often significant. Insulating the code from the libraries with a lot of layers and interfaces, for faking the libraries during tests, seems like an overreaction. On the other hand, it's also wasteful writing unit tests that truth-be-told mostly exercise a mature, vetted library and just slightly exercise the new custom code that calls it. Once again, my inclination is extracting the code that needs testing from the library code that doesn't, and minimizing the untested "glue" code that actually bridges the two (like the rule that the Model and View of MVC can each be intricate but not the code in-between).
Tuesday, July 08, 2008
performance dunderheads check this first...
(Note that even the best people are dunderheaded from time to time.) If an application has been deployed to a new environment but its performance is, say, 8x worse or more, ensure that the relevant database indexes are functioning properly. The hardware may be magnificent and the database well-tuned, but a sequential scan of many records will deliver a gut-punch to performance. It's also obviously not well-suited for caching.
Bonus tip: a good database engine has the ability to show the plan/strategy it computes for a query. Start there to find query optimizations that matter.
Bonus tip: a good database engine has the ability to show the plan/strategy it computes for a query. Start there to find query optimizations that matter.
Saturday, February 16, 2008
clarifications of metaprogramming, monads, DSLs
The last post led to some interesting feedback that has prompted me to make some clarifications. Specifically, I'm responding mostly to the entry on chromatic's use.perl.org Journal (I often enjoy pondering what chromatic writes there and over at O'Reilly Network Blogs). I'm also including a short response to the reddit comments, and tossing in a couple other thoughts I had after posting.
- I remembered a few other metaprogramming techniques. My quick reference to a "preprocessing step that applies templates/macros to the source" doesn't give due recognition to the (sometimes headache-inducing) tricksy acrobatics performed by template metaprogramming. The general category of compiler-compilers was a gaping omission, considering how many of them that Wikipedia lists and how frequently people use these great tools. Camlp4 is a snazzy way to create parsers in OCaml, even for extending OCaml syntax (see the slides for the One-Day Compilers presentation). And F# has a "quotations" feature for treating code like data.
- Perl 6 isn't a DSL, of course. When I wrote that "Parsec can implement external DSLs, even an external DSL like Perl 6", I meant something more along the lines of "Parsec can implement languages that are much different from the host language Haskell, even a language as nontrivial as Perl 6". My intent was merely to comment in passing that "monads in the form of a parser combinator like Parsec" can and do function as an effective technique for external DSLs. Those of us who're familiar with Higher-Order Perl (the later chapters...) aren't (much) fazed by the concept of parser combinators...
- Monads aren't DSLs. Actually, I said the two were opposites. The line "A monad is an inside-out DSL" (and in bold, no less) is using DSLs somewhat as a metaphor or counterpoint for monads, although as I wrote a while ago my preferred monad metaphor is an abstract algebra group or ring (and if you see what the origin for monads was, the suitability of this metaphor isn't surprising).
- However, I did write "In fact, as monad tutorials instruct, Haskell's 'do-notation' is syntax sugar, i.e. a DSL, for using monads..." My intent was merely to comment in passing that do-notation is like a DSL within Haskell syntax for the >>= operator, through which the domain "using monads" is made easier to work in. It reminds me of how LINQ's SQL-ish syntax, with its keywords like "from" and "where", acts like a DSL for data queries within applicable languages. As parts of a language's intrinsic syntax, are "do-notation" or extra-special LINQ syntax true stand-alone DSLs? No. Do those language features, like DSLs, make it easier to program for a specific purpose, a specific task's "domain"? Darn tootin' (yes).
- Are monads a genuine example of metaprogramming, or programming in a language and to an API? Given that a monad is a feature of the language syntax, a monad sure doesn't seem like metaprogramming to a Haskell programmer any more than defmacro does to a Lisper. However, think of how a language without monad capabilities would achieve monad-like effects (consider the "before" and "after" advice of AOP). On the whole, monads seem like a sufficiently sophisticated mechanism for code transformation, regardless of the language, to qualify for "metaprogramming". Someday, when monads aren't considered fancy wizardry, maybe the "plain programming" label will be the consensus. (As an aside, one of my personal syntactical/semantic wishes is that the freedom to choose dynamic or static variable type checking becomes commonplace.)
- reddit comments: Is my only point that do-notation is a DSL, and I'm just trying to be clever about it? 1) Well, I'm always trying to be clever on this blog, as a general rule. It's one of my motivations for writing at all. But I'm sure everyone realizes that my motivation has nothing to do with whether what I'm writing is useful or not to each individual reader. Applying what you read is your responsibility. I'm not one for writing how-tos. 2) As I already admitted, calling the do-notation a DSL is shaky (the "internal" qualifier notwithstanding). That isn't at all the main point. The main point is metaprogramming. The later paragraphs are about contrasting two applications or approaches of metaprogramming, monads and DSLs. If this "Grand Unified Theory" isn't as interesting or persuasive to anyone else, that's okay. It might offer some answers for people who ask, "Can I make DSLs in Haskell?"
- Woo-hoo! As of right now, not only is the blog the top Google result for "rippling brainwaves", but the discussed blog entry is the top Google result for "metaprogramming monads DSLs". (Using Blogger probably helps. You Google searchers have got to ask yourselves a question: "Do I feel lucky?" Well, do ya, punks?) But I didn't write the title or the entry to "bait" readers, honest. That's partly what I was referring to in the self-deprecating remark, "This must be what happens to your mind after reading too many blogs."
- Thanks to the commentators who said they grasped what I was struggling to communicate! I appreciate the occasional reassurance that I'm being lucid, rather than gibbering...
- Update (Feb 18, 2008): I noticed that Writing a Lisp Interpreter In Haskell seems to match some of my conclusions. Nice to see that I finally caught on to what I read many months ago... First a short quote:"Haskell comes standard with a parsing library called Parsec which implements a domain specific language for parsing text." Now a long quote:
A common misconception among Haskell beginners is that monads are an unfortunate evil necessary in a a lazy, side-effect free language. While it is true that monads solve the lazy IO problem, it is only one example of their power. As I plunged deeper and deeper into Haskell I began to realize that monads are a desirable feature that allows the programmer to build otherwise impossible abstractions. Monads, together with higher order functions, provide excellent facilities for abstracting away boilerplate code. In this sense Haskell's monads serve a similar purpose to Lisp's macros (though the concept is entirely different).
Thursday, February 14, 2008
of metaprogramming, monads, DSLs
Update: I wrote a follow-up as feedback to the feedback.
This must be what happens to your mind after reading too many blogs.
Like the writer of "I'm not tired of Java yet", I'm one of those many people who still (must) predominantly use Java at work for all the usual boring reasons, like platform stability and understandable syntax and 3rd-party APIs, but who also enjoy learning about other ways of doing things. The functional programming paradigm is one I've covered before (e.g. in this comparison of FP's and other paradigms' answers to the fundamental concerns of programming). Much of functional programming still appeals to me (e.g. when I implemented an Ajax callback that, if necessary, would make a data-specific number of additional Ajax calls before doing its original task(s) such as updating the DOM). However, over time I'm gaining more appreciation for another paradigm: metaprogramming, programs that manipulate programs, especially when the manipulating and manipulated program are in the same language and the manipulation happens at run-time. Metaprogramming can enable a higher level of abstraction and drastically reduce the need for code to repeat itself, though I'd advise first exhausting the plain reuse mechanisms of the language: namespaces, modules, classes, traits, functions, etc. (On the other hand, in cases in which a complex OO design pattern's careful balance between rigor and flexibility isn't vital and metaprogramming isn't absurdly difficult or error-prone, I prefer the metaprogramming option...)
A broad collection of techniques fall into the metaprogramming category. In LISP-like languages, homoiconicity languages in which the language syntax is a language data structure, read-write metaprogramming is natural. In other languages, metaprogramming could be supported through implementation-provided reflection objects. If the language implementation supports loading/linking additional code at run-time, a program could generate source, prepare it, and load it. With some limitations, metaprogramming might be possible through byte-level operations performed by a library, like ASM. When the language (or the platform it runs on, such as .Net 3.5) offers "expression tree" objects, the creation of new code at run-time is less messy but not necessarily easier. In still other languages that as a matter of course interpret/compile source at run-time (or immediately before), a program could just synthesize source as a string and run an "eval" function on it. Finally, a comparatively primitive yet widely-used technique is a preprocessing step that applies templates/macros to the source to produce the complete source.
One language characteristic blurs the line between metaprogramming and programming somewhat like homoiconic languages: classes and objects that are modifiable without restriction. Learning some ways to exploit this characteristic has been called "Basic Training" for Ruby, but other languages with the characteristic are applicable. Its relationship to metaprogramming is clear. Given that classes and objects combine code and data, and classes and objects constitute the structure of program B (so OOP is a prerequisite), and program A can freely modify the classes and objects of program B (and vice-versa), then program A can manipulate program B--the definition of metaprogramming, in a limited sense. Nevertheless, the modification of classes and objects can accomplish much of the effect of metaprogramming rather simply. (Freedom languages with unrestricted object modifications seem to usually have an "eval", too.)
Regardless of the specific metaprogramming technique, two applications of the paradigm have been getting publicity: monads (Monads in Python is a good example) and DSLs (find an example by your preferred Ruby cheerleader). The DSLs under discussion are internal, not external, which means the DSLs act as an API short-hand that uses the syntax and semantics of a host general-purpose programming language. (But monads in the form of a parser combinator like Parsec can implement external DSLs, even an external DSL like Perl 6...) Monads and DSLs are both applications of metaprogramming because each of the two effectively transforms minimal code into a complete form for execution. In fact, as monad tutorials instruct, Haskell's "do-notation" is syntax sugar, i.e. a DSL, for using monads...
The surprising revelation I came to a short while ago is that these two applications of the metaprogramming paradigm are opposites. In a DSL, statements and expressions of the source code "expand out" into larger blocks of code. The DSL implementation translates the source code and extrapolates a context of other code around it and from it. A monad implementation, by contrast, constitutes a context of other code around the source code that translates the source code and makes the monad's purpose "focus in" on the source code. A monad is an inside-out DSL. In the DSL application of metaprogramming, one observes and implements "operations" and "entities" in a domain, then creates a DSL--a language for those operations and entities. In a monad application of metaprogramming, one observes and implements "operations" and "entities" in a domain, figures out how to interweave those operations and entities with code in general (via the monad "return" and "bind" definitions), then creates a monad--a "domain" for those operations and entities, in which code has extra significance/side-effects. Obviously, the opposite function of monads and DSLs also reflects opposite purposes for the host programming language: an internal DSL acts as a highly-specific dialect and a monad acts as an extension. DSLs could perhaps be friendly to non-programmers (presuming a minimum level of aptitude), but monads would be definitely unfriendly to them.
I'd like to try employing a monad application of metaprogramming to make certain tasks easier. Of course, outside of the pure functional paradigm, where both mainstream languages and reality have state, monads are less essential. Monads could still be beneficial whenever I'll need to model a complicated commonality among several statements, without repeating myself. Those who think monads are still a long way off should note that F# is on its way to becoming an officially-supported .Net language (it also works on Mono), and F# has "computation expressions" whose similarity to monads and list comprehensions is no accident...
This must be what happens to your mind after reading too many blogs.
Like the writer of "I'm not tired of Java yet", I'm one of those many people who still (must) predominantly use Java at work for all the usual boring reasons, like platform stability and understandable syntax and 3rd-party APIs, but who also enjoy learning about other ways of doing things. The functional programming paradigm is one I've covered before (e.g. in this comparison of FP's and other paradigms' answers to the fundamental concerns of programming). Much of functional programming still appeals to me (e.g. when I implemented an Ajax callback that, if necessary, would make a data-specific number of additional Ajax calls before doing its original task(s) such as updating the DOM). However, over time I'm gaining more appreciation for another paradigm: metaprogramming, programs that manipulate programs, especially when the manipulating and manipulated program are in the same language and the manipulation happens at run-time. Metaprogramming can enable a higher level of abstraction and drastically reduce the need for code to repeat itself, though I'd advise first exhausting the plain reuse mechanisms of the language: namespaces, modules, classes, traits, functions, etc. (On the other hand, in cases in which a complex OO design pattern's careful balance between rigor and flexibility isn't vital and metaprogramming isn't absurdly difficult or error-prone, I prefer the metaprogramming option...)
A broad collection of techniques fall into the metaprogramming category. In LISP-like languages, homoiconicity languages in which the language syntax is a language data structure, read-write metaprogramming is natural. In other languages, metaprogramming could be supported through implementation-provided reflection objects. If the language implementation supports loading/linking additional code at run-time, a program could generate source, prepare it, and load it. With some limitations, metaprogramming might be possible through byte-level operations performed by a library, like ASM. When the language (or the platform it runs on, such as .Net 3.5) offers "expression tree" objects, the creation of new code at run-time is less messy but not necessarily easier. In still other languages that as a matter of course interpret/compile source at run-time (or immediately before), a program could just synthesize source as a string and run an "eval" function on it. Finally, a comparatively primitive yet widely-used technique is a preprocessing step that applies templates/macros to the source to produce the complete source.
One language characteristic blurs the line between metaprogramming and programming somewhat like homoiconic languages: classes and objects that are modifiable without restriction. Learning some ways to exploit this characteristic has been called "Basic Training" for Ruby, but other languages with the characteristic are applicable. Its relationship to metaprogramming is clear. Given that classes and objects combine code and data, and classes and objects constitute the structure of program B (so OOP is a prerequisite), and program A can freely modify the classes and objects of program B (and vice-versa), then program A can manipulate program B--the definition of metaprogramming, in a limited sense. Nevertheless, the modification of classes and objects can accomplish much of the effect of metaprogramming rather simply. (Freedom languages with unrestricted object modifications seem to usually have an "eval", too.)
Regardless of the specific metaprogramming technique, two applications of the paradigm have been getting publicity: monads (Monads in Python is a good example) and DSLs (find an example by your preferred Ruby cheerleader). The DSLs under discussion are internal, not external, which means the DSLs act as an API short-hand that uses the syntax and semantics of a host general-purpose programming language. (But monads in the form of a parser combinator like Parsec can implement external DSLs, even an external DSL like Perl 6...) Monads and DSLs are both applications of metaprogramming because each of the two effectively transforms minimal code into a complete form for execution. In fact, as monad tutorials instruct, Haskell's "do-notation" is syntax sugar, i.e. a DSL, for using monads...
The surprising revelation I came to a short while ago is that these two applications of the metaprogramming paradigm are opposites. In a DSL, statements and expressions of the source code "expand out" into larger blocks of code. The DSL implementation translates the source code and extrapolates a context of other code around it and from it. A monad implementation, by contrast, constitutes a context of other code around the source code that translates the source code and makes the monad's purpose "focus in" on the source code. A monad is an inside-out DSL. In the DSL application of metaprogramming, one observes and implements "operations" and "entities" in a domain, then creates a DSL--a language for those operations and entities. In a monad application of metaprogramming, one observes and implements "operations" and "entities" in a domain, figures out how to interweave those operations and entities with code in general (via the monad "return" and "bind" definitions), then creates a monad--a "domain" for those operations and entities, in which code has extra significance/side-effects. Obviously, the opposite function of monads and DSLs also reflects opposite purposes for the host programming language: an internal DSL acts as a highly-specific dialect and a monad acts as an extension. DSLs could perhaps be friendly to non-programmers (presuming a minimum level of aptitude), but monads would be definitely unfriendly to them.
I'd like to try employing a monad application of metaprogramming to make certain tasks easier. Of course, outside of the pure functional paradigm, where both mainstream languages and reality have state, monads are less essential. Monads could still be beneficial whenever I'll need to model a complicated commonality among several statements, without repeating myself. Those who think monads are still a long way off should note that F# is on its way to becoming an officially-supported .Net language (it also works on Mono), and F# has "computation expressions" whose similarity to monads and list comprehensions is no accident...
Tuesday, January 08, 2008
thinking in diffs for svn
Wait, why discuss subversion?
Generally, the topic of revision control doesn't interest me. Revision control falls into my "Meet my needs, but don't bug me!" category of tools, rather than my "Meet my needs, and enthrall me with your incredible additional features!" category. (I consider Spring an example of the latter category. Oooo, look, shiny AOP to go with my DI!) And as others have observed, if someone hasn't been investigating revision control or contributing to FLOSS on personal time, the chances aren't good that he or she has ever used the revision control up-and-comers; companies are typically hesitant to switch revision control systems for three understandable reasons:
Whatever, get back to your topic!
I'd like to share a revelation that I've had during my time here in svn-land. It came to me when I tried to understand svn's merges. I realized that this command is not actually merging. Every merge in revision control systems is for combining part or all of a branch with another branch in the surrounding repository, but svn's merge does not. An svn branch is cheap-copied to another location as a diff of the original, and it diffs, and diffs, until its development has diverged too far from the original. The only way the branch can again become like another branch (or the trunk) is to apply another diff.
Therefore, thinking in diffs resolves some possible confusions about the use of svn. I've read that darcs has a central concept of the "patch" and git has a few central concepts like the "index" and hashed "objects". Subversion's wikipedia page mentions that subversion is described as a "three-dimensional filesystem": a tree and diffs to that tree. Each revision number in subversion is thus a label for a particular set of diffs. Moreover, as an automatically incremented counter, the revision number is just a convenient way to keep revisions in time order. In my twisted pair of hemispheres, I compare it to entropy: always increasing over time. (On the other hand, I sincerely hope the entropy of the code isn't continually increasing. Are you familiar with technical debt?)
Generally, the topic of revision control doesn't interest me. Revision control falls into my "Meet my needs, but don't bug me!" category of tools, rather than my "Meet my needs, and enthrall me with your incredible additional features!" category. (I consider Spring an example of the latter category. Oooo, look, shiny AOP to go with my DI!) And as others have observed, if someone hasn't been investigating revision control or contributing to FLOSS on personal time, the chances aren't good that he or she has ever used the revision control up-and-comers; companies are typically hesitant to switch revision control systems for three understandable reasons:
- Code, both past (meaning its revision history) and present, is a highly valuable asset, which the company's destiny may be riding on. Therefore, the revision control system must be trustworthy, well-supported, etc. One way to cover those bases is to pick the "safe" choice, not the "bleeding-edge" choice. As an aside, I think open-source software has an edge here, because vendor lock-in would clearly be a Bad Thing. What would happen if the revision control system vendor decided to double the cost of the next upgrade (due to a wealth of brand-spanking-new features the company never plans to use), and to set a support end-of-life date for the current release? Not a rosy situation.
- Switching the revision control system has great costs. From the effort of the actual process of the export/import (although my impression is that this is improving) to the development downtime to the need for different (IDE, build system) integration tools to the productivity drop for retraining, the projected benefit of the switch must be significant.
- In the case of a company with special needs, or just being keen on using the "best" revision control system (such as a fast-moving start-up eking out competitive advantage), the cost of sufficiently learning and experimenting and testing the sheer number of candidates is also a factor.
Whatever, get back to your topic!
I'd like to share a revelation that I've had during my time here in svn-land. It came to me when I tried to understand svn's merges. I realized that this command is not actually merging. Every merge in revision control systems is for combining part or all of a branch with another branch in the surrounding repository, but svn's merge does not. An svn branch is cheap-copied to another location as a diff of the original, and it diffs, and diffs, until its development has diverged too far from the original. The only way the branch can again become like another branch (or the trunk) is to apply another diff.
Therefore, thinking in diffs resolves some possible confusions about the use of svn. I've read that darcs has a central concept of the "patch" and git has a few central concepts like the "index" and hashed "objects". Subversion's wikipedia page mentions that subversion is described as a "three-dimensional filesystem": a tree and diffs to that tree. Each revision number in subversion is thus a label for a particular set of diffs. Moreover, as an automatically incremented counter, the revision number is just a convenient way to keep revisions in time order. In my twisted pair of hemispheres, I compare it to entropy: always increasing over time. (On the other hand, I sincerely hope the entropy of the code isn't continually increasing. Are you familiar with technical debt?)
- When specifying a range of revisions, one uses a starting number before the first revision to be included in the range: to merge revisions 108-112, use 107 as the start. The range of revisions is a diff between the specified start and end revisions. Using 108, not 107, would result in collecting the differences between 112 and 108, but not 108 itself.
- In some highly-unusual examples, the start revision of the range is greater than the end revision of the range. This may seem strange (negative time?), but from the viewpoint of diffs it just indicates reversing the positions/roles of the compared revisions.
- As stated before, a merge that ports code changes from one branch (like the trunk) to another branch is just another diff. When one is about to entirely merge a branch into the trunk (or another branch), one starts with the trunk because the goal is to apply whatever differences are present in order to make the trunk match the branch.
Friday, November 16, 2007
has MVC in webapps been over-emphasized?
Most of the prior entries' titles don't contain a question mark. This one does, because I've become torn on this topic. As I understand it, MVC (Model-View-Controller) refers to the interface design principle of preserving code/implementation separation between the data (Model), the appearance or rendering (View), and the processing of user interactions (Controller). MVC in webapps typically means...
Nevertheless, I wonder if the zeal for MVC has misled some people (me included) into the fool's bargain of trading a minor uptick in readability/propriety for a substantial drag in productivity. For instance, consider the many template solutions for implementing the View in JEE. Crossing borders: Web development strategies in dynamically typed languages serves as a minimal overview of some alternative ways. I firmly believe that embedding display-oriented, output-generation code into a template is better than trying to avoid it at all costs through "code-like" tags; markup is a dreadful programming language. Any CFML backers in the audience? I don't mind excellent component tag libraries that save time, but using a "foreach" tag in preference to a foreach statement just seems wonky.
Indeed, it is true that including code inside a template may make it harder to distinguish static from dynamic content, and the burden of switching between mental parsing of HTML and programming language X falls upon the reader. Developers won't mind much, but what about the guy with the Queer Eye for Visual Design, whose job is to make the pages look phat? In my experience, the workflow between graphic artist and web developer is never as easy as everyone wishes. Page templates don't round-trip well, no matter how the template was originally composed in the chosen View technology. A similar phenomenon arises for new output formats for the same data. When one wishes to produce a syndication feed in addition to a display page, the amount of intermingled code will seem like a minor concern relative to the scale of the entire template conversion.
Consider another example of possibly-overdone MVC practices, this time for the Model rather than the View. One Model approach that has grown in popularity is ActiveRecord. Recently my dzone.com feed showed a kerfuffle over the question of whether or not ActiveRecord smells like OO spirit. The resulting rumble of the echo chamber stemmed more from confusion over definitions than irreconcilable differences, I think; in any case, I hope I grasp the main thrust of the original blog entry, despite the unfortunate choice of using data structures as a metaphor for ActiveRecord objects. Quick summary, with a preemptive apology if I mess this up:
In contrast, I'm steadily less convinced of the need for doing that. The number of times I've 1) completely swapped out the Model data source, or 2) significantly tweaked the Model without also somehow exposing that tweak in the View, is minuscule. Similarly, the majority of webapps I work on are almost all View, anyway. Therefore, as long as the View is separate from the Model, meaning no program entity executing both Model and View responsibilities, inserting an abstraction or indirection layer between the two probably is unnecessary extra work and complexity. When the coupling chiefly consists of feeding a dynamic data structure, like a list of hashes of Objects, into the View, the weakness of the contract implies that the Model could change in numerous ways without breaking the call--the parameter is its own abstraction layer. Of course, that flexibility comes at the cost of the View needing to "know" more about its argument to successfully use it. That information has in effect shifted from the call to the body of the call.
Lastly, after retooling in ASP.Net, the importance of a separate Controller has also decreased for me. I can appreciate the necessity of subtler URL-to-code mapping, and the capability to configure it on the application level in addition to the web server level. Yet the concept of each dynamic server page consisting of a page template and an event-driven code-behind class is breathtakingly simple and potent as a unifying principle. Moreover, the very loose MVC enforcement in ASP.Net (although explicit MVC is coming) is counterbalanced by the strong focus on components. To be reusable across Views, components must be not tied too closely to a specific Model or Controller. The Controller code for handling a post-back or other events is assigned to the relevant individual components as delegates. The Model...er, the Model may be the weak point, until the .Net Entity Framework comes around. As with any other webapp framework, developers should have the discipline to separate out the bulk of the nitty-gritty information processing from the page when it makes sense--fortunately, if that code is to be reused in multiple pages, the awkwardness acts as a nudge.
The practical upshot is to use MVC to separate the concerns of the webapp, while ensuring that separation is proportionate to the gain.
- The Model is the data structures and data processing. Ultimately speaking, the Model consists of the information manipulation which is the prime purpose of the webapp, even if it merely accomplishes database lookup.
- The View is the components, templates, and formatting code that somehow transforms the Model into Web-standard output to be sent to the client.
- The Controller processes HTTP requests by running the relevant 'action' code, which interacts with the Model and the View. Part of the Controller is a pre-built framework, since the Controller's tasks, like parsing the URL, are so common from webapp to webapp.
Nevertheless, I wonder if the zeal for MVC has misled some people (me included) into the fool's bargain of trading a minor uptick in readability/propriety for a substantial drag in productivity. For instance, consider the many template solutions for implementing the View in JEE. Crossing borders: Web development strategies in dynamically typed languages serves as a minimal overview of some alternative ways. I firmly believe that embedding display-oriented, output-generation code into a template is better than trying to avoid it at all costs through "code-like" tags; markup is a dreadful programming language. Any CFML backers in the audience? I don't mind excellent component tag libraries that save time, but using a "foreach" tag in preference to a foreach statement just seems wonky.
Indeed, it is true that including code inside a template may make it harder to distinguish static from dynamic content, and the burden of switching between mental parsing of HTML and programming language X falls upon the reader. Developers won't mind much, but what about the guy with the Queer Eye for Visual Design, whose job is to make the pages look phat? In my experience, the workflow between graphic artist and web developer is never as easy as everyone wishes. Page templates don't round-trip well, no matter how the template was originally composed in the chosen View technology. A similar phenomenon arises for new output formats for the same data. When one wishes to produce a syndication feed in addition to a display page, the amount of intermingled code will seem like a minor concern relative to the scale of the entire template conversion.
Consider another example of possibly-overdone MVC practices, this time for the Model rather than the View. One Model approach that has grown in popularity is ActiveRecord. Recently my dzone.com feed showed a kerfuffle over the question of whether or not ActiveRecord smells like OO spirit. The resulting rumble of the echo chamber stemmed more from confusion over definitions than irreconcilable differences, I think; in any case, I hope I grasp the main thrust of the original blog entry, despite the unfortunate choice of using data structures as a metaphor for ActiveRecord objects. Quick summary, with a preemptive apology if I mess this up:
- In imperative-style programming, a program has a set of data structures of arbitrary complexity and a set of subroutines. The subroutines act on the data structures to get the work done.
- In object-oriented-style programming, a program has a set of (reusable) objects. Objects are units having data structures and subroutines. As the program runs, objects send messages to get the work done. Objects don't interact or share data except by the messages. The advantage is that now a particular object's implementation can be anything, such as an instance of a descendant class, as long as the messages are still handled.
- Since ActiveRecord objects represent a database record by freely exposing data, other code in the program can treat the ActiveRecord like an imperative data structure. To quote the blog: "Almost all ActiveRecord derivatives export the database columns through accessors and mutators. Indeed, the Active Record is meant to be used like a data structure." You know how people sometimes complain about objects having public "getters" and "setters" even when the getters/setters aren't strictly necessary for the object to fulfill its responsibility? Roughly the same complaint here.
- The blog entry ends by reiterating that ActiveRecord is still a handy technique, as long as its messy lack of information hiding (leaky encapsulation) is isolated from other code to 1) avoid the creation of brittle dependencies on the associated table's schema, and 2) avoid the database design dictating the application design.
In contrast, I'm steadily less convinced of the need for doing that. The number of times I've 1) completely swapped out the Model data source, or 2) significantly tweaked the Model without also somehow exposing that tweak in the View, is minuscule. Similarly, the majority of webapps I work on are almost all View, anyway. Therefore, as long as the View is separate from the Model, meaning no program entity executing both Model and View responsibilities, inserting an abstraction or indirection layer between the two probably is unnecessary extra work and complexity. When the coupling chiefly consists of feeding a dynamic data structure, like a list of hashes of Objects, into the View, the weakness of the contract implies that the Model could change in numerous ways without breaking the call--the parameter is its own abstraction layer. Of course, that flexibility comes at the cost of the View needing to "know" more about its argument to successfully use it. That information has in effect shifted from the call to the body of the call.
Lastly, after retooling in ASP.Net, the importance of a separate Controller has also decreased for me. I can appreciate the necessity of subtler URL-to-code mapping, and the capability to configure it on the application level in addition to the web server level. Yet the concept of each dynamic server page consisting of a page template and an event-driven code-behind class is breathtakingly simple and potent as a unifying principle. Moreover, the very loose MVC enforcement in ASP.Net (although explicit MVC is coming) is counterbalanced by the strong focus on components. To be reusable across Views, components must be not tied too closely to a specific Model or Controller. The Controller code for handling a post-back or other events is assigned to the relevant individual components as delegates. The Model...er, the Model may be the weak point, until the .Net Entity Framework comes around. As with any other webapp framework, developers should have the discipline to separate out the bulk of the nitty-gritty information processing from the page when it makes sense--fortunately, if that code is to be reused in multiple pages, the awkwardness acts as a nudge.
The practical upshot is to use MVC to separate the concerns of the webapp, while ensuring that separation is proportionate to the gain.
Wednesday, November 14, 2007
another case of unintentionally funny
I've stumbled on another unintentional funny from somewhere on the Web. This is a concluding analysis after converting a function to be truly tail-recursive:
Hmm...tail recursion making a recursive function "nearly look" iterative. Go figure.
(What makes this funny, of course, is the fact that in situations without mutable variables, tail-recursive functions are the way to achieve iteration. And converting recursion into iteration through an explicit stack is another well-known technique...)
Comparing those two the first one increases the stack to a point until it starts to pop the stack. The tail recursive version does not use the stack to keep a “memory” what it has still to do, but calculates the result imediatly. Comparing the source though, in my view the tail recursive version takes all beaty out of the recursive implementation. It nearly looks iterative.
Hmm...tail recursion making a recursive function "nearly look" iterative. Go figure.
(What makes this funny, of course, is the fact that in situations without mutable variables, tail-recursive functions are the way to achieve iteration. And converting recursion into iteration through an explicit stack is another well-known technique...)
Tuesday, October 09, 2007
link: the agile memeplex
ACM Queue has an article analyzing agile development/methodology as a "memeplex": a collection of memes. Unlike some other writing on the 'Net, it goes to the hassle of defining what exactly a "meme" is, and it even uses the word to mean something beyond "blog fad". Its point is that all things Agile are more convincing and meaningful when context is included. Moreover, the vocabulary of Agile is less mystifying after people understand the more-traditional software development concepts the words are almost-synonyms for. As I read it, the article is not an attack on Agile, but a plea to delve into the ever-important details to extract and integrate agile (lower-case) ideas confidently.
The article also mentions in passing that the name "Extreme Development" may have incited both interest and disinterest among developers. Speaking as someone who's generally annoyed by X-treme usage of "extreme", I must agree. (Perhaps "extreme" is the new "awesome"?)
The article also mentions in passing that the name "Extreme Development" may have incited both interest and disinterest among developers. Speaking as someone who's generally annoyed by X-treme usage of "extreme", I must agree. (Perhaps "extreme" is the new "awesome"?)
Wednesday, August 08, 2007
design patterns: just relax
My feeds have been showing some more debate about design patterns. Are design patterns still applicable? Do design patterns lead to unnecessary complexity? Is the use of a design pattern an indication that a platform and/or programming language is inadequate? And on and on.
I suppose I just don't understand the hubbub. As I see it, a design pattern is a technique to solve one or more problems, by trading complexity for flexibility. The tricky part isn't recognizing a problem in existing code, and then refactoring it to use a relevant design pattern; the tricky part is deciding when (and if) it makes sense to apply a design pattern preventively. Maybe part of the reason some people hold their noses around Java code is because of their dislike for design pattern overuse.
Given that the goal of software development is to solve information problems, design patterns are organized descriptions of solutions. Solving a problem with a design pattern is fine. Solving a problem without a design pattern is even better, because that means the problem isn't one of the harder ones. Solving a problem inside a platform, framework, or language that makes the design pattern unnecessary (at least in some common cases) is the best, because the problem is solved on behalf of the programmer. Lastly, solving a difficult problem at runtime using some wild black-magic, while enjoyable, may demand careful organization and documentation to keep it maintainable (stuffing that genie into its own separate bottle, behind a good API, may be a good idea).
Design patterns: use them if you need to. In any case, learn them just in case they may be handy later, and also so you can communicate with other design pattern aficionados. A name for the "callbacks within callbacks design pattern" would have allowed me to end that post with a sentence that wasn't so lame.
I suppose I just don't understand the hubbub. As I see it, a design pattern is a technique to solve one or more problems, by trading complexity for flexibility. The tricky part isn't recognizing a problem in existing code, and then refactoring it to use a relevant design pattern; the tricky part is deciding when (and if) it makes sense to apply a design pattern preventively. Maybe part of the reason some people hold their noses around Java code is because of their dislike for design pattern overuse.
Given that the goal of software development is to solve information problems, design patterns are organized descriptions of solutions. Solving a problem with a design pattern is fine. Solving a problem without a design pattern is even better, because that means the problem isn't one of the harder ones. Solving a problem inside a platform, framework, or language that makes the design pattern unnecessary (at least in some common cases) is the best, because the problem is solved on behalf of the programmer. Lastly, solving a difficult problem at runtime using some wild black-magic, while enjoyable, may demand careful organization and documentation to keep it maintainable (stuffing that genie into its own separate bottle, behind a good API, may be a good idea).
Design patterns: use them if you need to. In any case, learn them just in case they may be handy later, and also so you can communicate with other design pattern aficionados. A name for the "callbacks within callbacks design pattern" would have allowed me to end that post with a sentence that wasn't so lame.
Thursday, June 21, 2007
objectifying javascript
The more things change, the more things stay the same. The Javascript code for the Ajax project I've worked on (the same project that motivated me to make a set of functions for mapping data onto widgets) was giving me rude flashbacks to the line-numbered BASIC days of yore. Global variables and functions are the way I've always written my Javascript (didn't everybody?). I figured it didn't matter, as long as I kept everything straight in my head, and continually looked for opportunities to replace duplicated code with functions....but then my head asplode from the criss-crossing interdependencies between all the separate bits.
Luckily, there are some pages out there that demonstrate a possible way out of the mess. Javascript Refactoring for Safer Better Ajax serves as a great guide and template for moving globally-accessible procedural code to finely-structured, encapsulated object code. Those who are a little rusty may find it helpful to first read about the syntax of Javascript custom objects at the mozilla project's developer site, or wander through Douglas Crockford's Javascript site. Structure your Javascript! recommends the less intricate approach of placing functions into nested objects to achieve namespace emulation.
The path I chose was more or less a compromise. As much as possible, I tried to identify distinct parts or organizational units in my Ajax application code. Then, for each unit, I created a singular global object containing the associated variables and functions. In effect, I broke the code up into object "modules". "Module" is a better descriptor than "object", because there still are no constructors and no real use of "this", nor is anything even remotely private (other than the few function definitions I moved inside of other functions). In other words, the code has not so much been rewritten as reorganized or relabeled. Frankly, the code's sanity may not be much improved, but mine should be.
Luckily, there are some pages out there that demonstrate a possible way out of the mess. Javascript Refactoring for Safer Better Ajax serves as a great guide and template for moving globally-accessible procedural code to finely-structured, encapsulated object code. Those who are a little rusty may find it helpful to first read about the syntax of Javascript custom objects at the mozilla project's developer site, or wander through Douglas Crockford's Javascript site. Structure your Javascript! recommends the less intricate approach of placing functions into nested objects to achieve namespace emulation.
The path I chose was more or less a compromise. As much as possible, I tried to identify distinct parts or organizational units in my Ajax application code. Then, for each unit, I created a singular global object containing the associated variables and functions. In effect, I broke the code up into object "modules". "Module" is a better descriptor than "object", because there still are no constructors and no real use of "this", nor is anything even remotely private (other than the few function definitions I moved inside of other functions). In other words, the code has not so much been rewritten as reorganized or relabeled. Frankly, the code's sanity may not be much improved, but mine should be.
Subscribe to:
Posts (Atom)