Is there a simple means of adding an aspect to an existing VB.NET method? - vb.net

I know there are numerous aspect-oriented frameworks for VB.NET. It's a little heavy to pull an entire framework into play in order to add an aspect to a couple methods. Does VB.NET offer a simple means (via some sort of metaprogramming/reflection) in which to layer an aspect over an existing method in a class/object?
Basically, the goal is intercept a method's incoming message to invoke it and add side effects or to manipulate the request, just as one would normally do in standard AOP.
Are there any plans to integrate aspects directly into the language?

Is polymorphism not an option in this case? I think you'll find that, outside of an AOP framework of some kind, there is no way in VB to change the functionality of an existing class. You can inherit and override base members, or you can use extension methods to add additional functionality to an existing class, but there's no way to alter existing functionality in an existing class.
It is possible to create a new library that mimics another existing library and trick existing code into thinking your new library is the original one, but unless absolutely necessary, this is a bad idea. Chances you just need to rethink your design in a standard OOP way rather than thinking in AOP terms.

How about the decorator (or proxy) pattern? Since it's only a few methods, then you only need one or two decorator classes. If you discover later that it's not just one or two methods, then you can consider bringing in an AOP tool.
Here's an example in C# that should translate pretty easily to VB.NET

Related

Converting the interfaces in hierarchical structure in OOD

I have a question about Facade design pattern. As i started learning design patterns from the book: Elements of re-useable object -oriented-software, there is a good explaination of what it is and how it solves the problem.
This Picture comes from that book:
Problem:
Suppose i add some extra functionality in the subsystem for which Domain is an Facade/interface. With this design, i think it's not possible to add extra functionality in the subsystem without changing the Domain class?
Second, suppose i use an abstract class Domain(to create a hierarchical structure) and delegate all the requests to it's subclasses so that whenever i want to add new functionality , i simply extend my new class/subsystem with Domain(abstract), would that be wrong or still i will have a Facade structure?
Same thing happends in Adapter pattern. We can have different kind of adapter and instead of hard-coding one class , can we create such an hierarchial structure without violating any OOD rule?
The facade as well as the adapter design patterns are part of the so called "wrapper" patterns (along with decorator and proxy). They essentially wrap certain functionality and provide a different interface. Their difference is on their intent:
facade: is used to provide a simple interface to clients, hiding the complexities of the operations it provides behind it
adapter: allows two incompatible interfaces to work together without changing their internal structure
decorator: allows new functionalities to be added to an object statically or dynamically without affecting the behavior of objects of the same class
proxy: a class (proxy) is used to represent and allow access to the
functionality of another class
If your components "in the back" add new functionality and you want your facade to expose this functionality, you would have to adjust your facade to do so.
If you have the Domain class (facade in your scenario) as an abstract class that others extend, you do not have a facade, you have whatever inheritance you created with your classes. Simply put there is no "wrapping" for achieving the intent of the facade pattern.
With this design, I think it's not possible to add extra functionality in the subsystem without changing the Domain class?
True. However, the changes you make may (or may not) affect the client (Process) class. If you add a new method to the Façade, it won't break the "old" clients. Although it's not its explicit intention (which is to hide complexities of a sub-system), Façade can provide a stable interface to its clients that can be extended. When I say interface, I don't mean a Java or C# interface. It's a programming interface.
A real-world example is the JOptionPane Façade in Java/Swing. Check the Java doc at the link I put and you'll see that some of its methods existed in 1.4, some in 1.6, etc. Basically, since this class is part of a Swing library, it had to remain stable so old clients of it's interface would not break. But it was still extended with new functionality by simply adding new methods.
I would say this is how Façades are typically extended, not with sub classing or hierarchy. Hierarchies are difficult to maintain, because they are brittle. If you get the abstraction wrong (the root of the hierarchy), then it affects the entire tree when you need to change it. Hierarchies make sense when the abstraction in the hierarchy is stable (certain).
The Adapter pattern has hierarchy because an Adapter adapts a method to work with several variants of a service that cannot be changed. You can see examples of several stable (abstract) services such as tax calculation, accounting services, credit authorization, etc. at https://stackoverflow.com/a/13323703/1168342.

Implementing .Net DI Compile Time Proxies?

I'm not so much seeking a specific implementation but trying to figure out the proper terms for what I'm trying to do so I can properly research the topic.
I have a bunch of interfaces and those interfaces are implemented by controllers, repositories, services and whatnot. Somewhere in the start up process of the application we're using the Castle.MicroKernel.Registration.Component class to register the classes to use for a particular interface. For instance:
Component.For<IPaginationService>().ImplementedBy<PaginationService>().LifeStyle.Transient
Recently I became interested in creating an audit trail of every class and method call. There's a few hundred of these classes so writing a proxy class for each one by hand isn't very practical. I could use a template to generate the code but I'd rather not blow up our code base with all that.
So I'm curious if there's some kind of on the fly solution. I know nHibernate creates proxy classes at some point which overlay all the entity classes. Can someone give me some guidance on how I might be able to do something similar here?
Something like:
Component.For<IPaginationService>().ImplementedBy<ProxyFor<PaginationService>>().LifeStyle.Transient
Obviously that won't work because I can only use generics to generalize the types of methods but not the methods themselves. Is there some tricky reflection approach I can use to do this?
You are looking for what Castle Windsor calls interceptors. It's an aspect-oriented way to tackle cross-cutting concerns -- auditing is certainly one of them. See documentation, or an article about the approach:
Aspect oriented programming is an approach that effectively “injects” pieces of code before or after an existing operation. This works by defining an Inteceptor wrapping the logic being invoked then registering it to run whenever a particular set/sub-set of methods are called.
If you want to apply it to many registered services, read more about interceptor selection mechanisms: IModelInterceptorsSelector helps there.
Using PostSharp, things like this can be even done at compile time. This can speed the resulting application, but when used correctly, interceptors are not slow.

Is creating a module with interfaces only a good idea?

Creating a module (bundle, package, whatever) with only interfaces seems to me a strange idea. Yet, I don't know the other best solution to solve the following architectural requirement.
There often appears a need for a set of utilities. In many projects I can see the creation of "utils" folder, or even a seperate package (module) with frequently used ones.
Now consider the idea that you don't want to depend upon a concrete utils set. Instead you, therefore, use interfaces.
So you may create the whole project, with multiple modules, dependent only on the "Utils-Interfaces" set, which could be a separate module. Then you think you can re-use it in other projects, as these utils are frequently used.
So what do you do? Create a seperate module (package, bundle...) with interfaces with definitions of the methods to be implemented by concrete utility-classes? And re-use this "glue-interfaces-packages" (possibly with other "glues", such as bridges, providers etc.) in your various other projects? Or is there a better way to design the archictecture regarding the utilities that could be easily switched from one to another?
It seems a bit odd to have an interface for utility methods as it should be clear what they do. Also in most language you won't have static dispatch anymore. And you wouldn't solve a problem by having interfaces for utility methods. I think it would make more sense to look for a library doing the same thing or writing your own if such functionality isn't already implemented. Very specific things should be tied to the project, though.
Let's look at an example in Java:
public static boolean isDigitOnly(String text) {
return "\\d+".matches(text);
}
Let's assume one would use an interface. That would mean that you have to have an instance of such an implementation, most likely a singleton. So what's the point of that? You would write the method head twice and you don't have any advantage; interfaces are used for loose coupling, however such generic utility methods aren't bound to your application.
So maybe you just want to use a library. And actually there is one for exactly this use case: Apache Commons. Of course you may not want to include such a big library for a single method. However, if you need this many utility methods you may want to use it.
Now I've explained how to use and reuse utility methods; however, a part of your question was about using different implementations.
I can't see many cases you wanted this. If, for example, you have a method specific to a certain implementation of sockets, you may instead want
A) the utility method as a part of the API
B) an interface for different socket implementations on which you have one common utility method
If you cannot apply this to your problem, it's probably not a utility method or I didn't consider it. If you could provide me with a more specific problem I'd be happy to give you a more concrete answer.

What is the correct system design when dealing with third party API?

This blog post by Joubert just opened my eyes. I have dealt with a lot of design patterns in Java and other languages. But Objective-C is a rather unique language.
Let's say that in a project we talk with a third party API, like Dropbox or Facebook. What I've been doing so far is to combine everything that has to do with the third party API into a singleton class. So I can access the class from anywhere in my view controllers. I can just go for example: [[DropboxModel sharedInstance] uploadFile:aFile]
However as the blog post noted, this isn't efficient and leads to spaghetti code and bad unit testing. So what is the best way to design the system so that it's modular and easy to use?
I would dispute the idea that singletons lead to spaghetti code and are inefficient. However, the unit testing problem is legitimate and singletons do reduce modularity since they are really just fancy global variables.
I like Joubert's idea of injecting the singleton instance into the controller(s) from the app delegate (which is itself a singleton, ahem). I think the same approach would work for you.
What I normally do in these situations where I might want to use a different stub object in unit tests is define a protocol to represent the API and make my "real" API object conform to it and also my stub API object. I use the stub in the unit tests and the real object in the app.
Not that this really solves any architectural problems associated with singletons, but for the sake of readability and typability you can always define a macro in your DropboxModel header file, eg:
#define DBM [DropboxModel sharedInstance]
<...>
[DBM uploadFile:aFile];
i'll typically create an abstraction layer. this wraps a simple interface onto the library's calls which you use, while giving you a chance to introduce whatever state (e.g. variables) you'll need.
you can then expose only what you need and use, and add your own state, checks, and conveniently deal with all issues of the library from one place. 'issues' may be introduced for several reasons - it could be threading, resources, state, or undesired behavioral changes across versions.
most libraries are not meant to be used solely via a singleton. in such cases, it's best (subjective) to create interfaces as you would normally -- of course, being mindful of the constraints behind the abstraction layer. in that sense, you simply create object based interfaces which are divided by size/task/purpose/functionality -- all as you'd usually do when writing your own classes.
if you don't need the library all over the place, then i think it's also good to wrap what you need to minimize dependencies (increasingly important in large projects).
if you use the library all over the place, then you may also prefer to use the calls without the abstraction layer.

When do you need to create abstractions in the form of interfaces?

When do you encourage programming against an interface and not directly to a concrete class?
A guideline that I follow is to create abstractions whenever code requires to cross a logical/physical boundary, most especially when infrastructure-related concerns are involved.
Another checkpoint would be if a dependency will likely change in the future, due to possible additional concerns code (such as caching, transactional awareness, invoking a webservice instead of in-process execution) or if such dependencies have direct references to infrastructure integration points.
If code depends on something that does not require control to cross a logical/physical boundary, I more or less don't create abstractions to interact with those.
Am I missing anything?
Also, use interfaces when
Multiple objects will need to be acted upon in a particular fashion, but are not fundamentally related. Perhaps many of your business objects access a particular utility object, and when they do they need to give a reference of themselves to that utility object so the utility object can call a particular method. Have that method in an interface and pass that interface to that utility object.
Passing around interfaces as parameters can be very helpful in unit testing. Even if you have just one type of object that sports a particular interface, and hence don't really need a defined interface, you might define/implement an interface solely to "fake" that object in unit tests.
related to the first 2 bullets, check out the Observer pattern and the Dependency Injection. I'm not saying to implement these patterns, but they illustrate types of places where interfaces are really helpful.
Another twist on this is for implementing a couple of the SOLID Principals, Open Closed principal and the Interface Segregation principle. Like the previous bullet, don't get stressed about strictly implementing these principals everywhere (right away at least), but use these concepts to help move your thinking away from just what objects go where to thinking more about contracts and dependency
In the end, let's not make it too complicated: we're in a strongly typed world in .NET. If you need to call a method or set a property but the object you're passing/using could be fundamentally different, use an interface.
I would add that if your code is not going to be referenced by another library (for a while at least), then the decision of whether to use an interface in a particular situation is one that you can responsibly put off. The "extract interface" refactoring is easy to do these days. In my current project, I've got an object being passed around that I'm thinking maybe I should switch to an interface; I'm not stressing about it.
Interfaces abstraction are convenient when doing unit test. It helps for mocking test objects. It very useful in TDD for developing without actually using data from your database.
If you don't need any features of the class that aren't found in the Interface...then why not always prefer the Interface implementation?
It will make your code easier to modify in the future and easier to test (mocking).
you have the right idea, already. i would only add a couple of notes to this...
first, abstraction does not mean 'interface'. for example, a "connection string" is an abstraction, even though it's just a string... it's not about the 'type' of the thing in question, it's about the intention of use for that thing.
and secondly, if you are doing test automation of any kind, look for the pain and friction that are exposed by writing the tests. if you find yourself having to set up too many external conditions for a test, it's a sign that you need a better abstraction between the thing your testing and the things it interacts with.
I think you've said it pretty well. Much of this will be a stylistic thing. There are open source projects I've looked at where everything has an interface and an implementation, and it's kind of frustrating, but it might make iterative development a little easier, since any objects implementation can break but dummies will still work. But honestly, I can dummy any class that doesn't overuse the final keyword by inheritance.
I would add to your list this: anything which can be thought of as a black box should be abstracted. This includes some of the things you've mentioned, but it also includes hairy algorithms, which are likely to have multiple useful implementations with different advantages for different situation.
Additionally, interfaces come in handy very often with composite objects. That's the only way something like java's swing library gets anything done, but it can also be useful for more mundane objects. (I personally like having an interface like ValidityChecker with ways to and-compose or or-compose subordinate ValidityCheckers.)
Most of the useful things that come with the Interface passing have been already said. However I would add:
implementing an interface to an object, or later multiple objects, FORCES all the implementers to follow an IDENTICAL pattern to implement contract with the object. This can be useful in case you have not so OOP-experienced-programmers actually writing the implementation code.
in some languages you can add attributes on the interface itself, which can be different from the actual object implementation attribute as sense and intent