Class Object Instantiation in UVM - uvm

In UVM Cookbook, it is written that class object instantiation is done at run time. But before run time, during compilation/elaboration also we may have all the details of class.
As depicted in the below image (Taken from UVM Cookbook), it is showed that Module and Interface instant creations are done in elaboration phase, but class object creation are done at run time.
Consider this sample example.
// Inside any .sv file
class A;
int a;
endclass
A x;
initial
x=new();
Now in this case there is no need of creating class at run time, as we have all the details of class available in compile/elaboration time like another module or interface details.
So why in Systemverilog, specifically only class instantiations are done at run time?
Even in C++ also object creation are not done at run time.
Note : In the question, I am talking about simple classes, not using inheritance, in which run time creation may become mandatory. By Creation I do not refer to memory allocation, as memory for all (module, interface, class) will be allocated during simulation only. I am just taking the context of the image.

All objects are created at run-time.
Maybe you are confusing run-time with run-phase? Run-phase is part of the phasing mechanism in uvm that allows for separation between different periods in a simulation. All uvm components can thus be synchronized by phase.
Object creation here is done in the build_phase, which is part of the run-time.

As #Tudor points out, all object instances are created at run time. They have to be because all objects have to execute their constructor. This is the same as C++.

Related

GLib - difference between class_init and init class methods

I'm a newbie with glib and I'm still struggling to understand the difference between my_class_name_class_init() methods and my_class_name_init() methods.
I get that the latter is kinda equivalent to a C++ constructor and that goes per-instance of the object created but I don't quite understand the purpose of those my_class_name_class_init() methods. By reading the documentation I think class_init() methods are somewhat similar to a static constructor valid for all instances but I'm still not sure I got this right.
What's the purpose of class_init() methods?
class_init functions are executed once per class, before first instance is constructed - in that way they are similar to C# static constructors. In contrast, instance_init functions are called for every instance of object created and are responsible for initializing that instance.
Like static constructors, class_init are responsible for initializing any shared data all instances might need, but more importantly, in GObject they play vital role in setting up GObject object system. They are responsible for:
Setting up virtual function tables
Setting up GObject property system
Setting up signals

Global property for DB access rather than passing DB around everywhere? Advice anyone?

Globals are evil right? At least everything I read says so, because something might alter the state of the global at any point.
However, I've a DB object that's a bit of a tramp in regards class parameters. The property below is an instance of a wrapper class that automatically works in MS Access or SQL - hence why it's not EF or some other ORM.
Public Property db As New DBI.DBI(DBI.DBI.modeenum.access, String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0} ;Persist Security Info=True;Jet OLEDB:Database Password=""lkjhgfds8928""", GetRpcd("c:\cms")))
The code itself does have PostSharp for exception handling, so I'm thinking that I can conditionally handle oledb errors by logging them and re initialising the DB if it is Null.
Up till now, the solution has been to continually pass the db around as a parameter to every single class that needs it. Most of the data classes have a shared observablecollection that is built from structures that individually implement inotifyproperty changed. One of these is asynchronously built. The collection property checks if it's empty before firing off the private Async buildCollection sub.
Given that we don't use dependency injection (yet) as I need to learn it; is the Global property all that bad? Db is needed everywhere that data is pulled in or saved. The only places I don't need it at all is the View and its code behind.
It's not a customer facing project but it does need to be solid.
Any advice gratefully recieved!!
Passing the DB connection as a parameter into your classes IS using dependency injection, perhaps you just didn't recognize it as such. Hard coding the connection string in the callers is still code that is not free of dependencies, but at least your database accessors themselves are free of the dependency upon a global connection.
Globals aren't just evil because they change without notice - that's just one effect you see resulting from the bad design choice. They're evil because a design using them is brittle. Code that depends upon globals requires invisible stuff to be set correctly before calling it, and that leads to inter-dependencies between unrelated code. The invisible stuff becomes critically important stuff. Reading just the interface of a module that internally uses globals, how would I know that I have to call the SetupGlobalThing() method before calling it? What happens if I call IncrementGlobalThing() and DecrementGlobalThing() and MultiplyGlobalThing() in varying orders, depending on the function the user selects?
Instead, prefer stateless methods where you pass in all the stuff to be changed and used: IncrementThing(Integer thing) doesn't rely on hidden setup steps. It clearly does one thing: it increments the thing passed in.
It may help to think about it from a unit testing viewpoint. If you were to write a unit test to prove a specific module of code works, would you need to pass in a real database connection (hard*), or would you be able to pass in a fake database reference that meets your testing needs easily?
The best way to test your logic is to unit test it. The best way to test your class interfaces and method structure is to write unit tests that call them. If the class is hard to test, it's likely due to dependencies upon external things (globals, singletons, databases, inappropriate member variables, etc.)
The reason I called using a real database "hard" is that a unit test needs to be easy and fast to run. It shouldn't rely on slow or breakable or complex external things. Think about unit testing your software on the bus, with no network connection. Think about how much work it is to create a dummy database: you have to add users, you have to have the right version of schema in it, it has to be installed, it has to be filled with the right kind of testing data, you need network connectivity to it, all those things can make your testing unreliable. Instead, in a unit test you pass in a mock database, which simply returns values that exercise your code being tested.

JUnit 4 PermGen size overflow when running tests in Eclipse and Maven2

I'm doing some unit tests with JUnit, PowerMock and Mockito. I have a lot of test classes annotated with #RunWith(PowerMockRunner.class) and #PrepareForTest(SomeClassesNames) to mock final classes and more than 200 test cases.
Recently I've run into a problem of a PermGen space overflow when I run my entire test suite in Eclipse or Maven2. When I run my test one by one then each of them succeeds.
I did some research about that, however none of the advice helped me (I have increased PermGenSize and MaxPermSize). Recently I've found out that there is one class that contains only static methods and each method returns object mocked with PowerMockito. I'm wondering whether it is a good practice and maybe this is the origin of the problem because static variables are being shared between unit tests?
Generally speaking is it a good practice to have a static class with a lot of static methods which returns static mocked objects?
I am getting PermGen errors from Junit in Eclipse too. But I am not using any mocking libs like Mockito nor EasyMock. However, my code base is large and my Junit tests are using Spring-Test (and are intense and complex test cases). For this, I need to truly increase the PermGen for all of my Junit tests.
Eclipse applies the Installed JRE settings to the Junit runs - not the eclipse.ini settings. So to change those:
Window > Preferences > Java > Installed JRE's
select the default JRE, Edit... button
add to Default VM Arguments: -XX:MaxPermSize=196m
This setting will allow Junit tests to run the more intense TestCases in Eclipse, and avoid the OutOfMemoryError: PermGen. This should also be low risk because most simple Junit tests will not allocate all of that memory.
As #Brice says, the problems with PermGen will be coming from your extensive use of mocked objects. Powermock and Mockito both create a new class which sits between the class being mocked and your test code. This class is created at runtime and loaded into PermGen, and is (practically) never recovered. Hence your problems with the PermGen space.
To your question:
1) Sharing of static variables is considered a code smell. It's necessary in some cases, but it introduces depdendencies between tests. Test A needs to run before test B.
2) Usage of static methods to return a mocked object isn't really a code smell, it's a attern which is often used. If you really can't increase your permgen space, you have a number of options:
Use a pool of mocks, with PowerMock#reset() when the mock is put back into the pool. This would cut down on the number of creations you're doing.
Secondly, you said that your classes are final. If this is changeable, then you could just use an anonymous class in the test. This again cuts down on the amount of permgen space used:
Foo myMockObject = new Foo() {
public int getBar() { throw new Exception(); }
}
Thirdly, you can introduce an interface (use Refactor->Extract Interface in Eclipse), which you then extend with an empty class which does nothing. Then, in your class, you do similar to the above. I use this technique quite a lot, because I find it easier to read:
public interface Foo {
public int getBar();
}
public class MockFoo implements Foo {
public int getBar() { return 0; }
}
then in the class:
Foo myMockObject = new MockFoo() {
public int getBar() { throw new Exception(); }
}
I have to admit I'm not a particular fan of mocking, I use it only when necessary, I tend to either extend the class with an anonymous class or create a real MockXXX class. For more information on this point of view, see Mocking Mocking and Testing Outcomes. by Uncle Bob
By the way, in maven surefire, you can always forkMode=always which will fork the jvm for each test class. This won't solve your Eclipse problem though.
First : Mockito is using CGLIB to create mocks, and PowerMock is using Javassist for some other stuff, like removing the final markers, Powermock also loads classes in a new ClassLoader. CGLIB is known for eating the Permanent Generation (just google CGLIB PermGen to find relevant results on the matter).
It's not a straight answer as it depends on details of your project :
As you pointed there is static helper class, I don't know if holds static variables with mocks as well, I don't know the details of your code, so this is pure guess, and other readers that actually knows better might correct me.
It could be the ClassLoader (and at least some of his childrens) that loaded this static class might be kept alive across tests - it might be because of statics (which lives in the Class realm) or because of some reference somewhere - that means that if the ClassLoader still lives (i.e. not garbage collected) his loaded classes are not discarded i.e. the classes including the generated ones are still in the PermGen.
These classes might also be huge in size, if you have a lot of these classes to be loaded this might be relevant to have higher PermGen values, especially since Powermock needs to reload classes in a new Classloader for each tests.
Again I don't know the details of your project, so I'm just guessing, but your permanent generation issue might be caused either due to point 1 or point 2, or even both.
Anyway generally speaking I would say yes : having a static class that might return static mocked object does look like a bad practice here, as it usually is in production code. If badly crafted it can leads to ClassLoader's leak (this is nasty!).
In practice I've seen running hundreds of tests (with Mockito only) without ever changing memory parameters and without seeing the CGLIB proxies being unloaded, and I'm not using static stuff appart the ones from the Mockito API.
If you are using a Sun/Oracle JVM you can try these options to track what's happening :
-XX:+TraceClassLoading and -XX:+TraceClassUnloading or -verbose:class
Hope that helps.
Outside the scope of this question :
Personnaly I don't like using to use Powermock anyway, I only use it in corner cases e.g. for testing unmodifiable legacy code. Powermock is too intrusive imho, it has to spawn for each test a new classloader to perform its deeds (modifying the bytecode), you have to heavily annotate the test classes to be able to mock, ...
In my opinion for usual development all these little inconvenience outweight the benefit of the hability to mock finals. Even Johan the author of Powermock, once told me he was recommanding Mockito instead and keeping Powermock for some specific purpose.
Don't get me wrong here: Powermock is a fantastic piece of technology, that really help when you have to deal with (poorly) designed legacy code that you cannot change. But not for the every day developpement, especially if praticing TDD.

Abstraction challenge. How to approach encapsulation for this purpose

Please do NOT comment on bad practices used here. I am simply trying to tackle abstraction of this scenario with easy-to-describe examples.
I am trying to model a system that allows a user to enter an entity called TASK with certain configuration parameters and later have the TASK perform actions particular to that task.
Some examples of task definitions could be:
* Create a file {filename} in directory {path}.
* Copy file {filename} from {source directory} to {target directory}.
* Open {notepad application}, enter the text {sample text} and save the file as {filename}.
* Open {sample.docx}, type the text {sample text} at the end of the second paragraph.
Each task has a descriptive name and up to 5 parameters. In the examples above, parameters are enclosed in curly braces {}. Users would be instructed to carry on the above tasks and our application will verify if they have been completed. Each task must have the following function:
In a static world, I would create the following classes:
public abstract class TaskBase
{ public abstract void Perform(param1, ... param5); }
public class TaskFileCopy: TaskBase
{ public override void Perform(param1, ... param5) {} }
The problem is, tasks could be practically anything and after the program is compiled and deployed, more tasks need to be added. The first and worst thing that comes to mind is to keep on deriving from TaskBase, implement Perform, recompile and redeploy while keeping previous task results in tact.
Two problems here: By the time we hit 2,000 tasks, we will have at most 2,000 derived classes and secondly, the underlying OODB will be bogged down.
I was thinking of System.AddIn at one point but am convinced that this scenario has a better solution within OOP design.
I doubt that System.AddIn is suitable for this kind of thing. IMHO System.AddIn is for more static APIs and not for something that is going to be extended rapidly. Maybe you could have a look at MEF instead which is simpler and is based on extensibility and composition.
As you say, inheritance is also not the way to go because having 2000 derived classes will be a nightmare.
I think you should look for design patterns that are based on composition instead of inheritance. There are a few of them. One of them is the Composite pattern. With this pattern, you could have some very simple reusable tasks which you can combine into more complicated tasks. You can have tasks that include subtasks, that include subtasks and on and on.
Also you could look at the dynamic languages that can be hosted on the DLR. Like IronPython. You could create a script repository. Each script a task.
Also for inspiration you could have a look at Windows Workflow Foundation and specifically the Activities.
What is kind of obvious is that you need to maximize reuse. Of course this is easier said than done.
Best regards and good luck.

helper functions as static functions or procedural functions?

i wonder if one should create a helper function in a class as a static function or just have it declared as a procedural function?
i tend to think that a static helper function is the right way to go cause then i can see what kind of helper function it is eg. Database::connect(), File::create().
what is best practice?
IMO it depends on what type of helper function it is. Statics / Singletons make things very difficult to test things in isolation, because they spread concrete dependencies around. So if the helper method is something I might want to fake out in a unit test (and your examples of creating files and connecting to databases definitely would fall in that category), then I would just create them as instance methods on a regular class. The user would instantiate the helper class as necessary to call the methods.
With that in place, it is easier to use Inversion of Control / Dependency Injection / Service Locator patterns to put fakes in when you want to test the code and you want to fake out database access, or filesystem access, etc.
This of course has the downside of there theoretically being multiple instances of the helper class, but this is not a real problem in most systems. The overhead of having these instances is minimal.
If the helper method was something very simple that I would never want to fake out for test, then I might consider using a static.
Singleton solves the confusion.
MyHelper.Instance.ExecuteMethod();
Instance will be a static property. Benefit is you get simple one line code in calling method and it reuses previously created instance which prevents overhead of instance creation on different memory locations and disposing them.

Resources