On/Off, C#, and Ternary Logic
This past week I've been working on a step sequencer built in Silverlight. One of the requirements was that a 'step' change to a different color when it is active ( an on/off switch ). The simplest solution is this piece of code:
if (currentStatus == on)
{
status = off
}
else
{
status = on
}
While this works, it can be made more elegant using a ternary operator, and rewritten with just one line of code:
status = currentStatus == on ? off : on;
which in my case translates to:
myButton.Background = currentBrush.Color == greenBrush.Color ? blueBrush : greenBrush;
Again, this just says, if the current brush is green (currentBrush.Color == greenBrush.Color) make the background (myButton.Background) blue, else make it green.
Design Patterns 101
Principles
1) Program to an interface rather than an implementation.
2) Composition and delegation result in runtime flexibility and should be favored to inheritance.
3) Find out what varies and encapsulate it.
Types of Patterns
:: Creational (factory, prototype, singleton)
:: Structural (adapter, proxy, façade)
:: Behavioral ( State, Visitor, Template Method, Strategy)
Notes
- Good when used correctly
- Bad when used like hammer with no nails