I'm plan to make a page that displays info about user's in the form of a table. Each column will be a property of the table. I want someone viewing the table to be able to choose ways to filter the users. There will be two check boxes: 1 for reported users and 1 for creation date. I'm planning to make an enum called UserFilter like so:
public enum UserFilter
{
None = 0,
Date = 1,
Reported = 2
}
If I need to add another type it's value will be set to 4 so that I can tell which enums are selected through a bitwise or (3 would be both 1 and 2). The problem I'm having is with reading in an enum from the query string. I guess I could do something like posting back with an int (0 for none, 1 for date, 2 for report, 3 for both) but I would like to try posting back with the actual string. I'm not sure how I would parse "Date|Reported" into an enum value that doesn't exist in UserFilter.
In a nutshell: Is there a clean way to parse "Date|Reported" into the value 3 without adding another value to my enum?
You could try something like
string enumString = "Date|Reported";
UserFilter uf = enumString.Split('|').ToList().Select(e =>
{
UserFilter u;
Enum.TryParse(e, true, out u);
return u;
}).Aggregate((u, c) => u = u | c);
I would however recomend that you change your enum to
public enum UserFilter
{
None = 1,
Date = 2,
Reported = 4
}
as if you have it your way None|Date is the same as Date, because 0 + 1 => 1
EDIT
As #ScottSelby stated, this would also work
UserFilter u = (UserFilter) 3;
//or 6 rather than 3 if you take my comment above into consideration
Currently I have 4 permissions in my website
Edit
Delete
Add
View
Everyone gets view permissions when someone subscribes to someone else.
Currently in I store each as a column in my database as a bit value.
I am thinking maybe I should use enum with flags but I have some questions.
The user will be able to choose the users permissions(eveyone gets view you cannot take that away). Right now it is easy as I use a checkbox and then save the bool value to the db.
My questions is what is the best way to convert checkboxes to the enum type? So if they choose add permission I can map that to the right enum type.
Wondering if there is a better way then
PermissionTypes t;
if(add == true)
{
t = PermissionTypes.Add
}
if(edit == true)
{
t += PermissionTypes.Edit // not sure if you even can do this.
}
I know with enum flags you can use the pipe and do something like this
PermissionTypes t = PermissionTypes.Add | PermissionTypes.Edit
I am wondering is it good practice to have another type in my enum like
AddEdit = Add | Edit
I am thinking that can result in many combinations(imagine if I had like 10 permissions or something like that).
Enums are simply integers values. By settings your enum values to different power of 2, you can easily have any combination you need:
enum ePermissions
{
None = 0,
View = 1,
Edit = 2,
Delete = 4,
Add = 8,
All = 15
}
ePermissions t;
t = (ePermissions)((add?ePermissions.Add:ePermissions.None) | (delete?ePermissions.Delete:ePermissions.None) | ...);
if you want to know if some user has the Add permission just do as follow:
canAdd = (currentPermission & ePermissions.Add) != 0;
On converting set of bool values to enum - for small set if would be ok. You can also use ?: operator to do the same in smaller number of lines:
[Flags]
enum Permissions
{
None = 0,
View = 1,
Edit = 2,
Delete = 4,
Add = 8,
}
var permissions =
(add ? Permissions.Add : Permissions.None) |
(edit ? Permissions.Edit : Permissions.None) |
(delete ? Permissions.Delete : Permissions.None);
If you have large number of values some sort of mapping of Control to Enum may be useful.
On AddEdit - this particular on is probably not useful. You can as easily write Add | Edit. Some menaingful combinations of permissions (or falgs) may be named specifically if code will use such combination in meanigfull way. I.e. CanModify = Add | View.
I'm writing some decision-making AI for a game, and I've come up with the following piece of code.
if(pushedLeft && leftFree && leftExists)
GoLeft();
else if(pushedRight && rightFree && rightExists)
GoRight();
else if(leftFree && leftExists)
GoLeft();
else if(rightFree && rightExists)
GoRight();
else if(pushedLeft && leftExists)
GoLeft();
else if(pushedRight && rightExists)
GoRight();
else if(leftExists)
GoLeft();
else if(rightExists)
GoRight();
// else do nothing...
That's a pretty long stream of if statements, with similar conditionals!
Note that it makes this nice pattern:
L1 L2 L3 -> L
R1 R2 R3 -> R
L2 L3 -> L
R2 R3 -> R
L1 L3 -> L
R1 R3 -> R
L3 -> L
R3 -> R
(nothing) -> 0
The aim of this code is to decide whether the object should move left or right (or not at all), based on some incoming state information. Each piece of information has a different priority. I could write it in an ordered list like this:
Highest Priority
----------------
Don't ever move into an invalid space
Prefer to move into an unoccupied space
Prefer to move in the push direction
Prefer to move left
----------------
Lowest Priority
It seems obvious that adding additional information inputs upon which to make this decision will double the number of conditionals. And doubling the number of potential values for those inputs (eg: allowing up/down/left/right) will double the number of conditionals as well. (So this is n×m2 conditionals, right?)
So my question is:
Is there a nice, satisfying, elegant way to code this?
I'm thinking that there must be a nice "n×m" way to do it (edit: I had "n+m" here originally, but that seems impossible as there are n×m input conditions). Something that is applicable to both my code here, and to the problem in general?
Preferably something that will perform just as well or better than the conditional version above. Ideally something that avoids heap allocations - important for use in game development scenarios (although these can always be optimised away with caching and the like, if necessary).
And also: Are there any "Googleable terms" for this problem? I suspect that this is not an uncommon problem - but I don't know of a name for it.
Update: An idea thanks to Superpig's answer, is to calculate a score for the various options. Something like this:
int nothingScore = 1 << 4;
int leftScore = (1 << 1) + (pushedLeft ? 1 << 2 : 0) + (leftFree ? 1 << 3 : 0) + (leftExists ? 1 << 5 : 0);
int rightScore = (pushedRight ? 1 << 2 : 0) + (rightFree ? 1 << 3 : 0) + (rightExists ? 1 << 5 : 0);
There's certianly a nicer way to write the scoring code (and alternate ways to score it, too). And then there's still the matter of selecting what to do once the score is calculated. And, of course, there may be a better method entirely that doesn't involve scoring.
Update 2: I've posted and accepted my own answer here (because Superpig's isn't a complete solution, and so far no other answer is even remotely on the right track). Rather than scoring the various outputs, I've chosen an option-elimination approach using a bit-field. This allows a decision to be made using only a single integer for memory.
This is essentially a classification problem; you want something like a decision tree (or behaviour tree). You're trying to take a bunch of discrete inputs for the situation (validity, freeness, push direction, etc) and classify the result as "up, down, left or right."
I suspect that if you want something of greater or equal performance to the long chain of if statements - at least in terms of instruction count / number of comparisons done - then you will have to make your comparisons in the manner you're doing there. Approaches like calculating a score for all directions and then checking the maximum, or recursively partitioning a list of moves into preferred and non-preferred, will all end up doing more work than a pure comparison sequence.
You could just build a lookup table, I think. You've got 4 bits indicating whether a direction is valid, 4 bits indicating whether a direction is occupied, and 2 bits indicating the push direction, for 10 bits in total - so that's 1024 different situations, and the behaviour in each one can be described with just 2 bits (so, 1 byte) - making the total table size 1024 bytes.
A single entry would be a structure like this:
union DecisionSituation
{
unsigned short Index;
struct
{
bool ValidLeft : 1;
bool ValidRight : 1;
bool ValidUp : 1;
bool ValidDown : 1;
bool OccupiedLeft : 1;
bool OccupiedRight : 1;
bool OccupiedUp : 1;
bool OccupiedDown : 1;
Direction PushDirection : 2;
} Flags;
}
You'd describe your situation by filling out the flags in that structure, and then reading the 'Index' value to get your lookup table index.
Edit: Also, regarding your scoring function, because you're doing strict bit-patterns, I think you can skip all the ternary operators:
int leftScore = (leftExists << 4) | (leftFree << 3) | (pushedLeft << 2) | 1;
int rightScore = (rightExists << 4) | (rightFree << 3) | (pushedRight << 2) | 0;
// Find the highest scoring direction here
// If none of the scores are at least (1 << 4) it means none of them existed
if(highest score < (1 << 4)) return nothing;
// otherwise just return the highest scoring direction
The most important thing is to have the code that declares what the inputs are and their relative priorities be simple, short and elegant. Here is one way to write that code:
PreferencedDecisionMaker pdm = new PreferencedDecisionMaker();
pdm.Push(false, leftExists, rightExists, upExists, downExists);
pdm.Push(0);
pdm.Push(false, leftFree, rightFree, upFree, downFree );
pdm.Push(false, pushedLeft, pushedRight, pushedUp, pushedDown);
pdm.Push(1);
switch(pdm.Decision)
{
case 1: GoLeft(); break;
case 2: GoRight(); break;
case 3: GoUp(); break;
case 4: GoDown(); break;
}
Here the inputs are declared in essentially a tabular format. The priority of each input is defined by the ordering of the rows. Each column corresponds to a possible output.
The "complexity" of this code is n×m.
(Although I've used indentation to make this look like a table, more complicated input conditions won't allow each row to exist neatly on a single line. This doesn't matter: the important bit is that there are only n×m declarations. Being able to make it look like a table when the conditions are short is just a nice bonus.)
Less important is the actual behind-the-scenes code to make the decision (the PreferencedDecisionMaker type). There are a few ways to calculate the best output decision based on priority. Superpig suggested scoring, which is good. But I've ended up going for an option-elimination approach using a bit-field. I've posted my code for this below.
Using a bit-field has the big advantage of not needing to allocate heap memory for arrays. The only downside is that it's limited to 32 options.
The following code hasn't been thoroughly tested. And I haven't filled out all 32 versions of the Push method. It uses a mutable struct, which is "naughty" - converting it to an immutable struct should be straightforward. Or you could make it a class - but then you lose the benefit of avoiding heap allocation.
struct PreferencedDecisionMaker
{
private uint availableOptionsBits;
private static readonly int[] MultiplyDeBruijnBitPosition = {
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
public int Decision
{
get
{
uint v = availableOptionsBits;
// Find position of lowest set bit in constant time
// http://stackoverflow.com/a/757266/165500
return MultiplyDeBruijnBitPosition[((uint)((v & -v) * 0x077CB531U)) >> 27];
}
}
private void InternalPush(uint preference)
{
if(availableOptionsBits == 0)
availableOptionsBits = preference;
else
{
uint combinedBits = availableOptionsBits & preference;
if(combinedBits != 0)
availableOptionsBits = combinedBits;
}
}
public void Push(int option)
{
if(option < 0 || option >= 32) throw new ArgumentOutOfRangeException("Option must be between 0 and 31");
InternalPush(1u << option);
}
// ... etc ...
public void Push(bool p0, bool p1, bool p2, bool p3, bool p4) { InternalPush((p0?1u:0u) | ((p1?1u:0u)<<1) | ((p2?1u:0u)<<2) | ((p3?1u:0u)<<3) | ((p4?1u:0u)<<4)); }
// ... etc ...
}
When you have a bunch of if statements, usually they can be refactored using polymorphism combined with the state pattern:
As an introduction, please watch the following video from Misko Hevery (you will love it)
http://www.youtube.com/watch?v=4F72VULWFvc&feature=player_embedded#!
This is a summary from the presentation:
Most if's can be replaced by polymorphism (subclassing)
This is desirable because:
Functions without ifs are easier to read than with ifs
Functions without ifs are easier to test
Related branches of ifs end up in the same subclass
Use Polymorphism (Subclasses)
If you are checking an object should behave differently based on its state
If you have to check the same if condition in multiple places
Use if
Bounds checking primitive objects (>,<, ==, !=)
... other uses but today we focus on avoiding if
Polymorphic solution is often better because
New behavior can be added without having the original source code
Each operation / concern is separated in a separate file
Makes it easy to test / understand
EDIT
At first sight using the state pattern with polymorphism, the solution would look more complex because it implies you will need more classes than before, but the trade-off is much much better, as long as you start writing tests for this kind of code you will find that's easier to test, easier to read and understand, and therefore, easier to maintain and extend (right now you just posted about movement to the right or left, but imagine if later you need to move up and down, if you do not refactor your code now, adding new functionality will be a real PITA)
You would have something like:
// represents the current position
class MyClass
{
public int X;
public int Y;
}
abstract class NodeMoving
{
abstract void Move();
abstract bool IsValid(MyClass myclass);
}
abstract class NodeMovingLeft : NodeMoving
{
override void Move()
{
// add code to move left
if(this.IsValid(MyClass myclass))
{
// move
}
}
}
abstract class NodeMovingRight : NodeMoving
{
override void Move()
{
// add code to move right
if(this.IsValid(MyClass myclass))
{
// move
}
}
}
// and then start modeling the different states
class RightFree : NodeMovingRight
{
override bool IsValid(MyClass myclass)
{
// add condition to validate if the right is free
}
}
// combining conditions
class PushedLeft : NodeMovingLeft
{
override bool IsValid(MyClass myclass)
{
// code to determine if it has been pushed to the left
}
}
class LeftFree : PushedLeft
{
override bool IsValid(MyClass myclass)
{
// get condition to indicate if the left is free
var currentCondition = GetCondition();
// combining the conditions
return currentCondition && base.IsValid(myClass);
}
}
You will need to add the properties needed in order to calculate the conditions and perform the movement
It's worth to note how small the methods are, (yes you will have more than before) but they can be tested in isolation really easy
Edit 2 -- adding priority
Well now that we have a simple state machine, we need to evaluate the priorities, one way to do it (and I would like to hear ways to improve it) is by using a priority queue:
http://www.codeproject.com/Articles/13295/A-Priority-Queue-in-C
It would look something like:
// you could place the priorities in a service to reuse it
var priorities = new HashSet<NodeMoving>();
priorities.Add(new RightExists());
priorities.Add(new PushedLeft());
var currentPosition = new MyClass { X = 1, Y = 2 };
foreach (var priority in priorities)
{
if (priority.IsValid(currentPosition))
{
priority.Move();
break;
}
}
// output is: RightExists
// now changing the priority order
foreach (var priority in priorities.Reverse())
{
if (priority.IsValid(currentPosition))
{
priority.Move();
break;
}
}
// output is: PushedLeft
Use the state pattern. Draw a state diagram that contains all your different states and the allowed transitions between them. When you code it have a state subclass for each node. Each state node / class will decide on the inputs and make drive the appropriate transition to the next allowed state. I don't think you can avoid the multiplicity of states you mention.
Would this not work:
if(!leftExists) {
if(rightExists) {
GoRight();
} else {
// Panic!
}
} else if(!rightExists) {
GoLeft();
} else if(rightFree || leftFree && !(rightFree && leftFree)) {
if(rightFree) {
GoRight();
} else {
GoLeft();
}
} else if(pushedRight) {
// Assumption: pushedLeft and pushedRight cannot both be true?
GoRight();
} else {
// PushedLeft == true, or we just prefer to move left by default
GoLeft();
}
Right now, it is a similar amount of code, but the difference being that we've eliminated the common conditions, so adding additional conditions no longer affects each branch - just insert it at the desired priority.
I'd stick with a modification of your solution.
Have you thought about making GoLeft into a function which also return whether or not left exists? Unless it's a complicated function, and you are calling this a LOT and testing shows that it needs to be optimized, that's what I'd do.
If you do that, then this becomes the following. It's basically what you're doing, but easier to read.
I'm sure I'll get downvotes for this since it's not OO and doesn't use the command pattern, but it does answer the question, and it is easy to read ;) For a more complicated problem, I'd think about using those answers, but for this particular problem, I would stick with a simple answer.
if(pushedLeft && leftFree && GoLeft()) ;
else if(pushedRight && rightFree && GoRight()) ;
else if(leftFree && GoLeft()) ;
else if(rightFree && GoRight()) ;
else if(pushedLeft && GoLeft()) ;
else if(pushedRight && GoRight()) ;
else if(GoLeft()) ;
else if(GoRight()) ;
// else do nothing...
To get a grip on this, i recommend the following measures:
decide which of the statements that are combined in the if statements weigh more
untangle the if statements, resulting in nested if statements like
if (moveRight)
{
if (pushedleft)
{
/// ...
}
}
when you have this, start packing all condidional logic into methods, e.g. HandleMoveRight
having done this, you can start extracting classes, ending up in a command pattern.
Now you have no more problems in adding extra functionality and complexity is flat.
I think the state pattern is the right approach as recommended by #john2lob. You also want some sort of decision tree approach to the determine the next transition on actions of the events 'push' / 'free' / 'exists'. BTW: what's the difference between 'free' and 'exists'?
The system have a plain enum like this,
public enum SomeEnum : short
{
Ok = 0,
Missing = 17,
};
This enum are now into a situation where I need to mask some more information into it without change the appearence of the existing enum values. The enum will got some new values,
[Flags]
public enum SomeEnum : short
{
Ok = 0,
Missing = 17,
Blocking = 18, // Values could be anything
Low = 19, // Values could be anything
};
I was afraid there could be problem to the current enum usage. It appears that I'm right, but I hope i'm proved wrong with your help. The usage until today are built around SomeEnum.Ok. Also tomorrow, but the Ok need additional info. I need to mask the enum values without affect it's current behavior, which could came from any common reference;
someEnumVariable.ToString()
(int)someEnumVariable
someVar = SomeEnum.Ok
Enum.Parse(typeOf(SomeEnum), someString)
If I flag the enum with
var test = (SomeEnum.Ok | SomeEnum.Blocking);
Both flags can be founded i.e. test.HasFlags(SomeEnum.Ok) or test.HasFlags(SomeEnum.Blocking) but the enum represents as SomeEnum.Blocking, which aren't possible.
Any ideas?
Because the value of SomeEnum.OK is 0, calling HasFlag(SomeEnum.OK) will always return true. When you mask enums together, the process relies on the fact that the sum of any combination of enum values will be unique. Typically you would set these up starting using values of 2^0, 2^1, 2^2, etc. For example:
[Flags]
public enum SomeEnum : short
{
Ok = 1,
Missing = 2,
Blocking = 4, // Values could be anything
Low = 8, // Values could be anything
}
If you want to mask the values together, you'll have to use the Flags attribute. If you can't refactor and change the value of SomeEnum.OK, then you may have to rely on passing in a SomeEnum[], rather than a single masked SomeEnum value.
EDIT
Just a quick note on masking the values together using the enum defined above. Take the following code:
var t1 = (int)(SomeEnum.OK | SomeEnum.Missing); //t1 = 1 + 2 = 3
var t2 = (int)(SomeEnum.Missing | SomeEnum.Blocking); //t2 = 2 + 4 = 6
var t3 = (int)(SomeEnum.OK | SomeEnum.Low); //t3 = 1 + 8 = 9
var t4 = (int)SomeEnum.OK; //t4 = 1
var s1 = (SomeEnum.Ok).ToString(); //s1 = "Ok"
var s2 = (SomeEnum.Ok | SomeEnum.Missing).ToString(); //s2 = "Ok, Missing"
When these items are OR'ed together, .NET just adds the values together to produce a new, unique value that represents the combination of the OR'ed items. Using enum values that are powers of 2 ensures that the combinations will always be unique.
http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx
I think a quick introduction to binary OR is in order.
| doesn't just let you sneak two integers into one variable. It performs a mathematical operation.
Therefore, any value other than 0 OR'ed with 0 will return that value itself.
You will probably encounter further unexpected behavior if you supply flag values that are not a single bit, such as 1, 2, 4, 8, 16.
EDIT
If you want to build a Flags enum around the existing values, you can do that. Don't use the currently reserved bits 10001 (17) for any other value, and be careful when testing for Ok.
Here's an example of how to accomplish this using a bitflag. This will however likely force you to change your existing flag comparisons.
[FlagsAttribute]
enum tester
{
alpha = 1,
beta = 2,
gamma = 4,
reggy=3
}
class Program
{
static void Main(string[] args)
{
tester t = tester.alpha | tester.beta;
if (t == tester.alpha)
Console.WriteLine("alpha only");
if ((t & tester.alpha) != 0)
Console.WriteLine("alpha");
if ((t & tester.beta) != 0)
Console.WriteLine("beta");
if ((t & tester.gamma) != 0)
Console.WriteLine("gamma");
if (t == (tester.beta | tester.alpha))
Console.WriteLine("alphabeta");
//this will produce alpha, beta, alphabeta
I've been trying to emulate in C# a behavior which I was implementing without any problems in C++. I have a flag collection, which based on powers of 2, and a flag which I need to check if it exists in the collection.
byte flagCollection = 1 | 2 | 4 | 8;
byte flag = 2;
if ((flagCollection & flag) != 0) MessageBox.Show("y"); else MessageBox.Show("n");
Now, the problem is that whatever I set Flag to (2, 3, 100, 211), I always get "y", except for 0. Of course, 1, 2, 4, 8 would be some constants which have various meanings in my application.
In C++:
if (flagCollection & flag)
Would result in TRUE for the variables above.
The way you are doing it seems correct. I'm not really sure what behavior you are expecting. Any of the flags you listed (2, 3, 100, 211) do contain an element of 1 | 2 | 4 | 8. If you want to check whether all of them are present you should be doing
if ((flagCollection & flag) == flag)
// ...
well, if you're flag collection has OR'd 1,2,4,8, uh yes I think every positive integer that's not a multiple of 16 when &'d to it is going to return something. Or am I missing something?
Would this work?
[Flag]
public enum flagCollection {
Type1,
Type2,
Type4,
Type8,
}
flagCollection testValue = flagCollection.Type2
if ((testValue & flagCollection.Type2) == flagCollection.Type2) {
MessageBox.Show("y");
} else {
MessageBox.Show("n");
}
Not in front of the compiler so cant chek if that will work or not.