Parse Enum by value using SnakeYAML - enums

As specified in the docs and seen from the source code, SnakeYAML works with enums by their names. What I'd like to have is to parse values by enum value, e.g.:
Enum:
public enum Strategy {
ALWAYS_RUN("always-run"),
ALWAYS_SKIP("always-skip"),
DEPENDS("depends");
...
}
YAML:
branches:
trunk: always-skip
bugfix: depends
default: always-run
The reason is our code style forces us to use uppercase for enum constants, while I'd like to keep data in the yaml file lowercase.

As far as I am aware, this is not possible. Enum constants are private, and are therefore not accessible by other classes, so the YAML parser would not be able to construct the objects.
Although not perfect, you could use aliases to create a nickname for the enums.

There is another way to do this. Probably it's not clean but works properly.
Create a new Constructor class by extending org.yaml.snakeyaml.constructor.Constructor.
Inside it create a ScalarConstuctor protected class with the same code implementation as in base ScalarConstructor class except of enum parsing implementation.
In a method constructStandardJavaInstance check if an enum exists with uppercase or lowercase name.
Finally create Yaml object with the Constructor (of step 1)

Related

Schema for referencing map elements

I'd like to create a jsonschmema for a yaml file that will contain a list of defined keys to be referenced later in the yaml document.
example
myDef:
foo: bar
baz: lipsum
someProperty:
refferencedValue: foo
the schema should only validate values for someProperty.refferencedValue that are listed in myDef. So only foo and baz would be a valid someProperty.refferencedValue
is this possible with jsonschema? if so what would this look like?
In jsonschema it's not possible to reference arbitrary, dynamic values from the data to use it as part of the schema validation. See this discussion for more context. However:
If you can enumerate all possible properties (or property name patterns) of your myDef object, you can use oneOf to apply specific constraints on the someProperty.refferencedValue value for each property.
If you can't enumerate all the values you can't use standard jsonschema. Some validator libraries implement non-standard features that can help you. For example, Avj implements a $data keyword that can solve your issue. But keep in mind that this solution is tied to Avj - other validators will ignore this keyword.

How do you emulate a dictionary / hashtable in boo?

If you want to make a boo class that behaves like a dictionary or hashtable, what is the correct syntax? In Python you'd override __getitem__ and __setitem__, but I've been unable to find the equivalent magic methods in Boo and I don't think I can inherit from Dictionary in this case.
If you want to adapt an existing class to act like a dictionary/hash, (or to access an internal field of one of these classes,) the equivalent to overriding __setitem__ and __getitem__ is defining a default array property on the class, like so:
public self[key as TKey] as TValue:
get:
return LookupValue(key)
set:
SetValue(key, value)
(You'll have to fill in the types and actual accessors yourself.)

Best way to validate and extend constructor parameters in Scala 2.10

I want to have a class that has a number of fields such as String, Boolean, etc and when the class is constructed I want to have a fieldname associated with each field and verify the field (using regex for strings). Ideally I would just like specify in the constructor that the parameter needs to meet certain criteria.
Some sample code of how :
case class Data(val name: String ..., val fileName: String ...) {
name.verify
// Access fieldName associated with the name parameter.
println(name.fieldName) // "Name"
println(fileName.fieldName) // "File Name"
}
val x = Data("testName", "testFile")
// Treat name as if it was just a string field in Data
x.name // Is of type string, does not expose fieldName, etc
Is there an elegant way to achieve this?
EDIT:
I don't think I have been able to get across clearly what I am after.
I have a class with a number of string parameters. Each of those parameters needs to validated in a specific way and I also want to have a string fieldName associated with each parameter. However, I want to still be able to treat the parameter as if it was just a normal string (see the example).
I could code the logic into Data and as an apply method of the Data companion object for each parameter, but I was hoping to have something more generic.
Putting logic (such as parameter validation) in constructors is dubious. Throwing exceptions from constructors is doubly so.
Usually this kind of creational pattern is best served with one or more factory methods or a builder of some sort.
For a basic factory, just define a companion with the factory methods you want. If you want the same short-hand construction notation (new-free) you can overload the predefined apply (though you may not replace the one whose signature matches the case class constructor exactly).
If you want to spare your client code the messiness of dealing with exceptions when validation fails, you can return Option[Data] or Either[ErrorIndication, Data] instead. Or you can go with ScalaZ's Validation, which I'm going to arbitrarily declare to be beyond the scope of this answer ('cause I'm not sufficiently familiar with it...)
However, you cannot have instances that differ in what properties they present. Not even subclasses can subtract from the public API. If you need to be able to do that, you'll need a more elaborate construct such as a trait for the common parts and separate case classes for the variants and / or extensions.

How do I discern whether a Type is a static array initializer?

I'll start by saying that I'm working off the assumption that static array initializers are turned into private nested classes by the compiler, usually with names like __StaticArrayInitTypeSize=12. As I understand it, having read this extremely informative article, these private classes are value types, and they aren't tagged with the CompilerGeneratedAttribute class.
I'm working on a project that needs to process certain types and ignore others.
I have to be able to process custom struct types, which, like the generated static array initializer classes, are value types. I must ignore the generated static array initializer classes. I also must ignore enumerations and delegates.
I'm pulling these classes with Linq, like so:
var typesToProcess = allTypes.Where(type => !type.IsEnum &&
!type.IsArray &&
!type.IsSubclassOf(typeof(Delegate)));
I'm fairly sure that the IsArray property isn't what I think it is. At any rate, the generated static array initializer class still shows up in the typesToProcess Enumerable.
Has anyone else dealt with this? How can I discern the difference between a custom struct and a generated static array initializer class? I could hack it by doing a string comparison of the type name against __StaticArrayInitTypeSize, but is there a cleaner solution?
Well, having just tried it myself with the C# 4 compiler, I got an internal class called <PrivateImplementationDetails>{D1E23401-19BC-4B4E-8CC5-2C6DDEE7B97C} containing a private nested struct called __StaticArrayInitTypeSize=12.
The class contained an internal static field of the struct type called $$method0x6000001-1. The field itself was decorated with CompilerGeneratedAttribute.
The problem is that all of this is implementation-specific. It could change in future releases, or it could be different from earlier releases too.
Any member name containing <, > or = is an "unspeakable" name which will have been generated by the compiler, so you can view that as a sort of implicit CompilerGenerated, if that's any use. (There are any number of other uses for such generated types though.)

Where is the best place to locate enum types?

I have found that there is generally a singe type or namespace that takes in any particular enum as a parameter and as a result I have always defined those enums there. Recently though, I had a co-worker make a big deal about how that was a stupid thing to do, and you should always have an enum namespace at the root of your project where you define everyone of your enum types.
Where is the best place to locate enum types?
Why treat enums differently to other types? Keep them in the same namespace as they're likely to be used - and assuming they're going to be used by other classes, make them top-level types in their own files.
The only type of type which I do commonly clump together is delegates - I sometimes have a Delegates.cs file with a bunch of delegates in. Less so with .NET 3.5 and Func/Action, mind you.
Also, namespaces are for separation of things that belong together logically. Not all classes belong in the same namespace just because they are classes. Likewise, not all enums belong in the same namespace just because they are enums. Put them with the code they logically belong in.
I generally try to put all my different types (classes, interfaces and enums) in their own files, regardless of how small they are. It just makes it much easier to find and manage the file they're in, especially if you don't happen to be in Visual Studio and have the "go to definition" feature available. I've found that nearly every time I've put a "simple" type like that in another class, I end up either adding on to it later on, or reusing it in a way that it no longer makes sense for it to not have its own file.
As far as which namespace, it really depends on the design of whatever you're developing. In general, I try to mimic the .NET framework's convention.
I try to put everything associated with a class in the class. That includes not just enums, but also constants. I don't want to go searching elsewhere for the file or class containing the enums. In a large app with lots of classes and folders, it wouldn't always be obvious where to put the enum file so it would be easy to find.
If the enum if used in several closely-related classes, you could create a base class so that the common types like enums are shared there.
Of course, if an enum is really generic and widely used, you may want to create a separate class for them, along with other generic utilities.
I think you put Enums and Constants in the class that consumes them or that uses them to control code decisions the most and you use code completion to find them. That way you don't have to remember where they are, they are associated with the class. So for example if I have a ColoredBox class then I don't have to think about where they are at. They would be part of ColoredBox. ColoredBox.Colors.Red, ColoredBox.Colors.Blue etc. I
I think of the enum and constant as a property or description of that class.
If it used by multiple classes and no one class reigns supreme then it is appropriate to have an enum class or constants class.
This follows rules of encapsulation. Isolating properties from dissimilar classes. What if you decide to change the RGB of Red in Cirle objects but
you don't want to change the red for ColoredBox objects? Encapsulating their properties enables this.
I use nested namespaces for this. I like them better than putting the enum within a class because outside of the class you have to use the full MyClass::MyEnum usage even if MyEnum is not going to clash with anything else in scope.
By using a nested namespace you can use the "using" syntax. Also I will put enums that relate to a given subsystem in their own file so you don't get dependency problems of having to include the world to use them.
So in the enum header file you get:
// MyEnumHeader.h
// Consolidated enum header file for this dll,lib,subsystem whatever.
namespace MyApp
{
namespace MyEnums
{
enum SomeEnum { EnumVal0, EnumVal1, EnumVal2 };
};
};
And then in the class header file you get:
// MyInterfaceHeader.h
// Class interfaces for the subsystem with all the expected dependencies.
#include "MyEnumHeader.h"
namespace MyApp
{
class MyInterface
{
public:
virtual void DoSomethingWithEnumParam (MyEnums::SomeEnum enumParam) = 0;
};
};
Or use as many enum header files as makes sense. I like to keep them separate from the class headers so the enums can be params elsewhere in the system without needing the class headers. Then if you want to use them elsewhere you don't have to have the encapsulating class defs as you would if the enums were declared within the classes.
And as mentioned before, in the outer code you can use the following:
using namespace MyApp::MyEnums;
What environment?
In .NET I usually create an empty class file, rename it to MyEnum or whatever to indicate it holds my enum and just declare it in there.
If my enumeration has any chance of ever being used outside the class I intend to use it, I create a separate source file for the enum. Otherwise I will place it inside the class I intend to use it.
Usually I find that the enum is centered around a single class -- as a MyClassOptions type of thing.
In that case, I place the enum in the same file as MyClass, but inside the namespace but outside the class.
namespace mynamespace
{
public partial class MyClass
{
}
enum MyClassOptions
{
}
}
I tend to define them, where their use is evident in the evident. If I have a typedef for a struct that makes use of it for some reason...
typedef enum {
HI,
GOODBYE
} msg_type;
typdef struct {
msg_type type;
union {
int hivar;
float goodbyevar;
}
} msg;

Resources