Archive for .NET

I get it – pun intended

Posted in Design Issues with tags , , , , , , , , , , , , on July 8, 2008 by moffdub

Going back to The Getter Setter Debate, I knew that, like most things you learn in software, you don’t really get it until you do it. And seeing examples that are convenient, simple, and complex enough to illustrate a situation is nice for reference, but, for me, it doesn’t stick until I have to use the new knowledge in my own situation.

You might remember such gems as these:

account.appendTransactionTo(statement);
statement.appendTransactionsFrom(account);
Money total = …;
Money amount = …;
total.increaseBy( amount );

What they all have in common is that they read like English sentences: “Hey account, append transaction to statement”. They surely get the point across to the reader, but like writing a compiler, until you do it yourself, you don’t get it.

The epic Martin Fowler book, Refactoring, was the second required reading in the course that also introduced me to Evans’ Domain-Driven Design and changed the way I think about software. While not as impactful on the impressionable me of a mere year ago, the Fowler book is brimming with code examples.

One code smell, among many, to which I have since become cognizant, is the Message Chain smell:

You see message chains when a client asks one object for another object, which the client then asks for yet another object, which the client then asks for yet another object, and so on. You may see these as a long line of getThis methods, or as a sequence of temps. Navigating this way means the client is coupled to the structure of the navigation. Any change to the intermediate relationships causes the client to have to change.

Coupling? getThis? Ding ding ding. This smell sounds like it can guide me in recognizing where I can eliminate the use of getters as much as possible. The remedy Fowler prescribes is to Hide Delegate:

The move to use here is Hide Delegate (157). You can do this at various points in the chain. In principle, you can do this to every object in the chain, but doing this often turns every intermediate object into a middle man.

Ah – this can hopefully help me limit getters in my real world projects that aren’t perfectly simple, complex, convenient, and plain just right like the examples that are given.

In my recent re-implementation of core parts of The Project in C#, I unconsciously wrote code like this:

IEnumerable query = from d in db
where d.getTitleForInfra().Contains(title) &&
d.getLifecycleCommentsForInfra().Contains(comments) &&
d.getLifecycle().Contains(lifecycle) &&
d.getDirectorForInfra().Contains(director)
select d;

and this:

public bool isIn(Room r)
{
return this._history.getRoomForInfra().Equals(r);
}

One night, like the Satanic hallucinations the Marine in Doom 3 experiences, the vision came to me:

IEnumerable query = from d in db
where d.titleContains(title) &&
d.lifecycleCommentsContain(comments) &&
d.lifecycleContains(lifecycle) &&
d.directorContains(director)
select d;

public bool isIn(Room r)
{
return this._history.roomEquals(r);
}

I grant you that these improvements are relatively minor, but the benefits are the same: clients are now coupled to only the class they are using. Also, these lines of code kind of read like sentences too: “… where d’s title contains the title”. If I had made prodigious and conscious use of my variable names, the English would be even more pleasing.

As far as keeping the server objects from becoming middle men, I don’t run that risk here. In the first example, d is of type DVD, which is a domain object. Similarly, _history in the second example is of type EquipmentHistory, also a domain object. They both contain useful domain knowledge, so they aren’t mere forwarders of messages.

Know your refactoring catalog. Many seemingly hot design debates in the industry might actually be recycled from yesterday, and we can all use a reminder. It seems that fashion and bad design are both cyclical.

Method Regulator Pattern

Posted in Design Issues with tags , , , , , , , , , , on July 1, 2008 by moffdub

(skip ahead to download here)

This blog’s thusfar most popular post, The Getter Setter Debate, spawned this comment from Wolter:

“Just put them in the same package and set them to package-private.
Or put warnings in the API documentation that the getters/setters are for internal use only, and are likely to change.”

While this is a viable solution, I strive for maximal generality. Granted, Java and .NET support the concept of package or “friend” access. Even so, this is language and/or platform dependent, and it can force some awkward package organization in some situations.

Since the thought-provoking idea of avoiding getters occurred to me, I’ve come to the following conclusion: yes, they should be avoided as much as possible, but no, you can’t avoid them completely. They are needed for legitimate uses, such as UI mapping and persistence.

And now, the natural question arises: if you are on a large team, how do you enforce this policy?

There is the possibility of manual intervention. Indeed, many teams employ code reviews and walkthroughs, and every instance of an accessor method being used can be scrutinized. A small example of domain-driven design called TimeAndMoney takes this approach in the file Money.java:

 /**
* How best to handle access to the internals? It is needed for
* database mapping, UI presentation, and perhaps a few other
* uses. Yet giving public access invites people to do the
* real work of the Money object elsewhere.
* Here is an experimental approach, giving access with a
* warning label of sorts. Let us know how you like it.
*/
public BigDecimal breachEncapsulationOfAmount() {
    return amount;
}

public Currency breachEncapsulationOfCurrency() {
    return currency;
}

Certainly, as the author of this class, you are discouraging other developers from using a method in their code with the substring “breachEncapsulation”. And giving the power to the class author is a step in the right direction.

Approach

But you know me. I’m never happy with anything. I’m especially not content with relying on others to behave. It rarely works.

This got me thinking of a pattern-based solution, one where only certain classes are authorized to use another class’s getters and setters, and violation of such would cause run-time problems like exceptions.

I began tinkering around with this approach and came up with the Method Regulator Pattern:

The heart of this setup is the Regulator. It keeps track of a type that is being regulated and a list of types that are authorized to use regulated methods of that type.

What is a regulated method? It is up to the class that wants to be regulated to, first off, inherit from the Regulated Object class, and second, call the inherited authorizeCaller method as the first statement in every method that should be regulated.

The Regulated Object base class uses the process-global Regulated Types class to look up all of the Regulators for the class that called authorizeCaller, including those inherited from base classes and interfaces. Then, for each Regulator, if at least one of them authorizes the method call, the authorization succeeds. Otherwise, indicate failure somehow, like with an exception.

The burning question remains: how does authorizeCaller know the type of the caller? This will depend on your platform, but your platform must have some kind of reflective capability. Both Java and .NET support the ability to query the activation stack: getStackTrace in Java and StackTrace in .NET.

Example

I would never be one to just describe something very abstractly, wave my hands at it, and declare that it works. What am I, a professor? I went ahead and implemented this pattern in C#. You can download it here. Included is a set of NUnit tests.

Another burning question: what prevents some mischievous or misinformed coder from highjacking an instance of a Regulator, twiddling with it to allow access to a specific type to their new class, and rendering this scheme impotent?

This is an implementation issue, and I chose to deal with it by providing methods to close or “lock” a regulator once we’re finished authorizing types. I also do the same for trying to replace an entire Regulator for a given type with a new Regulator.

Some of you are confused. I’m confused as well. I think an example will clear up what is going on.

Suppose you have the following relatively complicated class hierarchy of five classes, each of which has some getters that you’d like to regulate:

Attached to each class in that diagram is a note indicating which classes are allowed to call getters on each class. It is important to note that authorized callers in a base class should be inherited by a subclass to preserve the Liskov Substitution Principle.

Speaking of which, suppose there are five calling classes like so:

Therefore, the classes authorized to use the accessors of class Sub1 are Caller2, Caller1, and Caller5, the latter two inherited. Also, since Caller3 and Caller4 implement Interface1, we could just as easily authorize Interface1 for Sub3 instead of the two classes individually.

Here is some code for setting up who can call accessors on who:

public void Setup()
{
MethodAccessRegulator superReg = new MethodAccessRegulator(typeof(Super));
superReg.addAuthorizedType(typeof(Caller1));
superReg.closeRegulator();

RegulatedTypes.addRegulatedType(superReg);

MethodAccessRegulator sub1Reg = new MethodAccessRegulator(typeof(Sub1));
sub1Reg.addAuthorizedType(typeof(Caller2));
sub1Reg.closeRegulator();

RegulatedTypes.addRegulatedType(sub1Reg);

MethodAccessRegulator subInterfaceReg = new MethodAccessRegulator(typeof(SubInterface));
subInterfaceReg.addAuthorizedType(typeof(Caller5));
subInterfaceReg.closeRegulator();

RegulatedTypes.addRegulatedType(subInterfaceReg);

MethodAccessRegulator sub2Reg = new MethodAccessRegulator(typeof(Sub2));
sub2Reg.addAuthorizedType(typeof(Caller2));
sub2Reg.closeRegulator();

RegulatedTypes.addRegulatedType(sub2Reg);

MethodAccessRegulator sub3Reg = new MethodAccessRegulator(typeof(Sub3));
sub3Reg.addAuthorizedType(typeof(Caller3));
sub3Reg.addAuthorizedType(typeof(Caller4));
sub3Reg.closeRegulator();

RegulatedTypes.addRegulatedType(sub3Reg);
}

Here is some code for Super:

public class Super: MethodAccessRegulatedObject
{
private int _x;

public int x
{
get
{
authorizeCaller(this);
return _x;
}
}
}

Boring; only one member to protect, but it gets the point across.

Now if, say, Caller2 is defined in this way:

public class Caller2
{
public void useSub1()
{
int i = (new Sub1()).x;
}

public void useSub2()
{
int i = (new Sub2()).z;
}

// inherited access
public void useSub3()
{
int i = (new Sub3()).x;
}

// should throw exception
public void useSuper()
{
int i = (new Super()).x;
}
}

and then we use Caller2 like this:

public void TestSingleInheritance()
{
(new Caller2()).useSub1();
(new Caller2()).useSub2();

try
{
(new Caller2()).useSuper();
Assert.Fail();
}
catch (MethodAuthorizationException ex)
{
Console.WriteLine(ex.Message);
}
}

the first two calls will succeed, while the second one will throw a MethodAuthorizationException with message “An object of type Caller2 attempted an unauthorized method call on class Super”.

Catches

  • First, we make use of this StackTrace class, and we kind of assume where we are in the stack. This approach, as I have implemented it, breaks if you build the download in Release mode, because calls to InvokeMethodFast are inserted instead of the actual calling class.
  • Second, a much better way for client classes to declare their desire to be regulated would be to use Aspect-Oriented Programming. I do not have experience with AOP yet, so this is a future enhancement. I also wanted a lightweight approach for the blog, instead of telling you to download something like NAspect.
  • The “locking” aspect mentioned above (all the code in that Setup() function) is only effective if you can, within your organization, centralize the creation and instantiation of the Regulated Types object and the constituent Regulators.
  • Finally, all of this has to happen within a single process, though I think if you are distributing your objects, you might have more pressing problems.
  • This entire scheme might be rendered impotent by reflection.

I look forward to some feedback on the practicality, usability, and security of this approach.

WinForms DataGrid Pagination in .NET 1.1 (with highlighting)

Posted in .NET with tags , , , , , , , on June 25, 2008 by moffdub

(download at the end of this post)

Problem

Believe it or not, there are still poor souls out there stuck with antiquated equipment. In the previous post on highlighting DataGrid rows, I recounted a situation in which I found myself needing to implement myself a feature in .NET 1.1 that is easy in .NET 2.0 or above.

To summarize, instead of handling an event, I had to go down a much pricklier path:

  • Via polymorphism and event-handling dexterity, enable arbitrary highlighting of rows in a DataGrid.
  • Force the colored rows to behave when sorting on any column.
  • Mourn the fact that for relatively large DataSets, the re-coloring of rows after a sort is a performance problem, the solution of which is to implement paging.

To the best of my knowledge, paging a System.Windows.Forms DataGrid is not supported in any version of .NET.

Solution

When I started thinking about this post on Monday, I was just going to outline possible solutions:

  • Out-of-memory paging: hit your data source as the user pages through data, only loading pages that need to be loaded for viewing
  • Out-of-memory paging with cache: same as above except load the current page, previous page, and next page
  • In-memory paging: load entire DataSet and page in memory

Upon first encountering the problem while on The Project, my first instinct was either of the first two options. While considering the solution on Monday, this did not change.

But I have since become much more wise and lazy since The Project ended, and honestly, I don’t like writing so much code, because bugs will surely follow. The first two solutions are not ideal because they involve knowing what your data source is and most likely changing to accommodate extra parameters to indicate how many records to fetch for a given query.

In The Project’s case, SQL Server inexplicably does not allow you to use a stored procedure in a FROM clause. So to do any out-of-memory paging would require changes to the s-procs.

Then, to maintain proper layering, report services and repositories would have to change for the same reason. Add caching to the mix and this is a minor headache.

Finally, out-of-memory paging would be good for performance problems related to the size of the DataSet. No such problem existed, so tackling it at this point would be over-engineering.

So, I settled on in-memory paging. At first I was only going to outline the solution with UML and a half-hearted code example. As usual, I wrote the example first. Then I looked deep into its eyes. And just like that episode of Seinfeld where Jerry shaves his chest:

Jerry: I did something stupid.

Kramer: What did you do?

Jerry: Well I was shaving. And I noticed an asymmetry in my chest hair and I was trying to even it out. Next thing I knew, (high pitched voice) Gone.

one thing led to another, half a day of coding and debugging led to two days, and at the end of this post you can download a WinForms DataGrid Pagination demo.


(red is the highlighting color here)

Since you can download the VS project in all its glory, I will only list the PaginatedDataGrid interface:

namespace System.Windows.Forms
{
public interface PaginatedDataGrid
{
uint pageSize
{
set;
}

void moveToNextPage();
void moveToPrevPage();
void moveToFirstPage();
void moveToLastPage();
bool canMoveBack();
bool canMoveForward();
String getCurrentPaginationInfo();
void sort(int col, bool descending);
}
}

This is supposed to be self-explanatory. The only thing that would need to be explained is that the PaginatedDataGrid is a wrapper around an existing DataGrid, and that DataGrid must use a DataSet as its DataSource. Hence, the download contains only one implementation of this interface. If I ever wanted this code up on CodeProject, I’d implement the remaining five.

PaginatedDataGrid is a bit like the Decorator pattern in that it can be turned on and off at run-time, save the exact inheritance structure of the actual pattern.

Also, you’ll notice this example in C# instead of the usual VB. I have started re-implementing the core of The Project in my spare time so I can fix all of the ridiculous design mistakes I made, practice TDD, and learn C#.

Usage

I wrote this example in .NET 3.5. It is ready to run, except you need to provide your own DataSet, however you wish to do so. I did it through SQL Server and I left the boilerplate code for that route in the demo if you choose to do so.

Checking the “Pagination on” checkbox will turn the feature on and off so you can see the performance problem I was facing. You can also choose your own page size by entering a valid positive integer (I didn’t sanity-check this field so be nice) and tabbing off the textbox.

Comments

Here is a sampling of the interesting bugs I had to destroy:

  • When moving from page to page, sometimes page P’s first row, if to be highlighted, wouldn’t be highlighted until you either moved to page P+1 or highlighted the rows twice.
  • Getting a truly “deep copy” of the rows of the initial DataSet proved to be more of a challenge than it should’ve been.
  • Adding those rows back to the DataTable of the DataSet had to be accomplished with a new object array because you can’t create a new DataRow and can’t add the existing one because of an ArgumentException that I didn’t feel like dealing with.
  • Sorting on a page would only sort that page, when it should sort the entire DataSet and then reload the page you’re on for that DataSet.

Download

ZIP file can be downloaded here. Any feedback is much appreciated.

Follow

Get every new post delivered to your Inbox.