Do you use enum types in your WCF web services?
Asked Answered
F

9

43

I've heard some people saying that enums are evil and shouldn't be used in web services because of the mismatches that could occur between the server and the client if some values are assigned, or if the enum is marked with the Flags attribute. They also said that web services exposing enums are harder to maintain but couldn't really give me viable arguments. So from your experience what are the pros and cons of using enums in a WCF web service?

Frederickafredericks answered 28/11, 2008 at 18:3 Comment(0)
C
43

The reason people recommend to avoid enums in webservices is because they create subtle backwards compatible problems.

The same applies to regular enums but in web services the problem is even more clear specially in .NET-generated proxies (see below).

  • If the enumerate is input only you have no issues.
  • If the enumerate can be an out parameter then if you add a new element and you return it, old clients could have problems:
    • If the client is using a .NET-generated proxy it will break before the caller can handle it (in the deserialization)
    • Even if the generated code for the proxy supported the change (for example if it maps the enumerate to a string) the user code in the client may not process properly the new unexpected value (it could easily be a never executed path)

By defining the parameter as a string you signal the user of your API that the value may change in the future. Even if you think that the value will never change is a good practice to be ready.

There is a good post by Dare Obasanjo on this topic.

Crossexamine answered 25/4, 2009 at 5:19 Comment(2)
​As a workaround for backward- compatibility of enums, they can be declared as [DataContract] and only old values set as [DataMember] , but left new values without the attribute.Besiege
"If the enumerate is input only you have no issues." Not quite true: If you renamed one of the values used by a .NET generated proxy, then an old client sending you the old name would get an exception when the server was unable to deserialise the value.Sontich
F
18

I have used enums in WCF, also in interoperability scenarios. If you control both sides of the service, it is easier to work with. If you only control one side of the service, you need to look out for the issues that you mentioned.

Enums are so much better that string variables, or what else you might choose to use. Using strings instead of enums is an anti pattern called "loosey Goosey" in SOA.

Fail answered 17/12, 2008 at 15:40 Comment(0)
G
10

Enumerations are fully supported in WSDL and XSD through the xsd:enumeration schema element. It provides support for both single values and flags-style enumerations, where multiple values in a flags enumeration are separated by spaces.

So you should have no problem using enumerations with any standards compliant platforms.

Grassgreen answered 17/12, 2008 at 16:5 Comment(1)
Backward compatibility mentioned by MMind is a seriose concern, that often overlooked.Besiege
B
3

Of course, it all depends on where you are going to use this WCF service.

If it's a single application that will use it, then changing the contract won't have any effects.

If it's multiple internal applications, changing the contract might require some changes on the other applications.

And finally, if the WCF service is public, you might have to provide 2 versions of the service with differents version so that the people consuming them have the time to transfer their version of the client to the new service.

It all depends on your needs honestly.

Backpack answered 28/11, 2008 at 21:43 Comment(0)
L
3

Using anything else but enums does not solve your compatibility issue, it only hides it. Assume you use an int to replace an enum. Did you really solve the compatibility issue or just disguised it until the client runtime hits the unknown value?

However, one thing is worth mentioning: WCF proxies do not recreate explicitly set enum numeric values. If the enum is declared with "holes", like

enum ErrorCodes
{
  OK = 0,
  GenericError = 100,
  SomeOtherError = 101,
}

the client side representation will be like this

enum ErrorCodes
{
  OK,
  GenericError,
  SomeOtherError,
}

... which on the client results in (int)ErrorCodes.GenericError being 1.

You'll have syntactic equivalence, but not numeric equivalence.

Libby answered 15/1, 2014 at 21:10 Comment(1)
Not preserving "holes" has been fixed in more recent versions of .Net (eg 4.5.1).Keble
L
2

Enums in WSDLs must be considered as a concern for maintenance.

Adding or removing an enumeration value is(should be!) a trigger for a major update of the interface. If the enum is an output value, then you necessarily need to define a new version of the WSDL through a new URI, so to keep current clients from breaking the established contract("what if they receive on of these new, unexpected values in return?") If the enum is an input value, you could consider this as a minor update("since current clients won't need to know about this new value"), but then, the only way for those clients to benefit from the addition of this new option/functionnality (you added this new enum value for a reason, right?) would be to ask them to switch, later or sooner, to the new version of the interface.

And this doesn't have to do with the functionnal meaning of the enum, I think.

Stay on the best practices side, and you'll be safe.

Lime answered 12/1, 2012 at 10:54 Comment(1)
​Enums can be declared as [DataContract] and only old values set as [DataMember] , but left new values without the attribute until the new MAJOR releaseBesiege
H
1

I've used enums in my WCF based services without any problems. The possible issues you mention are definitely things to consider, although if you make sure you apply enums in fairly static situations you probably won't have much trouble.

Hardej answered 28/11, 2008 at 21:39 Comment(0)
L
1

Real world story (values changed for anonymity) . Use to have an implicit enum in the application

public enum { orange, banana, mango }

Some refactoring around order and new values, and we decide to make it explicit:

public enum { orange=1, banana=2, grape=3, mango=4 }

looks inoffensive ...
Next thing, a Website explodes. Scratch head, check service, add debug messages, all seems fine.
Down the rabbit hole, one day later, the reason is a base wcf service that was using the enum as a return type.

Apparenly , Wcf does not like enums with no default value.

Fix:

public enum { wcfBugBane=0, orange=1, banana=2, grape=3, mango=4 }

So ... it might bite you.

Lumber answered 17/4, 2018 at 6:47 Comment(0)
O
0

Here's an approach. Maybe it's cumbersome. I just really dislike not being able to use enums.

It gracefully handles deserialization of an unrecognized value, returning the default value instead. The default value would need to be safe - either an acceptable fallback or something that the application could recognize as exceptional. (Like "Unspecified.")

The extensions prevent having to null-check before comparing.

[DataContract]
public class EnumValue<T> where T : struct
{
    [DataMember]
    private string _raw = string.Empty;

    [IgnoreDataMember]
    private bool _parsed;

    [IgnoreDataMember]
    private T _parsedValue;

    public EnumValue()
    {
        Set(default(T));
    }

    public EnumValue(T value)
    {
        Set(value);
    }

    internal T Value
    {
        get
        {
            if (_parsed) return _parsedValue;
            if (!Enum.TryParse<T>(_raw, out _parsedValue))
            {
                _parsedValue = default(T);
            }
            _parsed = true;
            return _parsedValue;
        }
    }

    public void Set(T value)
    {
        _raw = value.ToString();
        _parsedValue = value;
        _parsed = true;
    }
}

public static class EnumValueExtensions
{
    public static T GetValue<T>(this EnumValue<T> enumValue) where T : struct
    {
        return enumValue == null ? default(T) : enumValue.Value;
    }

    public static bool EqualsValue<T>(this EnumValue<T> enumValue, T compareTo) where T : struct
    {
        return (enumValue.GetValue().Equals(compareTo));
    }
}
Olli answered 29/12, 2015 at 21:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.