Tutorial :Useful mini patterns (not design patterns)



Question:

My most used mini pattern is:

VideoLookup = new ArrayList  { new ArrayList { buttonVideo1, "Video01.flv" },                                 new ArrayList { buttonVideo2, "Video02.flv" },                                 new ArrayList { buttonVideo3, "Video03.flv" },                                  new ArrayList { buttonVideo4, "Video04.flv" },                                 new ArrayList { buttonVideo4, "Video04.flv" }                               };  

This means that rather than a switch statement with a case for each button I can instead just compare the button that was clicked with each item in the ArrayList. Then when I've found a match I launch the correct file (although the action that's the 2nd part the "lookup" could be a delegate or anything else).

The main benefit is that I don't have the problem of remembering to add all the correct code for each switch statement case, I just add a new item to the lookup ArrayList.

(Yes I know using an ArrayList isn't the best way to go, but it's old code. And I know that looping through an array each time isn't as efficient as using a switch statement, but this code isn't in a tight loop)

Does anyone else have any mini-patterns they use that save time/effort or make code more readable? They don't have to just be GUI related.

Update: Don't copy this code, I knew it was bad, but I didn't realise how bad. Use something like this instead.

Hashtable PlayerLookup = new Hashtable();  PlayerLookup.Add(buttonVideo1, "Video01.flv");  PlayerLookup.Add(buttonVideo2, "Video02.flv");  PlayerLookup.Add(buttonVideo3, "Video03.flv");  PlayerLookup.Add(buttonVideo4, "Video04.flv");    string fileName = PlayerLookup[currentButton].ToString();              


Solution:1

You could just create a struct or object that has a button reference and a string representing the file name and then a List of these things. Or, you could just use a Dictionary and make it even easier on yourself. Lots of ways to improve. :)


Solution:2

please please please omg use this version.

VideoLookup = new Dictionary<Button, string> {      { buttonVideo1, "Video01.flv" },      { buttonVideo2, "Video02.flv" },      { buttonVideo3, "Video03.flv" },       { buttonVideo4, "Video04.flv" },      { buttonVideo4, "Video04.flv" }  };  


Solution:3

On the subject of switches, I write this kind of thing a lot:

public Object createSomething(String param)  {      return s == null                          ? new NullObject() :             s.equals("foo")                    ? new Foo() :             s.equals("bar")                    ? new Bar() :             s.equals("baz") || s.equals("car") ? new BazCar() :                                                  new Object();  }  

I think it looks more readable compared to regular switch statements and has the ability to have more complex comparisons. Yeah, it'll be slower because you need to compare each condition but 99% of the time that doesn't matter.


Solution:4

In Java, I sometimes find that private inner classes which implement a public interface can be very helpful for objects composed of tightly-coupled elements. I've seen this mini-pattern (idiom) discussed in the context of creating UIs with Allen Holub's Visual Proxy architecture, but not much beyond that. As far as I know it doesn't have a name.

For example, let's say you have a Collection interface that can provide an Iterator:

public interface Collection  {    ...      public Iterator iterate();  }    public interface Iterator  {    public boolean hasNext();    public Object next();  }  

If you have a Stack that implements Collection, then you could implement its Iterator as a private inner class:

public class Stack implements Collection  {    ...      public Iterator iterate()    {      return new IteratorImpl();    }      private class IteratorImpl implements Iterator    {      public boolean hasNext() { ... }      public Object next() { ... }    }  }  

Stack.IteratorImpl has complete access to all of Stack's private methods and fields. At the same time, Stack.IteratorImpl is invisible to all except Stack.

A Stack and its Iterator will tend to be tightly coupled. Worst case, implementing Stack's Iterator as a public class might force you to break Stack's encapsulation. The private inner class lets you avoid this. Either way, you avoid polluting the class hierarchy with something that's really an implementation detail.


Solution:5

In my last job I wrote a C# version of the Enforcements concept introduced in C++ by Andrei Alexandrescu and Petru Marginean (original article here).

This is really cool because it lets you interweave error handling or condition checking in with normal code without breaking the flow - e.g.:

  string text = Enforce.NotNull( myObj.SomeMethodThatGetsAString(), "method returned NULL" );  

This would check if the first argument is null, throw an EnforcementException with the second argument as the message if it is, or return the first argument otherwise. There are overloads that take string formatting params too, as well as overloads that let you specify a different exception type.

You could argue that this sort of thing is less relevant in C# because the runtime checking is better and already quite informative - but this idiom lets you check closer to the source and provide more information, while remaining expressive.

I use the same system for Pre and Post condition checking.

I might write an Open Source version and link it from here.


Solution:6

for when I'm churning out code fast (deadlines! deadlines! why am I on stackoverflow.com? deadlines!), I wind up with this kind code:

Button1.Click += (o,e) => { DoSomething(foo); };  

Will this cause me memory leaks at some point? I'm not sure! This probably deserves a question. Ack! Deadlines!


Solution:7

For Windows forms I'll often use the Tag field to put a psuedo-command string so that I can have a single event handler for a shared set of buttons. This works especially well for buttons that do pretty much the same thing but are parameterized.

In your first example, I would set the Tag for the buttons equal to the name of the video file -- no lookup required.

For applications that have some form of text-based command processor for dispatching actions, the Tag is a string that is just fed into the command processor. Works nice.

(BTW: I've seen the term "idiom" used for mini-patterns...)


Solution:8

A new idiom that I'm beginning to see in C# is the use of closure parameters that encapsulate some configuration or setup that the method will need to function. This way, you can control the relative order that code must run from within your method.

This is called a nested closure by Martin Fowler: http://www.martinfowler.com/dslwip/NestedClosure.html


Solution:9

Perhaps there's already a better way of doing this (vbEx2005/.Net2.0), but I've found it useful to have a class of generic delegate-creators which accept a method that takes some parameters, along with the values of either all, or all but one, of those parameters, and yields a delegate which, when invoked, will call the specified function with the indicated parameters. Unlike ParamArray-based things like ParameterizedThreadStart, everything is type-safe.

For example, if I say:

  Sub Foo(param1 As Integer, param2 As String)      ...  End Sub    ...    Dim theAct as Action(of Integer) = _        ActionOf(of Integer).NewInv(AddressOf Foo,"Hello there")      theAct(5)  ...

the result will be to call Foo(5, "Hello there") on object where Foo was declared. Unfortunately, I end up having to have separate generic classes and methods for every different number of parameters I want to support, but it's nicer to have all the cut-and-paste in one file than to have extra code scattered about everywhere to create the appropriate delegates.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »