How do you emulate a dictionary / hashtable in boo? - 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.)

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 to check where a who calls this method?

I have a custom method in an ABAP class.
I used the 'Where used' tool to show where the class is called from but, as it turns out, it's called from somewhere else I didn't expect.
So what's the best way of showing a complete list of everything that calls the method?
Due to the wonders of object-oriented programming, an instance of a class can hide behind a reference to one of its base classes or interfaces it implements. For example:
DATA foo TYPE REF TO z_my_interface.
CREATE OBJECT foo TYPE z_my_class.
" lots of more code
foo->bar( ).
You can not find this reference to z_my_class->foo with its "Where Used" list, because at that code location foo could also be a reference to an instance of any other class which implements z_my_interface. But you might be able to find this if you don't just look at the where-used list of the method but at the where-used list of the whole class or the interface / base class which declares the method.
And then there are evil dynamic programming tricks like this which determine methods and classes at runtime:
DATA foo TYPE REF TO object.
CONSTANTS: classname TYPE string VALUE 'Z_MY_CLASS',
methodname TYPE string VALUE 'BAR'.
CREATE OBJECT foo TYPE (classname).
CALL METHOD foo->(methodname).
There is no chance to find this with the where-used tool. But if the class- and/or method name does actually appear in the code (it might not, for example if they are read from a customizing table) then you can use the report RS_ABAP_SOURCE_SCAN. This handy little tool allows you to select a set of ABAP programs and search for strings (and even regular expressions) within their sourcecodes.
However, if you know the method gets called when you do something specific as a user and just want to know where, then it can be easier to just set a debugger breakpoint in the method, run into it and check the call stack.
Sorted using the code_scanner transaction.

Parse Enum by value using SnakeYAML

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)

Coding Style: How to Make Obvious Determination of Parameter's Type We Have To Pass To a Function?

What is the best way to document the type of parameters that a function expects to receive?
Sometimes a function uses only one or two fields of an object. Sometimes this fields have common names (get(), set(), reset(), etc.). In this situation we must leave a comments:
...
#staticmethod
def get( postId, obj ):
"""obj is instance of class Type1, not Type2"""
inner = obj.get()
Is there a more explicit way to make it obvious? Maybe an object name should contain expecting typename?
Given python's 'duck-typing' (late bound) behaviour, it would be a mistake to require a particular type.
If you know which types your function must not take, you can raise an exception after detecting those; otherwise, simply raise an exception if the object passed does not support the appropriate protocol.
As to documentation, just put the required protocol in the docstring.
One strength of python is "duck typing", that is not to rely on the actual type of a variable, but on its behaviour. So I'd suggest, that you document the field, that the object should contain.
"""obj should have a field 'foo' like in class 'bar' or 'baz' """
First of all, name your methods properly, and use properties if they make sense.
You should try to get the hang of duck-typing. It's pretty useful. And if not, try and see if abstract base classes helps you do what you want.

Best way to implement extension methods

I am really really really new to all of this, and most of it is unexplored territory. Today I needed to create an anonymous class and put it to a list. I was trying to find how I can make a list of anonymous types, and found that I should make an extension method. I also already figured out an extension method should be in a static class. But what I haven't figured out yet is if there is some pattern that I should use? For now, I have made a static class in my App_Code folder named ExtensionMethods, but have no idea if I should put extension methods of all kinds of types in this class, or if I should make separate classes etc.
To my knowledge you can not implement extension methods for anonymous classes. And this makes sense as really and truly if the class has some semantics it should be made a named class.
To create a list of anonymous classes use this method:
public static List<T> CreateListFromType<T>(T anonType){
return new List<T>();
}
To use this method to create a list, do something like:
var list = CreateListFromType(new {A = default(int), B = default(int)});
Extension method is nothing more than easier-to-read static helper/utility methods. The way you organize them is the same principal as how you organize your normal classes. If you think those should stays together, then try to give them a meaningful, general enough name as the class name. Once you found your class name cannot include what that method doing, then you know that method should belongs to other places.
Firstly extension methods are normal static methods declared like this -
void MyExtension(this MyTarget target, int myparam){ ..
After this the C# compiler adds some syntactic sugar letting you call this method as
target.MyExtension(myparam);
The compiler will replace all these calls with
MyStaticClass.MyExtension(target, myparam);
The important thing is that an extension method is a normal static method. You should follow following guidelines while creating them -
Try to group extension methods for each target class in a separate static class and name it appropriately as Extensions.
Create a new namespace in your application for Extension methods such as MyAppExtensions and keep your static classes inside this namespace. This will keep the coder from misunderstanding them as Extension method and accidentally using them as instance methods.
Make these naming conventions for namespaces and static classes of Extension methods as a standard in the team.
In your extension method check if the first parameter is null and take appropriate action. If you do not then it will be possible to call the method with target being null and may result in unexpected behavior. If the first parameter is allowed to be null then document it clearly.
Consciously decide if it is correct to create and extension method or instance method will be better.
Be careful that the extension method names do not clash with instance method names or other existing extension method names for this class. Following point 1, 2 and 3 will help you achieve this.
I learnt these from Jon Skeet's C# In Depth. You should read it too.
This is how you create a list of an anonymous class.
var anonList = new[]{
new {Foo = "foo", Bar = 2},
new { Foo = "bar", Bar = 3},
}.ToList();
It has nothing to do with writing extension methods.
Edit:
In fact you will have a hard time to use extension methods to create anonymous types since anonymous types can not be used as method parameters or return type.
Edit2:
If you want to convert a list of anonymous types to a list of specific types you can use Select:
class MyClass
{
public string Prop1 {get;set;}
public int Prop2 {get;set;}
}
List<MyClass> myList = anonList.Select(x => new MyClass(){Prop1 = Foo, Prop2 = Bar}).ToList();
I use to put anonymous to DataTable. Due to it's limitation, DataTable provide more functionality such as serialization.

Resources