Question

I have a system which should return if first entity is ok or the second one or both of them. I decided to return char ,representing a bitmap : i.e. 00 - no one,01 - the first, 10 the second,11 - both. When I read the values, if the result sits in char res I check res %2 == 1 and res / 2 == 1 My team lead said that it is not readable What do you propose to do it better?

Était-ce utile?

La solution

Set up an enum like this:

[Flags]
enum myBitSet  : ushort
{ 
    none = 0,
    firstThing = 1,
    secondThing = 2,
    bothThings = 3   // or better firstThing | secondThing
}

Now you can do things like:

if ((test & myBitSet.firstThing) == myBitSet.firstThing) 
{
    // firstThing was set
}

Which is easier to read because you don't have to remember which bit is which.

And:

if ((test & myBitSet.bothThings) > 0) 
{
    // either firstThing, secondThing or both were set.
}

Autres conseils

I don’t know what your system is. A class, a method, a framework?

A method can return several results through out parameters

public void CheckEntities(Entity a, Entity b, out bool isAOK, out bool isBOK)
{
    isAOK = Test(a);
    isBOK = Test(b);
}

You can also create a dedicated type

public class EntitiesStatus
{
    public EntitiesStatus(bool isAOK, bool isBOK)
    {
        IsEntity1OK = isAOK;
        IsEntity2OK = isBOK;
    }

    IsEntity1OK { get; private set; }
    IsEntity2OK { get; private set; }
}

You can use an enum

[Flags]
public enum EntityStatus
{
    NoneIsOK = 0,
    FirstIsOK = 1,   // = 2^0
    SecondIsOK = 2,  // = 2^1
    BothAreOK = FirstIsOK | SecondIsOK;
}

When using the FlagsAttribute, make sure that the enum constants the can be combined are all powers of two. This ensures that any combination of them yields distinct values.

You have a lot of options, but don't use some "magic" bit manipulations that make look your code like early days c code and requires extra knowledge from those using your char result. And by the way, why char? Even just using an int and constants would be better (while not optimal). const int FirstIsOK = 1, SecondIsOK = 2; int result FirstIsOK + SecondIsOK;. This requires no bit manipulations.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top