views:

1022

answers:

9

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();
+3  A: 

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. :)

BobbyShaftoe
+3  A: 

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.

Outlaw Programmer
In C# you can just use System.Activator.CreateInstance to do this...
Jason Punyon
hmm...maybe not the bazcar line...
Jason Punyon
I used this too, but I've found this doesn't work in PHP, ?: must not have low enough precedence or something..
Kip
Switch statements (at least in Java) are limited to integrals, so the only choice in this case would be to use "if-else" conditionals, comparing each condition one at a time, like its done.
Mystic
I don't see how that is more readable than an already well known construct (the switch statement).
Ed Swangren
@Ed - I agree it's not more readable, nor more efficient, but it _is_ more compact.
NVRAM
This is not the proper way to go about this. You should look into the Factory pattern.
monksy
+1 I'm also using this kind of ?-operator-switches all the time. They are the best. We might be a minority though. :)
AareP
A: 

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...)

Jeff Kotula
I don't think that binding your control tags to something that's so prone to change as a file name is a good idea. In fact, it's a really bad idea, unless you know for a fact that that's never gonna change, but still...
Trap
Attaching it to a tag is no more brittle than the original choice of encoding it in a switch statement. I presumed that the filenames were fixed -- or compiled-in resources.
Jeff Kotula
+2  A: 

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.

Phil Nash
+3  A: 

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.

Rich Apodaca
A: 

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

Jordão
+3  A: 

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" }
};
Jimmy
A: 

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!

Jimmy
what language is this code snippet even in?
Andrew
C# .................
Jimmy
This isn't much of a memory leak. Yes, the compiler-generated closure class will remain alive as long as the button does, but it's trivial overhead and the memory will be reclaimed properly when the button is collected.
MikeP
A: 

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.

supercat