Nobody else is watching you read this blog, so for the next 15 or 30 minutes, do not Google, and do not reach for any CS books you've got handy. Use your memory and common sense, and let's see how much you really know about encapsulation.
First off, can you provide a decent explanation of the term? If you (somewhat dubiously) assert that it describes the bundling of data that describes the state of an object, along with methods (behaviour) that operate on that data, you get a grade of C. You are not wrong, but you have not completed the definition.
Let's feel our way towards a better definition of encapsulation. If I told you that accessors (setters and getters) sometimes break encapsulation, but not always, does that help? If I told you that default constructors are possibly a sign that encapsulation is broken, does that throw the switch?
Let's think about object state. We want the state of an object to always be valid and consistent. This means that a new object must start out that way (constructors), and stay that way over all operations (methods) done upon it. We have got a mechanism for ensuring that this is so, and you have likely now guessed what we call that mechanism.
Encapsulation is how we maintain valid and consistent object state.
Understanding this definition explains why a default constructor often breaks encapsulation. For starters, it may simply be available because the coder didn't bother to make it unavailable, or if having left it in, did not have it set valid member values that satisfy class invariants. A default constructor may sometimes be perfectly OK (e.g. there are no data members), but often it is not.
Understanding the definition of encapsulation also explains why sometimes setters and getters break encapsulation, and why sometimes they don't. There have been many blogs written where a pundit claims that any accessor breaks encapsulation. Well, no, that is incorrect. These same pundits opine that public accessors to a member are tantamount to making the member public. Well, no - that is also incorrect.
I should point out that I am using a restrictive definition of encapsulation. Many, if not most, definitions of the term bundle it together with the definition of information hiding. The two are frequently used interchangeably. Information hiding is usually defined as the separation of the contractual interface and its corresponding implementation. The purpose of information hiding is to permit implementation changes without affecting calling code. Because encapsulation is a usual technique for information hiding, the concepts get blurred.
One should also be aware, when reading about information hiding and encapsulation, that different folks have different definitions. For example, some folks take my definition of information hiding above, and refer to it as encapsulation. I do not like this confusion much, and will summarize my preferred definitions with the following observations:
Encapsulation: data, and the operations on that data, belong in the same class. It stands to reason that a sane design has determined what data belongs together, otherwise all bets are off. Determine the class invariants, and ensure that no use of constructors or methods can violate those invariants.
Information Hiding: deny direct access to data members; use accessors. Hide internal structure of a class, and do not expose implementation details. Expose an interface that represents a conceptual abstraction, and keep the implementation private.
Encapsulation and Information Hiding: a design consideration that is relevant to both concepts - when defining the operations on class data, decide what actions objects of that class must perform, and what information they are required to share.
Encapsulation makes information hiding easier to do. We want both, but they are different concepts. I have found that it makes my life easier when I consider the two ideas separately, and don't lump them in under the one or the other term. YMMV.
Sunday, June 19, 2011
Saturday, June 4, 2011
Procedural Objects
Consider one of the classic problems of object-oriented languages. Or to be precise, class-oriented languages, like Java, C++, Objective-C, C#, Smalltalk and Eiffel. Namely, you've got a use case. A use case is an algorithm: it says, with these objects we shall do certain things. You might have two or five or ten different classes, and dozens or hundreds of actual object instances, participating in this particular use case.
What object, or objects, describe the use case?
Before we continue, let's address some terminology problems. People make reference to business objects, domain objects, entities, and value objects, among other types. Unfortunately these terms mean different things to different people. This is an observable fact, it won't go away, and so we may as well assume that we cannot use these terms and still maintain clarity of discussion.
So I'll simply refer to objects (or classes, or instances of classes, or prototypes).
Object-oriented languages - class-oriented languages specifically - early on arrived at a picture of a system where use cases were split up amongst the methods belonging to classes. This is still a primary hallmark of object-oriented design. Furthermore, it is assumed that if the partitioning is done correctly that overall system behaviour will somehow emerge from all the object interactions.
This thinking becomes problematic quickly: a use case may involve dozens of methods in dozens of classes. This is difficult to reason about, both for original implementation and also for maintenance.
Point being, there is a lot of logic in an application that is procedural. It describes use cases, or algorithms. In the sense of classic objects - objects that have state, and whose behaviour is meant to operate only on that state - there is a great deal of logic that doesn't belong to classic objects.
A simple use case that illustrates this problem is a conventional document approval workflow. There is a Document object - its state might include a name (title), contents (a reference), security information, versioning, and its lifecycle status. There are also Actors - the initial author(s), one or more reviewers, one or more approvers, and recipients. We'll keep it simple and assume that the document is not a record. We'll also assume that external processes decide which people belong to which groups, for any given document.
A flowchart for a typical document approval workflow is moderately dense; you could diagram it on a standard letter-sized piece of paper and be able to read it at arm's length, but the diagram would certainly be busy.
So what methods in what classes are responsible for all this logic? Document? Absolutely not - the workflow will vary enormously by organization and timeframe and project, to mention just a few factors. Actors? No, because actors are external to the system by definition. Let's say that there were actor "stub" objects - the actions that these stubs would take are extremely simple. For example, if an actor stub existed for an Approver, there are aspects of a single approval task, like enforcing non-repudiation, or dealing with an unmet deadline, that are not its job. But neither are they responsibilities of the Document instance.
So in a typical C++ or Java or C# application - for that matter Python or Ruby - we end up doing a number of undesirable things:
- we shoehorn a bunch of state and behaviour into Document that doesn't belong there;
- we jam a bunch of state and behaviour into other classes in the application; any class that has the slightest relationship with document approval becomes a possible candidate for housing some of the logic;
- we create one or more procedure objects to handle the use case, but hold our noses while doing it.
The first two activities happen in 99 percent of OO apps. There are also lots of ways of (dubiously) justifying all this. One design smell is when people start talking about rich domain classes; this usually means that they are justifying, often unconsciously, the placement of logic in the wrong spots. In other words, they are breaking up use case logic and don't know where to put it.
There is actually nothing wrong with the first part of #3. It's the second part that is the problem - the fact that we have been conditioned to think that it is bad to have great chunks of procedural, imperative code in our OO program. To add insult to injury, methods that are too "imperative looking" are often derisively and incorrectly referred to as God methods, or the objects that contain them as God objects. The problem in fact is having dozens of small methods in inappropriate classes, accompanied by excessive coupling.
OO design patterns largely skirt this issue. They serve a different purpose. If anything, logic which is badly fragmented due to mistaken beliefs about OO design simply makes it more difficult to properly identify opportunities for application of patterns.
Some readers probably know where I am going with this: Data, Context and Interaction, or DCI. To use Domain Driven Design (DDD) language, the Data in DCI consists of Entities: objects that have state, and behaviour pertaining to that state, but no use-case behaviour.
A Context is an object with one or more methods, all of which relate to a use case (or several related use cases). The Context knows about Roles, and its methods both bind objects to roles and enact the use case logic.
Finally, the Interactions are what the Roles do. As dictated by the Context, data objects assume Roles for varying periods to execute use case logic.
From a design perspective, with DCI, it now becomes much easier to reason about what the code is doing for a given use case. The business logic is obviously still not in one spot, lexically, but all the code that comprises a use case is much easier to locate.
In subsequent posts we will examine implementations of a simple document approval workflow, using DCI, in C++, Scala and F#.
Wednesday, March 30, 2011
Your Friend and Mine - Mister Ted Dziuba
Just kidding. I only ever heard of the man a few days ago through CodeProject Daily News, so whatever Web 2.0 milieu this guy swims in, I'm not normally aware of it. Having read his one rant about how bad Mac OS X is, I was strangely fascinated, and read some more of Ted's blog posts. This force-feeding of Dziuba included diatribes about NoSQL, a somewhat incoherent critique of people who talk about scalability (food for thought: if you badmouth people who talk about scalability, are you not yourself talking about scalability?), and a potpourri of other posts from his blog archives.
Now, I don't mean to disrespect Ted. I don't know the man, and if I'm lucky I never will. But he is a poster child for a lot of things that are badly wrong with software development, and I mean to point those out. It may be illustrative. One thing I really don't care about is his profanity. For all I know it's shock value, and if it works it works - I doubt he swears at people like that face to face; he'd have less teeth and be in a wheelchair.
Point number one...and this is fairly significant...unless I miss my guess the fellow is on the youngish side of 30 years of age. Based on when he graduated school, maybe mid-20's. Gentle readers, that means that Master Ted is inexperienced. No ifs and buts. Furthermore, of the five different jobs he's had in as many years, he was briefly a webhead at Google (wonder why he left?), participated in the failed (and apparently not failed for the right reasons) experiment Persai/Pressflip, had the brass balls to think he knew enough about anything as a youngster to write tech columns (did he have the Register's Youth Perspectives editorial or what?), got in with another startup (Milo) so he could do the same thing that he blasts other people for (develop Web 2.0 basic CRUD-tech ad magnets), and is now a senior dude with the company that bought this startup (eBay), presumably so they have him on hand to fix the code.
Some of his blog posts crack me up. The implied seasoning of experience in dozens of turns of phrase, the purported vast knowledge of technology (after all, if you're going to comment on something then the reader supposes you've learned through trial and error), the venture into Joel Spolsky territory when he talks about how to interview, and the wise world-weariness evidenced by I Don't Code In My Free Time. Ted apparently has so much experience under his belt that he's already compiled a list of programming things he wishes he'd known earlier (like when? In high school?), he knows exactly why "engineers" (dude, you're not an engineer and neither are 95 percent of the script kiddies out there) hop jobs, and he presumes to know how to spot valuable engineers.
One wonderful quote from the esteemed Dziuba: "Any developer who has been around enough to accumulate valuable experience will have his personal collection of stories that have mad him rage. I have been burned by bugs in programming language implementations, bugs I call "coding slurs". I have gotten the shaft more times than I can count from pathological character set issues that make me want to run for Congress on the platform of requiring licenses before people are allowed to use computers."
Character set issues that burned him more times than he can count? Doing what? Writing a small handful of twinkie LAMP web apps? "Accumulate valuable experience?" Give it a few more years, Ted...then we can talk.
It's not about Ted Dziuba. He himself is irrelevant, except insofar as he's a useful symbol of a lot of what's wrong with the software development profession. Which, to put it bluntly, is that there's way too many superficial Web x.y types out there that are not professional. In a sane world - especially one starting from the premise that the script kiddies insist on being called engineers - this guy would have maybe just transitioned from being an apprentice to being a journeyman, and perhaps a decade or so down the road he'd have his first shot at becoming a master software engineer. A decade or more after that his peers might even allow that he's sort of senior.
Ted, my man, thank you. I mean that. You're a mouthpiece for all the problem children in the industry, and the first step in cleaning up the mess is awareness of the problem. You're helping...albeit maybe not like you expect.
Oh, and Ted? In Java subList Gotcha, you mention "Well it turns out that subList didn't do what I thought it did. I assumed that I just got a new List that contained the elements in the given range of the original." And "read the documentation." Well, yes, Ted, you do read the documentation when using an API. Leastways professionals do. But if you got bit by something this basic, with a fundamental Java interface, then I guess that points to a pattern of either novice or sloppy behaviour...or both. Given that you've declaimed that there are way more important things to do than professional development outside work hours, it looks like both.
Now, I don't mean to disrespect Ted. I don't know the man, and if I'm lucky I never will. But he is a poster child for a lot of things that are badly wrong with software development, and I mean to point those out. It may be illustrative. One thing I really don't care about is his profanity. For all I know it's shock value, and if it works it works - I doubt he swears at people like that face to face; he'd have less teeth and be in a wheelchair.
Point number one...and this is fairly significant...unless I miss my guess the fellow is on the youngish side of 30 years of age. Based on when he graduated school, maybe mid-20's. Gentle readers, that means that Master Ted is inexperienced. No ifs and buts. Furthermore, of the five different jobs he's had in as many years, he was briefly a webhead at Google (wonder why he left?), participated in the failed (and apparently not failed for the right reasons) experiment Persai/Pressflip, had the brass balls to think he knew enough about anything as a youngster to write tech columns (did he have the Register's Youth Perspectives editorial or what?), got in with another startup (Milo) so he could do the same thing that he blasts other people for (develop Web 2.0 basic CRUD-tech ad magnets), and is now a senior dude with the company that bought this startup (eBay), presumably so they have him on hand to fix the code.
Some of his blog posts crack me up. The implied seasoning of experience in dozens of turns of phrase, the purported vast knowledge of technology (after all, if you're going to comment on something then the reader supposes you've learned through trial and error), the venture into Joel Spolsky territory when he talks about how to interview, and the wise world-weariness evidenced by I Don't Code In My Free Time. Ted apparently has so much experience under his belt that he's already compiled a list of programming things he wishes he'd known earlier (like when? In high school?), he knows exactly why "engineers" (dude, you're not an engineer and neither are 95 percent of the script kiddies out there) hop jobs, and he presumes to know how to spot valuable engineers.
One wonderful quote from the esteemed Dziuba: "Any developer who has been around enough to accumulate valuable experience will have his personal collection of stories that have mad him rage. I have been burned by bugs in programming language implementations, bugs I call "coding slurs". I have gotten the shaft more times than I can count from pathological character set issues that make me want to run for Congress on the platform of requiring licenses before people are allowed to use computers."
Character set issues that burned him more times than he can count? Doing what? Writing a small handful of twinkie LAMP web apps? "Accumulate valuable experience?" Give it a few more years, Ted...then we can talk.
It's not about Ted Dziuba. He himself is irrelevant, except insofar as he's a useful symbol of a lot of what's wrong with the software development profession. Which, to put it bluntly, is that there's way too many superficial Web x.y types out there that are not professional. In a sane world - especially one starting from the premise that the script kiddies insist on being called engineers - this guy would have maybe just transitioned from being an apprentice to being a journeyman, and perhaps a decade or so down the road he'd have his first shot at becoming a master software engineer. A decade or more after that his peers might even allow that he's sort of senior.
Ted, my man, thank you. I mean that. You're a mouthpiece for all the problem children in the industry, and the first step in cleaning up the mess is awareness of the problem. You're helping...albeit maybe not like you expect.
Oh, and Ted? In Java subList Gotcha, you mention "Well it turns out that subList didn't do what I thought it did. I assumed that I just got a new List that contained the elements in the given range of the original." And "read the documentation." Well, yes, Ted, you do read the documentation when using an API. Leastways professionals do. But if you got bit by something this basic, with a fundamental Java interface, then I guess that points to a pattern of either novice or sloppy behaviour...or both. Given that you've declaimed that there are way more important things to do than professional development outside work hours, it looks like both.
Saturday, March 5, 2011
Collaboration Is Missing The Point
MIT Technology Review has started a new monthly topic in Business, entitled Collaboration Tools. They promise to examine why some tools work, and why others don't. They will also be looking at when and how collaboration is valuable.
Think about that last statement. I didn't see it phrased quite that way on Technology Review, but at least a few articles urge caution in the deployment and use of collaboration tools. So that's what they mean, that sometimes collaboration can be overrated. And that means that it's not always necessary, and sometimes collaboration is counterproductive.
A lot of technology companies and IT users are still mesmerized by the Kollaboration Kool-Aid. After all, how can it be a bad thing if as many people as possible are in touch, and always in touch? How can it be a bad thing if people are sharing knowledge 24/7?
Well, it can be a bad thing, and in my opinion often is. An IEEE Spectrum article entitled "Metcalfe's Law is Wrong" pretty much lays some real-world realities on the line. As the article surmises, a fundamental flaw behind Metcalfe's or Reed's laws is in the assignment of equal value to all connections. The authors argue that Zipf's law makes more sense. And intuitively it does - in my work environment, for any given problem I am working on, I can rank the value of collaborating with various people. To a greater or lesser degree only a few connections have significant value.
Let's go one further. It stands to reason that some connections actually have negative value - opening up a social, "collaborative" channel with a certain person may actually hamper my work.This may also depend very much on the nature of the work: everyone has had tasks from time to time where, quite frankly, everyone else is a nuisance and a hindrance to getting the job done.
This happens more often than the vendors of collaboration tools are willing to admit. To hear their user stories everyone benefits by intimately working together all the time. Not true: it's more likely the case that valuable collaboration is the exception, not the rule.
What knowledge workers really need is effective knowledge management (KM). The typical state of KM in enterprises is abysmal, and that's perhaps a subject for another blog. What I'd like to be able to do (and usually have to resort to Google for, in place of something truly effective) is to search for information inside the organization, and not have to disrupt other peoples' time to do it. Collaboration is disruptive, good KM is not.
Unrestricted, uncontrolled collaboration cannot work. If jamming a dozen people into a room without leadership, and letting them jabber at each other to try to figure out how best to solve a problem, had ever worked, then organizations would be doing that all the time. Oh wait...those are called meetings. Sorry.
Seriously, carefully controlled small doses of collaboration are fine. But here's a thought - we've had an excellent IT tool for that, for decades: it's called email. Switch off the email notification pop-ups, and simply ask that people on a team check their Inbox at least once an hour. Do you really think you need more than that?
Think about that last statement. I didn't see it phrased quite that way on Technology Review, but at least a few articles urge caution in the deployment and use of collaboration tools. So that's what they mean, that sometimes collaboration can be overrated. And that means that it's not always necessary, and sometimes collaboration is counterproductive.
A lot of technology companies and IT users are still mesmerized by the Kollaboration Kool-Aid. After all, how can it be a bad thing if as many people as possible are in touch, and always in touch? How can it be a bad thing if people are sharing knowledge 24/7?
Well, it can be a bad thing, and in my opinion often is. An IEEE Spectrum article entitled "Metcalfe's Law is Wrong" pretty much lays some real-world realities on the line. As the article surmises, a fundamental flaw behind Metcalfe's or Reed's laws is in the assignment of equal value to all connections. The authors argue that Zipf's law makes more sense. And intuitively it does - in my work environment, for any given problem I am working on, I can rank the value of collaborating with various people. To a greater or lesser degree only a few connections have significant value.
Let's go one further. It stands to reason that some connections actually have negative value - opening up a social, "collaborative" channel with a certain person may actually hamper my work.This may also depend very much on the nature of the work: everyone has had tasks from time to time where, quite frankly, everyone else is a nuisance and a hindrance to getting the job done.
This happens more often than the vendors of collaboration tools are willing to admit. To hear their user stories everyone benefits by intimately working together all the time. Not true: it's more likely the case that valuable collaboration is the exception, not the rule.
What knowledge workers really need is effective knowledge management (KM). The typical state of KM in enterprises is abysmal, and that's perhaps a subject for another blog. What I'd like to be able to do (and usually have to resort to Google for, in place of something truly effective) is to search for information inside the organization, and not have to disrupt other peoples' time to do it. Collaboration is disruptive, good KM is not.
Unrestricted, uncontrolled collaboration cannot work. If jamming a dozen people into a room without leadership, and letting them jabber at each other to try to figure out how best to solve a problem, had ever worked, then organizations would be doing that all the time. Oh wait...those are called meetings. Sorry.
Seriously, carefully controlled small doses of collaboration are fine. But here's a thought - we've had an excellent IT tool for that, for decades: it's called email. Switch off the email notification pop-ups, and simply ask that people on a team check their Inbox at least once an hour. Do you really think you need more than that?
Friday, September 3, 2010
Changing Requirements
I recently finished almost two years worth of work for a client, the lion's share of which was spent on one specific J2EE application. It occurred to me shortly before I transferred off, and not for the first time, that with the exception of some new functionality that's been added over those years that at least 95% of the requirements for this application have not changed since the software was a mainframe program written in Natural and using Adabas more than 5 years ago.
I then realized that with no major exceptions I could think of, every application I've ever worked on, in twenty-odd years of serious programming, has had fairly stable requirements.
Now, don't get me wrong. Frequently the requirements encoded in the final version of a program are wildly at variance with what the client and programmers initially thought them to be. The client may be quite inarticulate at expressing what he wants, the client may assume that the business analyst or developer knows or understands things about the business rules when they really don't, the business analyst may do a bad job at describing the requirements for the designers, the designers may botch the job of capturing the requirements when they do the design, and so forth.
Once the application is delivered it's rarely correct. The client now has something they can compare their wishes to, and years of fixing and upgrading reshape the work into something approximating what should have been captured and coded 3 or 5 years before. The main point being, over a substantial timeframe the real requirements do not change.
The agile community would have it that requirements change, and change a lot. Well, no, they don't. The understanding of what the requirements are does change a lot, though. But it seems rather silly to me to espouse a philosophy that basically accepts poor communications, and rather than working to fix the problem, works around the problem.
I recently read a blog article, and a comment in another, that seem to me to be wise solutions. One writer espoused writing a thorough Readme first, before doing design, and another advocated writing the user manual first. Both are basically the same thing, although I like the idea of the user guide.
Think about it. The business analyst gathers the requirements, and at that point the user manual is written. This can immediately go back to the client for review and approval. If there is some serious misunderstanding of what the users want, it's likely to show up in the user guide.
A user manual isn't everything. Not every requirement manifests as a process or step or procedure that's described in a user guide. But a lot does. The rest is often business rules, and I also believe that there are better ways of capturing and coding these than what is often the case. I'll discuss that in a future article.
I then realized that with no major exceptions I could think of, every application I've ever worked on, in twenty-odd years of serious programming, has had fairly stable requirements.
Now, don't get me wrong. Frequently the requirements encoded in the final version of a program are wildly at variance with what the client and programmers initially thought them to be. The client may be quite inarticulate at expressing what he wants, the client may assume that the business analyst or developer knows or understands things about the business rules when they really don't, the business analyst may do a bad job at describing the requirements for the designers, the designers may botch the job of capturing the requirements when they do the design, and so forth.
Once the application is delivered it's rarely correct. The client now has something they can compare their wishes to, and years of fixing and upgrading reshape the work into something approximating what should have been captured and coded 3 or 5 years before. The main point being, over a substantial timeframe the real requirements do not change.
The agile community would have it that requirements change, and change a lot. Well, no, they don't. The understanding of what the requirements are does change a lot, though. But it seems rather silly to me to espouse a philosophy that basically accepts poor communications, and rather than working to fix the problem, works around the problem.
I recently read a blog article, and a comment in another, that seem to me to be wise solutions. One writer espoused writing a thorough Readme first, before doing design, and another advocated writing the user manual first. Both are basically the same thing, although I like the idea of the user guide.
Think about it. The business analyst gathers the requirements, and at that point the user manual is written. This can immediately go back to the client for review and approval. If there is some serious misunderstanding of what the users want, it's likely to show up in the user guide.
A user manual isn't everything. Not every requirement manifests as a process or step or procedure that's described in a user guide. But a lot does. The rest is often business rules, and I also believe that there are better ways of capturing and coding these than what is often the case. I'll discuss that in a future article.
Thursday, December 31, 2009
End of the Noughties
I've found one thing out - it's not in me to regularly maintain a blog. For a couple of reasons. One, I could never keep a diary either; I'd rather do than record what I've done. I don't have the habit of confiding on paper or to a computer. Second, I'm never happy with what I just wrote. I'm a pretty good technical writer, where that kind of obsessive attention to detail is fine, but I suspect I'd be a disaster as a novelist: good material, but about a page per week.
Nevertheless, it's the end of 2009, and it's a worthy moment to write a blog entry. If for no other reason than to maintain the fiction that I might eventually keep this thing up.
On the software front I'd call it a good year. Not a great year, but nonetheless a decent year. The company I work for is weathering the recession, no mean feat for what is still a startup. We're trying to diversify our client base, which is understandably important. We're unfortunately, by dint of our current customers, rather more tied to only J2EE, and obsolete J2EE at that, than I'd like. But as they say, mendicants can't be choosers. One major downside of this is that if all your resources are occupied with J2EE 1.4 work, it's difficult to find adequate downtime to keep up with the Joneses. State of the art technology-wise, that is.
Speaking of technology, just in J2EE (forget about .NET, all those ERP systems, and so forth) and related (support) technologies things are getting a bit too scrambled for me. I'm starting to like the stately advance of MS .NET quite a lot. Granted, Microsoft moves at a pretty quick clip themselves, and they foster a huge 3rd party ecosystem, but compared to J2EE they are very stable.
In our case (my colleagues and I) we're stuck into mostly OAS 10.1.3.x from Oracle. J2EE 1.4 with EJB3 (most of it) slathered on top...imperfectly. I'm thirsting to ditch JPA and ORMs entirely, and stick with iBatis. Or more to the point, we're starting to realize that not every Java persistence solution ought to include JPA. And of course oc4j 10.1.3.x uses JSF 1.1...not even JSF 1.2, let alone JSF 2.0. Christ. Quite frankly we'd all love to use Spring MVC et al. - we're all familiar with it...but you need clients that are willing to use it.
What's with Spring anyway? A person barely assimilates most of Spring 2.5, and now they're onto Spring 3, all DM and OSGi and what have you. And Maven is no longer their fad favourite anymore - now we have to start considering Apache Ivy. I consider myself a pretty bright spark, but there are only so many hours in the day to keep up with all this crap. I'm biting the bullet anyway, and learning Spring DM.
Eclipse Galileo (3.5) is a disappointment. I say so. It's got too many quirks. NetBeans, certainly for all of the 6.x series (I'm trying out 6.8 on Ubuntu 9.10, and have 6.7 on Mac OS X 10.6 and Windows XP SP3 both), is way ahead. Unfortunately a lot of people develop for Eclipse and neglect NetBeans. Too bad. But if you're an Eclipse person, stick with Ganymede. Unless you can't.
Parallels for Mac is a disappointment. Again, I say so. If all you're going to do is run Windows VMs, it's OK. But VMWare is much better. And VirtualBox rules for running Solaris VMs on Mac OS X. Hands down.
Java is a disappointment. Yes, I say so. For a professional programmer I am unusually unpicky about language quirks and deficiencies. I can make things work. And Java is without a doubt a good GP programming language. But they lost their way on a few things, which ought to have been dealt with no later than Java 6. Now that I think about it, what real importance did JDK 1.6 have anyway? Anyhow, I believe the JVM needs to understand true value types, sooner rather than later. True first-class functions (methods), and so lambdas and closures, would be nice too.
But the main thing I see that Java really has a problem with in years ahead is concurrency. Yes, concurrency. Seems ironic, seeing as how Java was the first language touted as making concurrency easier to use. Well, yes, it is easier to use. But it's still hard. Other languages like Scala, Clojure and Erlang have Java beat hands down in this regard. Why would a developer want to use the difficult and complex concurrency constructs in Java when they can use much higher abstractions? Either Java builds these abstractions in or it soon becomes irrelevant. IMHO.
Ultimately, is software development more simple today (Dec 31st 2009) than it was 10 years ago? Not hardly. It's more complex, and becoming more so. I used to laugh at all the efforts and projects and initiatives that wanted to put design power into the hands of business users. I still think those efforts have a long way to go, but now I genuinely want them to succeed. Because Joe Average Coder is becoming overwhelmed with all the plumbing. Anything that takes some of the load off us is welcome.
Best of the New Year.
Nevertheless, it's the end of 2009, and it's a worthy moment to write a blog entry. If for no other reason than to maintain the fiction that I might eventually keep this thing up.
On the software front I'd call it a good year. Not a great year, but nonetheless a decent year. The company I work for is weathering the recession, no mean feat for what is still a startup. We're trying to diversify our client base, which is understandably important. We're unfortunately, by dint of our current customers, rather more tied to only J2EE, and obsolete J2EE at that, than I'd like. But as they say, mendicants can't be choosers. One major downside of this is that if all your resources are occupied with J2EE 1.4 work, it's difficult to find adequate downtime to keep up with the Joneses. State of the art technology-wise, that is.
Speaking of technology, just in J2EE (forget about .NET, all those ERP systems, and so forth) and related (support) technologies things are getting a bit too scrambled for me. I'm starting to like the stately advance of MS .NET quite a lot. Granted, Microsoft moves at a pretty quick clip themselves, and they foster a huge 3rd party ecosystem, but compared to J2EE they are very stable.
In our case (my colleagues and I) we're stuck into mostly OAS 10.1.3.x from Oracle. J2EE 1.4 with EJB3 (most of it) slathered on top...imperfectly. I'm thirsting to ditch JPA and ORMs entirely, and stick with iBatis. Or more to the point, we're starting to realize that not every Java persistence solution ought to include JPA. And of course oc4j 10.1.3.x uses JSF 1.1...not even JSF 1.2, let alone JSF 2.0. Christ. Quite frankly we'd all love to use Spring MVC et al. - we're all familiar with it...but you need clients that are willing to use it.
What's with Spring anyway? A person barely assimilates most of Spring 2.5, and now they're onto Spring 3, all DM and OSGi and what have you. And Maven is no longer their fad favourite anymore - now we have to start considering Apache Ivy. I consider myself a pretty bright spark, but there are only so many hours in the day to keep up with all this crap. I'm biting the bullet anyway, and learning Spring DM.
Eclipse Galileo (3.5) is a disappointment. I say so. It's got too many quirks. NetBeans, certainly for all of the 6.x series (I'm trying out 6.8 on Ubuntu 9.10, and have 6.7 on Mac OS X 10.6 and Windows XP SP3 both), is way ahead. Unfortunately a lot of people develop for Eclipse and neglect NetBeans. Too bad. But if you're an Eclipse person, stick with Ganymede. Unless you can't.
Parallels for Mac is a disappointment. Again, I say so. If all you're going to do is run Windows VMs, it's OK. But VMWare is much better. And VirtualBox rules for running Solaris VMs on Mac OS X. Hands down.
Java is a disappointment. Yes, I say so. For a professional programmer I am unusually unpicky about language quirks and deficiencies. I can make things work. And Java is without a doubt a good GP programming language. But they lost their way on a few things, which ought to have been dealt with no later than Java 6. Now that I think about it, what real importance did JDK 1.6 have anyway? Anyhow, I believe the JVM needs to understand true value types, sooner rather than later. True first-class functions (methods), and so lambdas and closures, would be nice too.
But the main thing I see that Java really has a problem with in years ahead is concurrency. Yes, concurrency. Seems ironic, seeing as how Java was the first language touted as making concurrency easier to use. Well, yes, it is easier to use. But it's still hard. Other languages like Scala, Clojure and Erlang have Java beat hands down in this regard. Why would a developer want to use the difficult and complex concurrency constructs in Java when they can use much higher abstractions? Either Java builds these abstractions in or it soon becomes irrelevant. IMHO.
Ultimately, is software development more simple today (Dec 31st 2009) than it was 10 years ago? Not hardly. It's more complex, and becoming more so. I used to laugh at all the efforts and projects and initiatives that wanted to put design power into the hands of business users. I still think those efforts have a long way to go, but now I genuinely want them to succeed. Because Joe Average Coder is becoming overwhelmed with all the plumbing. Anything that takes some of the load off us is welcome.
Best of the New Year.
Sunday, December 28, 2008
JSF: Frameworks and Security
One thing that has been conspicuously missing from every J2EE project I've worked on - ever - is a clean way of handling authorization. That is no less true for applications that use JSF. I shouldn't go out on a limb and say that authentication is all that clean either...actual implementations tend to range from being inextricably tied to a specific J2EE server in code to being effectively tied to a security implementation (albeit not a complete app server) because of the amount of configuration (and provision of custom security classes) that one has to do.
What a developer would like is to choose an authentication method (let's assume here that it'll be FORM-based over HTTPS, because this is quite common), and have the container do the authentication in a standard way (j_security_check and all that), with login and error pages configured in the web.xml. The same goes for logout. In addition, the login/logout code should not be inextricably tied to a server or security provider.
Furthermore, once authenticated, authorization should be easy: coming up on the end of 2008 a developer might expect a standardized way of rendering (or not rendering) JSF page elements based on authenticated role, and a standardized way of marking managed bean methods with required roles.
Note the word "standardized" - there are ways of doing all of this, even if it comes to hand-rolling it, but it ends up being a horrible mishmash. Let's bear in mind, too, that the customer usually dictates the J2EE server, and you, the developer, are possibly going to choose a framework or frameworks based on what you know they can do for you. I say possibly because that decision may not be yours either...for example, if you're working with Oracle SOA you may use Oracle across the board: JDeveloper to work with Oracle ADF etc. So, for example, you probably don't have any choice as to whether it's JBoss or OAS or Glassfish or Websphere, and at best you'll have some leeway in deciding, say, on Facelets and ICEFaces, or perhaps SEAM (maybe with ICEFaces too). But all of these decisions will be made before you start considering security.
You may think that you'll do requirements and design first, then look at how you want your security to work, and then pick servers and frameworks...I wish you luck with that.
Login Forms
Anyway, let's start with that login form. Try this little experiment...once you've set up security realms, groups and users in your application server, create a barebones web application with FORM based login. You may as well add your JSF framework(s) - it proves nothing to leave that stuff out. First off, create a target page which is JSF (say, a facelet using ICEFaces components). Perhaps that could be your welcome page in the web.xml.
Next, create two pages for your login and login error pages. This may not hold true for every server or framework, but you ought to be able to use JSF pages (say .jspx or .xhtml)...the main thing is to use only HTML tags for the login form. I know that for ICEFaces/Facelets on Glassfish V2 I can use .xhtml pages processed by the ICEFaces servlet no problem.
For the login HTML or JSP, use all HTML tags, as in the below snippet:
<form action="j_security_check" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="j_username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="j_password"/></td>
</tr>
</table>
<input type="submit" value="Login"/>
</form>
Set up your error page similarly, except perhaps with an informative message. Make sure your web.xml has a section that looks something like:
<security-constraint>
<display-name>All Pages</display-name>
<web-resource-collection>
<web-resource-name>All</web-resource-name>
<description/>
<url-pattern>*.iface</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description/>
<role-name>all</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>test</realm-name>
<form-login-config>
<form-login-page>/login.jspx</form-login-page>
<form-error-page>/login_error.jspx</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description/>
<role-name>all</role-name>
</security-role>
You may also have to configure an application server-specific web.xml (like sun-web.xml) to map groups to roles.
If you build, deploy and run, and navigate to your JSF welcome page, you should first see the login page come up. Try putting in the username and password you set up in your security realm incorrectly first, to make sure the error page comes up. Then, if you enter the credentials correctly, you'll be redirected to your welcome page, replete with JSF effects.
What Exactly Is The Problem?
Between you and me that's actually a really good question. Because, as you may have found out already, if you modify our example to make the login page use JSF components for the form, input elements, command button etc, so-called JSF name-mangling (or ID mangling really) comes into play. For example, if your form has ID 'mainForm', then the ID for the username input (h:inputText) becomes 'mainForm:j_username'. And this is not what the container expects to see.
What people are essentially complaining about is that they can't use JSF tags for the login form itself (unless they use MyFaces Tomahawk with the 'forceId' attribute, or use a regular backing bean that resubmits to the container behind the scenes, or suchlike). Apparently the main problem with this is that they can't validate in the login form. Now, maybe it's just me, but it seems to me that if the username and/or password are wrong (including empty fields), the only answer you need is that the login failed...being able to pop up a nice message in red that a password is required is really sweet, but I imagine most users can work that one out for themselves. If necessary the login error page can provide a few tips.
In any case, a very common model in web applications is to dispense with FORM-based login, in the standard sense, entirely, and have a JSF form (possibly complex) that does have the username/password fields, and a JSF login action on a backing bean. The login method eventually ends up calling the container authentication programmatically, plus a whack of other things like redirecting based on role.
It strikes me as a bit silly to want a rich JSF login screen based on the 'j_security_check' model, but that's what a lot of people want.
Authorization
One of the things that a developer typically wants to do is to display or not display a UI component based on the security role of the authenticated user. For example, one user may only be able to view certain information on a page, but another might be able to edit certain items. Being able to control 'rendered' and 'disabled' attributes based on role is pretty handy.
This is actually not so difficult to do. It's merely that there are no security-specific attributes on standard JSF tags, although some JSF extensions do have them (MyFaces, ICEFaces, ACEGI). The JSF Security Project is looking (looked?) at making this kind of information available through EL.
Until such a thing is completely standardized it's just as easy to roll your own, unless you're already using MyFaces or IDEFaces or ACEGI. I certainly wouldn't pull in any of those only for this purpose...for example, adopting ACEGI means adopting Spring. Note also that there can be many quirks...if authenticating with JAAS you may have issues using the ICEFaces authorization attributes, and if mixing frameworks...well, sometimes they don't mix well, and sometimes they do (Tomahawk and ICEFaces don't cooperate on a single page).
Summary
In the J2EE world right now, we still spend too much time on implementing security. The requirements of 95%+ of developers in this area are simple and they are constant, and yet we tend to re-invent the wheel. As a development shop you can certainly reinvent once, and then re-use many times, but it would be nice if you never had to re-invent. What's still missing is simple off-the-shelf J2EE/JSF security solutions.
What a developer would like is to choose an authentication method (let's assume here that it'll be FORM-based over HTTPS, because this is quite common), and have the container do the authentication in a standard way (j_security_check and all that), with login and error pages configured in the web.xml. The same goes for logout. In addition, the login/logout code should not be inextricably tied to a server or security provider.
Furthermore, once authenticated, authorization should be easy: coming up on the end of 2008 a developer might expect a standardized way of rendering (or not rendering) JSF page elements based on authenticated role, and a standardized way of marking managed bean methods with required roles.
Note the word "standardized" - there are ways of doing all of this, even if it comes to hand-rolling it, but it ends up being a horrible mishmash. Let's bear in mind, too, that the customer usually dictates the J2EE server, and you, the developer, are possibly going to choose a framework or frameworks based on what you know they can do for you. I say possibly because that decision may not be yours either...for example, if you're working with Oracle SOA you may use Oracle across the board: JDeveloper to work with Oracle ADF etc. So, for example, you probably don't have any choice as to whether it's JBoss or OAS or Glassfish or Websphere, and at best you'll have some leeway in deciding, say, on Facelets and ICEFaces, or perhaps SEAM (maybe with ICEFaces too). But all of these decisions will be made before you start considering security.
You may think that you'll do requirements and design first, then look at how you want your security to work, and then pick servers and frameworks...I wish you luck with that.
Login Forms
Anyway, let's start with that login form. Try this little experiment...once you've set up security realms, groups and users in your application server, create a barebones web application with FORM based login. You may as well add your JSF framework(s) - it proves nothing to leave that stuff out. First off, create a target page which is JSF (say, a facelet using ICEFaces components). Perhaps that could be your welcome page in the web.xml.
Next, create two pages for your login and login error pages. This may not hold true for every server or framework, but you ought to be able to use JSF pages (say .jspx or .xhtml)...the main thing is to use only HTML tags for the login form. I know that for ICEFaces/Facelets on Glassfish V2 I can use .xhtml pages processed by the ICEFaces servlet no problem.
For the login HTML or JSP, use all HTML tags, as in the below snippet:
<form action="j_security_check" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="j_username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="j_password"/></td>
</tr>
</table>
<input type="submit" value="Login"/>
</form>
Set up your error page similarly, except perhaps with an informative message. Make sure your web.xml has a section that looks something like:
<security-constraint>
<display-name>All Pages</display-name>
<web-resource-collection>
<web-resource-name>All</web-resource-name>
<description/>
<url-pattern>*.iface</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description/>
<role-name>all</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>test</realm-name>
<form-login-config>
<form-login-page>/login.jspx</form-login-page>
<form-error-page>/login_error.jspx</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description/>
<role-name>all</role-name>
</security-role>
You may also have to configure an application server-specific web.xml (like sun-web.xml) to map groups to roles.
If you build, deploy and run, and navigate to your JSF welcome page, you should first see the login page come up. Try putting in the username and password you set up in your security realm incorrectly first, to make sure the error page comes up. Then, if you enter the credentials correctly, you'll be redirected to your welcome page, replete with JSF effects.
What Exactly Is The Problem?
Between you and me that's actually a really good question. Because, as you may have found out already, if you modify our example to make the login page use JSF components for the form, input elements, command button etc, so-called JSF name-mangling (or ID mangling really) comes into play. For example, if your form has ID 'mainForm', then the ID for the username input (h:inputText) becomes 'mainForm:j_username'. And this is not what the container expects to see.
What people are essentially complaining about is that they can't use JSF tags for the login form itself (unless they use MyFaces Tomahawk with the 'forceId' attribute, or use a regular backing bean that resubmits to the container behind the scenes, or suchlike). Apparently the main problem with this is that they can't validate in the login form. Now, maybe it's just me, but it seems to me that if the username and/or password are wrong (including empty fields), the only answer you need is that the login failed...being able to pop up a nice message in red that a password is required is really sweet, but I imagine most users can work that one out for themselves. If necessary the login error page can provide a few tips.
In any case, a very common model in web applications is to dispense with FORM-based login, in the standard sense, entirely, and have a JSF form (possibly complex) that does have the username/password fields, and a JSF login action on a backing bean. The login method eventually ends up calling the container authentication programmatically, plus a whack of other things like redirecting based on role.
It strikes me as a bit silly to want a rich JSF login screen based on the 'j_security_check' model, but that's what a lot of people want.
Authorization
One of the things that a developer typically wants to do is to display or not display a UI component based on the security role of the authenticated user. For example, one user may only be able to view certain information on a page, but another might be able to edit certain items. Being able to control 'rendered' and 'disabled' attributes based on role is pretty handy.
This is actually not so difficult to do. It's merely that there are no security-specific attributes on standard JSF tags, although some JSF extensions do have them (MyFaces, ICEFaces, ACEGI). The JSF Security Project is looking (looked?) at making this kind of information available through EL.
Until such a thing is completely standardized it's just as easy to roll your own, unless you're already using MyFaces or IDEFaces or ACEGI. I certainly wouldn't pull in any of those only for this purpose...for example, adopting ACEGI means adopting Spring. Note also that there can be many quirks...if authenticating with JAAS you may have issues using the ICEFaces authorization attributes, and if mixing frameworks...well, sometimes they don't mix well, and sometimes they do (Tomahawk and ICEFaces don't cooperate on a single page).
Summary
In the J2EE world right now, we still spend too much time on implementing security. The requirements of 95%+ of developers in this area are simple and they are constant, and yet we tend to re-invent the wheel. As a development shop you can certainly reinvent once, and then re-use many times, but it would be nice if you never had to re-invent. What's still missing is simple off-the-shelf J2EE/JSF security solutions.
Subscribe to:
Posts (Atom)