Get FieldDescription for protected field in one of the superclasses - byte-buddy

Based on a TypeDefinition (eg. the instrumented type) I want to quickly find the FieldDescription for a protected variable. I know the variable is there in one of the superclasses but I don't know exactly in which one. Here's a simplified example:
class C1 { protected int id; }
class C2 extends C1 {}
Based on the typeDefinitionC1 = TypeDescription.ForLoadedType.of(C1.class), I can find the field by doing something like this:
typeDefinitionC1.getDeclaredFields().filter(named("id")).getOnly()
But using the type definition for C2 it doesn't work because the field is not declared in C2. I've written a small function to iterate over all superclasses in order to find the field but I would expect ByteBuddy to let me do something like:
typeDefinitionC2.getFields().filter(named("id").and(isProtected())).getOnly()
Is there some convenient way of doing this?

You can use new FieldLocator.ForExactType(typeDefinitionC1).locate(named("id")).
Byte Buddy does not bake the location into the description API as the reflection API does as location is often dependant on the lookup site and use case.

Related

Recursively building a data class in Kotlin

I have am trying to create a recursive data class like so:
data class AttributeId (
val name: String,
val id: Int,
val children: List<AttributeId>?
)
The thing I'm struggling with now is building the data class by iterating over a source object.
How do I recursively build this object?? Is a data class the wrong solution here?
EDIT: Some more information about the Source object from which I want to construct my data class instance
The source object is a Java Stream that essentially* has the following shape:
public Category(final String value,
final Integer id,
final List<Category> children) {
this.value = value;
this.id = id;
this.children = children;
}
(For brevity the fields I don't care about have been removed from example)
I think I need to map over this stream and call a recursive function in order to construct the AttributeId data class, but my attempts seem to end in a stack overflow and a lot of confusion!
I don't think there's anything necessarily wrong with a data class that contains references to others.
There are certainly some gotchas.  For example:
If the list were mutable, or if its field was mutable (i.e. var rather than val), then you'd have to take care because its hashcode &c could change.
And if the chain of links could form a loop (i.e. you could follow the links and end up back at the original class), that could be very dangerous.  (E.g. calling a method such as toString() or hashCode() might either get stuck in an endless loop or crash the thread with a StackOverflowError.  You'd have to prevent that by overriding those methods to prevent them recursing.)  But that couldn't happen if the list and field were both immutable.
None of these issues are specific to data classes, though; a normal class could suffer the same issues (especially if you overrode methods like toString() or hashCode() without taking care).  So whether you make this a data class comes down to whether it feels like one: whether its primary purpose is to hold data, and/or whether the automatically-generated methods match how you want it to behave.
As Tenfour04 says, it depends what you're constructing these from.  If it naturally forms a tree structure, then this could be a good representation for it.
Obviously, you wouldn't be able to construct a parent before any of its children.  (In particular, the first instance you create would have to have either null or an empty list for its children.)  This would probably mean traversing the source in post-order.  The rest should fall out naturally from that.

Avoiding setter to change value of class's property

I have a class with one private field:
class Person {
string name;
public void setName(string name);
}
Then, using some object which is responsible for interacting with user (in this example by command line), I want to change the value of this field:
Person somePerson;
CommandLineView view;
somePerson.setName(view.askUserForName());
It works. But I don't like using set function as it exposes class members.
Therefore I started looking how to avoid it.
New implementation looks like this:
class Person
{
string name;
public void changeName(view) { name = view.askUserForName(); }
}
and:
Person somePerson;
CommandLineView view;
somePerson.changeName(view);
Now Person does not expose its member. Moreover this class is responsible for logic related to changing name (for example function changeName could also update database, notify interested parties etc.
The question is: Is such kind of refactoring a good practice? Or maybe implementation with setter was better, even if it break encapsulation?
I think there should be no method to set the name at all, it should be a constructor parameter:
Person somePerson(view.askUserForName());
Problem with your approach is that you first create the object which is not fully initialized, so is dangerous to use: Person somePerson. What if you forget to setName? Will your code still work with this "empty" person?
And then you allow to directly modify the internal state with setName method, which is also not good.
Using the constructor parameter you avoid both of these problems.
As for the original question - I don't think there is big difference between the two methods.
The result is exactly the same - you call the method and the internal object state changed. You can name it setName or changeName, result is the same.
The second method with changeName(view) actually is worse because you also introduce the dependency of the Person on the View object.
Now, if you want to change the name, you always need to create the View object first.

Why parent class is not able to access child class member

If we go according to below code
class A;
int a = 10;
endclass
class B extends A;
int b = 20;
endclass
program test;
A a1;
B b1;
initial begin
b1 = new();
a1 = b1; //child class object is assigned to parent class handle
$display("Value of variable b is %x", a1.b);
end
endprogram
Then the above code results into error that "Could not find member 'b' in class 'A'"
Now my observation is that when extended class object is assigned to base class handle then simulator will check the type of handle and check whether variable is present in that class or not. As variable b is not defined in base class then it will result into error.
So I want to confirm whether my above observation is correct or incorrect?
I would welcome if anyone wants to add something to my observation, in case it's correct.
Thanks
You are correct, and it is the intended behavior in OOP languages I know (I don't especially know the one you are using, but your example is simple enough). Being able to use a variable declared by a child class would result in a violation of the object oriented principle of polymorphism (or subtyping).
I will answer you in Java, because I'm sure of the syntax in this language for the example i want to give. Imagine two variables with the same declared type :
public A buildA () {
return new B();
}
public static void main () {
A a1 = new A();
A b1 = buildA();
}
The polymorphism principle is that a1 and b1 should implement the same interface and be used indifferently. If I was allowed to access a variable's member b, since the compiler couldn't guess which is base and which is child, then it would allow the program to crash at runtime every time I access a concrete A, removing the safety net types are supposed to provide.
I would not use the terms parent and child class here. It implies you have two separate class objects.
What you describe is two different class types where one type is derived/extended from a base type. Then you declare two class variables: a1 and b1. These variables may hold a handle to class object of the same type, or a handle to an object of any type extended the type of the variable. However, the compiler will not let you reference any variable or member that has not been defined by type of the class variable regardless of the type of the object the class variable currently hold a handle to.
OOP gives you the ability to interact with a class variable with the possibility of it having a handle to much more complex object without you knowing what extensions have been made to that object. But you have to assume that the object could be the same type as the class variable. The compiler enforces this as well. If you want to interact with the extended class variables, you need to use an extended class variable type.

DO YOU KNOW OF ANY OOP dynamic language that has field instantiation level?

Trying to orthogonalize the prototype and class concepts for an interpreted dynamic language, I arrived to the conclusion that classes in their more generic form in order to be able to define not only objects but classes too, SHOULD BY ABLE to hold not only fields for their direct instances, but also fields for instances of their instances and so on.
So every field of a class ( or meta class if you like ) could have a level that indicates after how many instantiations the field will appear as a storage location where to store data.
My question isn't if that is right or not ( but feel free to clarify if curious )
but if you know about any language that already allows that capability, or at least any article that speaks about that possibility.
As my experience with OOP ( object oriented programming ) is limited, I would like to have some indications on where to find some advanced concepts like the one mentioned before.
Just to clarify: A meta-class of that kind could define as it's instances classes that have a static variable A and two fields X Y.
A C++ like tentative syntax could be:
metaclass mc1 {
var A;
meta var X,Y;
} c1,c2;
with the above definition we would had created two classes c1 and c2 that normally would be defined as:
class c1{
static var A;
var X,Y;
}
class c2{
static var A;
var X,Y;
}
When we create an instance of c1 it isn't the same thing as creating an instance of c2 because the static var A is different between c1 and c2;
So in that case in the metaClass mc1 we have the definition of a
normal field A ( normal level 1 ), and the definition of two fields X,Y of level 2 .
The fields of level 2 will appear as storage space when we create an instance of an instance of mc1.
Morover classes c1 and c2 may be get more different by the later (dynamic) addition of more static variables or field variables ( prototype field addition ).

How to define a set of input parameters in Pex?

Say I have MyClass with 100s of fields.
If I use an object of MyClass as an input param, Pex would simply choke trying to generate all possible combinations (mine runs into 1000s of paths even on a simple test)
[PexMethod]
void MytestMethod(MyClass param){...}
How can I tell Pex to use only a set of predefined objects of MyClass rather than having it trying to be smart and generate all possible combinations to test?
In other words I want to manually specify a list of possible states for param in the code above and tell Pex to use it
Cheers
If you find that Pex is generating large amounts of irrelevant, redundant, or otherwise unhelpful inputs, you can shape the values that it generates for your parametrized unit tests' input using PexAssume, which will ensure that all generated inputs meet a set of criteria that you provide.
If you were wanting to ensure that arguments came from a predefined collection of values, for instance, you could do something like this:
public void TestSomething(Object a) {
PexAssume.IsTrue(someCollection.Contains(a));
}
PexAssume has other helper methods as well for more general input pruning, such as IsNotNull, AreNotEqual, etc. What little documentation is out there suggests that there is some collection-specific functionality as well, though if those methods exist, I'm not familiar with them.
Check out the Pex manual for a bit more information.
Pex will not try to generate every possible combination of values. Instead, it analyses your code and tries to cover every branch. So if you have
if (MyObject.Property1 == "something")
{
...
}
then it will try to create an object that has Property1 == "something". So limiting the tests to some predefined objects is rather against the 'Pex philosophy'. That said, you may find the following information interesting.
You can provide a Pex factory class. See, for instance, this blog post or this one.
[PexFactoryClass]
public partial class EmployeeFactory
{
[PexFactoryMethod(typeof(Employee))]
public static Employee Create(
int i0,
string s0,
string s1,
DateTime dt0,
DateTime dt1,
uint ui0,
Contract c0
)
{
Employee e0 = new Employee();
e0.EmployeeID = i0;
e0.FirstName = s0;
e0.LastName = s1;
e0.BirthDate = dt0;
e0.StartDateContract = dt1;
e0.Salary = ui0;
e0.TypeContract = c0;
return e0;
}
}
Pex will then call this factory class (instead of a default factory) using appropriate values it discovers from exploring your code. The factory method allows you to limit the possible parameters and values.
You can also use PexArguments attribute to suggest values, but this will not prevent Pex from trying to generate other values to cover any branches in your code. It just tries the ones you provide first.
[PexArguments(1, "foo")] // try this first
void MyTest(int i, string s)
{
...
}
See here for more information on PexArguments and also search for 'seed values' in the PDF documentation on Parameterized Test Patterns.