Qt has a build-in supprt for creating objects with integrated reference counting via QSharedData and QSharedDataPointer. All works great, but for each such object I need to write a lot of code: QSharedData-based implementation class with constructor and copy constructor, object class itsef with accessor methods for each filed.
For a simple structures with 5-10 fields this requires really lot of near same code. Is it some ways to automate such classes generation? Maybe it's some generators exists that take a short description and automatically generates implementation class and object class with all accessors?
You usually don't have to implement copy ctor or operator= when using QSharedData/Pointer. The default impls copy/assign the QSharedData-derived member, which usually does the Right Thing (TM).
For the public class, you need to implement the ctor creating the private object, and if the private class is not declared in the header but in the implementation (which is better), a dtor (doing nothing, the only point is that is not inlined and defined in the .cpp, after the private declaration).
For the private class, no method/ctor/dtor implementations are necessary.
For simple value-based classes, writing setters is of course tedious, but the same is true if you use plain private member variables. The overhead in LOC doesn't grow with the number of members.
And no, there is no standard generator solution for that I know of, although writing a script or emacs macro etc. doing it is not that hard. Probably would make sense to add such things to a publicly available toolbox, or QtCreator...
I don't think generators would exist for these things, but I suggest two things:
(ab)use existing shared containers (QVector, QList...)
read the documentation (with examples) on QSharedData, QSharedDataPointer, and QExplicitelySharedDataPointer
The two subclasses have simple examples that show how to implement the shared-ness it seems. I can't help you further though, because I've never had the need to create my own.
On second thought, why not make all data fields public, and use the QSharedData derivative as a struct-like class with reference counting? Maybe not nice on encapsulation, but if you're careful, nothing wrong should happen.
Related
Can we mock private methods without using powermockito. I know it is possible though powermockito but just wanted to check with all, is it possible by some other means.
Thanks
-Sam
By design, this isn't possible without PowerMockito or a similar tool.
See Mockito's Wiki where they give the following reasons:
It requires hacking of classloaders that is never bullet proof and it
changes the API (you must use custom test runner, annotate the class,
etc.).
It is very easy to work around - just change the visibility of
method from private to package-protected (or protected).
It requires
the team to spend time implementing & maintaining it. And it does not
make sense given point (2) and a fact that it is already implemented
in different tool (powermock).
Finally... Mocking private methods is a
hint that there is something wrong with Object Oriented understanding.
In OO you want objects (or roles) to collaborate, not methods. Forget
about pascal & procedural code. Think in objects.
There are of course cases where it is not possible to work around, but just take a step back and
Make sure that you are testing the correct things (should you be testing private methods instead of the public ones)
Consider just changing these methods to be package private instead of relying on PowerMock.
Yes we can use the Reflection API for this which provided by Java vendor.
Im using phpunit. But you know its difficulties, no possibility to mock private functions, to access private variables, etc. Is there a tool which help me? Something to turn private functions to public, turn static method to mockable, etc
Not directly answering your question, but the best "tool" for making phpunit easier is good design of your code. If you are not sure what the good design would be for a given problem, you are already using the other good tool available to you - this site.
The things that you mention in your question as causing difficulties are generally difficult because there are issues with the design of your code. If it is hard to test, it will be hard to refactor, use, and maintain. The tests show you this early in your coding process and allow you to make changes to save your future self from issues.
For example in the difficulties from your question:
Mocking private functions - This is a smell that there is a second
class that needs to be created. Your object may be violating the
Single Responsibility Principle. This function should probably be
moved into its own object and passed in to system under test.
Access private variables - PHPUnit does have assertions for object
attributes (assertAttributeEquals, etc.). However this really
isn't something that you should need to use. A private variable is
an implementation detail of your object, there should be some sort of
public method that you can use to verify that the proper information
was set (a getter or dependency injected mock object)
Mocking static methods - There are many questions on SO about this
difficulty and many resources saying how static methods are not good
design. If you need to mock a static method, that means that you are
affecting global state. Static methods are also hiding dependencies
from users of your object and make things difficult to modify. Your
design becomes less flexible and more modular.
Yo do not need to test private methods and attributes. They're private for a reason and have sense only when called from inside the class that holds them. More, if you test a public method, you are also indirectly testing the private methods that it calls, and the result of the public function also might depend on some private attributes, which you are also testing with the public method.
If you test all public methods of a class (i.e. its interface), and by this I mean full code/branch coverage on those methods, then you are testing all private methods/attributes that are needed. If after testing all public stuff you are left with some pieces of code that wasn't reached, then you can safely delete that code, as it's of no use.
I have a series of classes that have a number of analogous Shared methods that I want to ensure are implemented in a consistent manner in each class. These Shared methods are called via reflection in various areas of code, and up to this point I’ve been keeping them in synch manually. As the number of classes grows, ensuring synchronization is becoming a bit tedious – as is the process to ensure, when I add a new Shared method to the paradigm, that it is indeed implemented in all of the classes to prevent run-time errors when reflection comes looking for them.
I’d initially thought this would be an ideal use of interfaces, but per various threads (such as Why we can not have Shared(static) function/methods in an interface/abstract class?) you cannot define Shared methods as part of an interface. I then tried to define a common base class and mark these methods MustOverride, but you cannot do that either. I’ve looked into delegates (which I’ve not used before), but it appears to allow the opposite of what I’m trying to do (namely, delegates seem to allow a common implementation of a common need from multiple classes instead of a unique implementation of a common need from multiple classes).
As such, is there an approach in VB.Net to ensure at compile-time that each of my classes implements a set of common Shared methods and functions in a consistent manner?
As a side note, the classes in question are currently all extensions of Entity Framework classes and are being blended into the EF classes.
EDIT: As a alternative to a language feature (which may not exist), I'd also be open to suggestions on any refactoring-type tools that provide this sort of functionality.
Here is sort of the skeleton of code I'm using:
Public MustInherit Class AbstractUpdateItem
Public MustOverride Function ValidateFields(ByRef dto As BusinessDTO) As Boolean
End Class
Public Class UpdateSomeFields
Inherits AbstractUpdateItem
Public Overrides Function ValidateFields(ByRef dto As BusinessDTO) As Boolean
' some code here to do the real stuff
End Function
End Class
When I comment out one of my Overrides Function (ValidateFields), I get a compile time error: Class x must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): ValidateFields. So that would seem to ensure that they implement a set of methods. They aren't declared as shared, but will that do what you want?
Approach one : creating object of the subclass through reference of base class.
Approach Two : creating object of the subclass through reference of same class.
List<Point> objOne = new ArrayList<Point>();
ArrayList<Point> objTwo = new ArrayList<Point>();
List is an Interface even. It is more abstract and defines exactly but not more, the API properties. The implementation can differ in Java: ArrayList for bulk work, LinkedList for just a couple, saving on memory. This implementation decision should be hidden.
Functions should operate on List more than on a specific implementation, say ArrayList. It is also more generally formulated if one talks about Lists instead of ArrayLists. So also for variables I would not overspecify their type.
In many (scripting) languages like VB, PHP and others this distinction does not exist, and there is one type with one implementation. This simplifies their language and might appeal to some, but Java has a nice technical side.
You can play with different implementations, dynamically elect one with a factory method. Mock the implementation in a unit test.
List is an interface while ArrayList is a Class.
So lets suppose your co-worker wrote a function which takes in a list of points and does some work on it.
Now he used abstraction like this so that his code could work on both ArrayList as well as LinkedList.
public void myfunction(List<Point> pointlist){
//do something on the point
}
Now your first object objOne will work with this function because it has used Abstraction. This is how good code should be written.
Now your second object objTwo will not work with this function and so this kind of code should be avoided.
Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.
Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:
Given a config file with lines like
x = "Hello World!"
y = 5.0
dynamically set the fields of some config object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)
When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.
When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate
!some_command arg1 arg2
into a method call actions.some_command(arg1, arg2) and print whatever that function returned back to the IRC channel.
When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.
So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.
I can list following usage for reflection:
Late binding
Security (introspect code for security reasons)
Code analysis
Dynamic typing (duck typing is not possible without reflection)
Metaprogramming
Some real-world usages of reflection from my personal experience:
Developed plugin system based on reflection
Used aspect-oriented programming model
Performed static code analysis
Used various Dependency Injection frameworks
...
Reflection is good thing :)
I've used reflection to get current method information for exceptions, logging, etc.
string src = MethodInfo.GetCurrentMethod().ToString();
string msg = "Big Mistake";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
instead of
string src = "MyMethod";
string msg = "Big MistakeA";
Exception newEx = new Exception(msg, ex);
newEx.Source = src;
It's just easier for copy/paste inheritance and code generation.
I'm in a situation now where I have a stream of XML coming in over the wire and I need to instantiate an Entity object that will populate itself from elements in the stream. It's easier to use reflection to figure out which Entity object can handle which XML element than to write a gigantic, maintenance-nightmare conditional statement. There's clearly a dependency between the XML schema and how I structure and name my objects, but I control both so it's not a big problem.
There are lot's of times you want to dynamically instantiate and work with objects where the type isn't known until runtime. For example with OR-mappers or in a plugin architecture. Mocking frameworks use it, if you want to write a logging-library and dynamically want to examine type and properties of exceptions.
If I think a bit longer I can probably come up with more examples.
I find reflection very useful if the input data (like xml) has a complex structure which is easily mapped to object-instances or i need some kind of "is a" relationship between the instances.
As reflection is relatively easy in java, I sometimes use it for simple data (key-value maps) where I have a small fixed set of keys. One one hand it's simple to determine if a key is valid (if the class has a setter setKey(String data)), on the other hand i can change the type of the (textual) input data and hide the transformation (e.g simple cast to int in getKey()), so the rest of the application can rely on correctly typed data.
If the type of some key-value-pair changes for one object (e.g. form int to float), i only have to change it in the data-object and its users but don't have to keep in mind to check the parser too. This might not be a sensible approach, if performance is an issue...
Writing dispatchers. Twisted uses python's reflective capabilities to dispatch XML-RPC and SOAP calls. RMI uses Java's reflection api for dispatch.
Command line parsing. Building up a config object based on the command line parameters that are passed in.
When writing unit tests, it can be helpful to use reflection, though mostly I've used this to bypass access modifiers (Java).
I've used reflection in C# when there was some internal or private method in the framework or a third party library that I wanted to access.
(Disclaimer: It's not necessarily a best-practice because private and internal methods may be changed in later versions. But it worked for what I needed.)
Well, in statically-typed languages, you'd want to use reflection any time you need to do something "dynamic". It comes in handy for tooling purposes (scanning the members of an object). In Java it's used in JMX and dynamic proxies quite a bit. And there are tons of one-off cases where it's really the only way to go (pretty much anytime you need to do something the compiler won't let you do).
I generally use reflection for debugging. Reflection can more easily and more accurately display the objects within the system than an assortment of print statements. In many languages that have first-class functions, you can even invoke the functions of the object without writing special code.
There is, however, a way to do what you want(ed). Use a hashtable. Store the fields keyed against the field name.
If you really wanted to, you could then create standard Get/Set functions, or create macros that do it on the fly. #define GetX() Get("X") sort of thing.
You could even implement your own imperfect reflection that way.
For the advanced user, if you can compile the code, it may be possible to enable debug output generation and use that to perform reflection.