How to decide an object behavior through the web.config? - vb.net

I want to be able to define in my web.config the type of connexion my object will use to get data (variable) (from an xml or from a databases).
I though about using a Strategie Pattern, but I'm somewhat stuck by the need to write somewhere the name of the class, which I do not want.
Any suggestions?
Additionnal info
I have the interface IContext.
It's implemented in ContextXML and ContextDB.
I have the class Context which has a IContext member (called _context).
The Context class reads (through ContextConfiguration) app.config.
I want _context to be able to be a ContextXML or a ContextDB... or a ContextJSon or any other new class that would implements IContext.

Have you thought about creating a ContextManager class and employing "configuration by convention"?
What I would do, is add a member getName to your IContext interface - this just returns a nice human-readable string for each implementation - as simple as "ContextXML" for your ContextXML class.
When your ContextManager (probably a Singleton, BTW) starts up, it scans a known directory for IContext implementations, instantiating them by reflection (or some other mechanism, I'm not familiar with VB.Net but I'm sure there's a way), and placing them in a collection.
Now when you are building up Context objects, you can ask your ContextManager for a suitable IContext - either explicitly [e.g. getIContextByName("ContextDB")] or with a simpler method that just returns whatever has been configured by some other mechanism - i.e. a suite of methods something like this:
getPossibleIContextImplementationNames()
setCurrentIContextImplementation({name})
getCurrentIContext()
Just as an aside, are you stuck with that naming? Because having a Context object that uses an IContext seems a little unusual. If your IContext implementations are actually used to retrieve data from somewhere, why not call the interface IDAO or IDataAccessor?

Related

Why does ByteBuddy route method delegation to the "wrong" method in this scenario?

I am putting together a very simple ByteBuddy delegate/proxy class.
The intention is (again, very simple) to proxy a class such that any of its non-final, non-private, non-static methods and so forth get routed to equivalent methods on its proxiedInstance field as returned by its getProxiedInstance method. (There should be exceptions made for the usual suspects: equals, hashCode, wait and notify and so on.)
I've set up my proxy class using the subclass strategy. I've also defined two methods, getProxiedInstance and setProxiedInstance, along with a private field named proxiedInstance of the proper type. I've done this using the FieldAccessor.ofBeanProperty() strategy. I've omitted that here for brevity and clarity. The class does in fact contain this field and these two methods.
Then I've defined the method interception like this, statically importing the relevant ElementMatchers methods:
builder
.method(not(isFinal()).and(not(isStatic())).and(not(isPrivate()))
.and((isPublic().and(named("toString")).and(takesArguments(0)).and(returns(String.class)))
.or((not(isDeclaredBy(Object.class)).and(not(named("getProxiedInstance"))).and(not(named("setProxiedInstance"))))))
)
.intercept(MethodDelegation.toMethodReturnOf("getProxiedInstance"));
In English: not final, not static, not private, and either the public String toString() method inherited from Object (or overridden), or any other method not declared by Object.class and not named getProxiedInstance or setProxiedInstance.
Suppose I have a class like this:
public class Frob {
public String sayHello() {
return "Hello!";
}
}
When I create a proxy class for it, instantiate it, and then call toString() on the proxy, I get Hello!.
This suggests to me somehow that the recipe I've quoted above is somehow routing toString() to sayHello().
From reading the MethodDelegation javadocs, it seems that maybe sayHello on the target/delegate object is picked for delegation because it is more specific than the method invoked on the proxy (toString). I guess name matching is lower priority than that.
I think this use case I have is relatively simple. How do I best accomplish it?
The best I could do, which works, but seems perhaps a little clunky or verbose, was this:
builder = builder
.method(not(isDeclaredBy(Object.class))
.and(not(isFinal()))
.and(not(isStatic()))
.and(not(isPrivate()))
.and(not(named("getProxiedInstance")))
.and(not(named("setProxiedInstance"))))
.intercept(MethodDelegation.toMethodReturnOf("getProxiedInstance"))
.method(is(toStringMethod))
.intercept(invoke(toStringMethod).onMethodCall(invoke(named("getProxiedInstance"))));
(toStringMethod is the Method resulting from Object.class.getMethod("toString").)
I think using MethodCall is a better approach to this. MethodDelegation is meant for "catch all proxies" where you inject corresponding dispatchers into what is often a single delegate method, maybe two. Method call is also much more performance since it does not need to do the analysis but just reroutes to a method of a compatible type.

When to use singletons in OOP?

When reading about singletons, I have found this explanation as a reason to use singleton:
since these object methods are not changing the internal class state, we
can create this class as a singleton.
What does this really mean ? When you consider that some method is not changing internal class state ? If it is a getter ? Can someone provide code examples for class that uses methods that are not changing its internal state, and therefore can be used as a singleton, and class that should not be a singleton ?
Usually, when people are explaining singleton pattern, they use DB connection class as an example. And that makes sense to me, because I know that I want to have only one db connection during one application instance. But what if I want to provide an option to force using the new connection when I instantiate DB connection class? If I have some setter method, or constructor parameter that forces my class to open new connection, is that class still a subject to be a singleton ?
I am using PHP, but may understand examples written in JAVA, C#...
This is the article reference. You can ctrl+f search for "internal". Basically, autor is explaining why FileStorage class is a good candidate to be a singleton. I do not understand this sentance
"These operations do not change the internal class state, so we can
create its instance once and use it multiple times."
and therefore I do not understand when to use singletons.
In their example, they have some FileStorage class :
class FileStorage
{
public function __contruct($root) {
// whatever
}
public function read() {
// whatever
}
public function write($content) {
// whatever
}
}
And they say that this class can be a singleton since its methods read() and write() do not chage internal class structure. What does that mean ? They are not setters and class is automatically singleton ?
The quote reads:
These operations do not change the internal class state, so we can create its instance once and use it multiple times.
This means that the object in question has no interesting internal state that could be changed; it’s just a collection of methods (that could probably be static). If the object has no internal state, you don’t have to create multiple instances of it, you can keep reusing a single one. Therefore you can configure the dependency injection container to treat the object as a singleton.
This is a performance optimization only. You could create a fresh instance of the class each time it’s needed. And it would be better – until the object creation becomes a measurable bottleneck.

difference between class and instance structure

I'm currently trying to learn how to use GObject and there's a point I absolutely don't understand: What's the difference between the class and the instance structure (like "MamanBarClass" and "MamanBar") resp. how do I use them? At the moment I'd put all my object attributes into a private structure (like "MamanBarPrivate"), register it with "g_type_class_add_private" and define properties/getters/setters to access them. But when I leave the class structure empty I get the following error at "g_type_register_static_simple":
specified class size for type `MamanBar' is smaller than `GTypeClass' size
And why are all object methods defined in the class structure (like "GtKWidgetClass")? Probably I'm just screwing up everything, but I only worked with Delphi for OOP yet (I know, nothing to be proud about :D)
Regards
I'm currently trying to learn how to use GObject and there's a point I absolutely don't understand: What's the difference between the class and the instance structure (like "MamanBarClass" and "MamanBar") resp. how do I use them?
The class structure is only created once, and is not instance-specific. It's where you put things which are not instance-specific, such as pointers for virtual methods (which is the most common use for the class struct).
At the moment I'd put all my object attributes into a private structure (like "MamanBarPrivate"), register it with "g_type_class_add_private" and define properties/getters/setters to access them.
Good. That's the right thing to do.
But when I leave the class structure empty I get the following error at "g_type_register_static_simple":
You should never leave the class structure empty. It should always contain the class structure for the type you're inheriting from. For example, if you're trying to create a GObject, the class structure should look like this (at a minimum):
struct _MamanBarClass {
GObjectClass parent_class;
};
Even if you're not inheriting from GObject, you still need the base class for GType:
struct _FooClass {
GTypeClass parent_class;
};
This is how simple inheritance is done in C.
And why are all object methods defined in the class structure (like "GtKWidgetClass")? Probably I'm just screwing up everything, but I only worked with Delphi for OOP yet (I know, nothing to be proud about :D)
Those are virtual public methods. As for why they're defined in the class structure instead of the instance structure, it's because the implementations are the same for every instance.

Network storage design pattern

Let's say I have a few controllers. Each controller can at some point create new objects which will need to be stored on the server. For example I can have a RecipeCreationViewController which manages a form. When this form is submitted, a new Recipe object is created and needs to be saved on the server.
What's the best way to design the classes to minimize complexity and coupling while keeping the code as clean and readable as possible?
Singleton
Normally I would create a singleton NetworkAdapter that each controller can access directly in order to save objects.
Example:
[[[NetworkAdapter] sharedAdapter] saveObject:myRecipe];
But I've realized that having classes call singletons on their own makes for coupled code which is hard to debug since the access to the singleton is hidden in the implementation and not obvious from the interface.
Direct Reference
The alternative is to have each controller hold a reference to the NetworkAdapter and have this be passed in by the class that creates the controller.
For example:
[self.networkAdapter saveObject:myRecipe];
Delegation
The other approach that came to mind is delegation. The NetworkAdapter can implement a "RemoteStorageDelegate" protocol and each controller can have a remoteStorageDelegate which it can call methods like saveObject: on. The advantage being that the controllers don't know about the details of a NetworkAdapter, only that the object that implements the protocol knows how to save objects.
For example:
[self.remoteStorageDelegate saveObject:myRecipe];
Direct in Model
Yet another approach would be to have the model handle saving to the network directly. I'm not sure if this is a good idea though.
For example:
[myRecipe save];
What do you think of these? Are there any other patterns that make more sense for this?
I would also stick with Dependency Injection in your case. If you want to read about that you will easily find good articles in the web, e.g. on Wikipedia. There are also links to DI frameworks in Objective C.
Basically, you can use DI if you have two or more components, which must interact but shouldn't know each other directly in code. I'll elaborate your example a bit, but in C#/Java style because I don't know Objective C syntax. Let's say you have
class NetworkAdapter implements NetworkAdapterInterface {
void save(object o) { ... }
}
with the interface
interface NetworkAdapterInterface {
void save(object o);
}
Now you want to call that adapter in a controller like
class Controller {
NetworkAdapterInterface networkAdapter;
Controller() {
}
void setAdapter(NetworkAdapterInterface adapter) {
this.networkAdapter = adapter;
}
void work() {
this.networkAdapter.save(new object());
}
}
Calling the Setter is where now the magic of DI can happen (called Setter Injection; there is also e.g. Constructor Injection). That means that you haven't a single code line where you call the Setter yourself, but let it do the DI framework. Very loose coupled!
Now how does it work? Typically with a common DI framework you can define the actual mappings between components in a central code place or in a XML file. Image you have
<DI>
<component="NetworkAdapterInterface" class="NetworkAdapter" lifecycle="singleton" />
</DI>
This could tell the DI framework to automatically inject a NetworkAdapter in every Setter for NetworkAdapterInterface it finds in your code. In order to do this, it will create the proper object for you first. If it builds a new object for every injection, or only one object for all injections (Singleton), or e.g. one object per Unit of Work (if you use such a pattern), can be configured for each type.
As a sidenote: If you are unit testing your code, you can also use the DI framework to define completely other bindings, suitable for your test szenario. Easy way to inject some mocks!

specific questions about scope and property reference in actionscript 3

I've been battling with AS3 for a little while now, and I'm working on a simple application using only actionscript and the FlashDevelop/flex-compiler combo. I've hit a bit of a wall in my fledgling OOP understanding, and I'm wondering whether someone might be able to point me in the right direction. I have genuinely read several books, and spent many hours reading online tutorials etc, but something's just not clicking!
What's baffling me is this: When something is declared 'public', according to what I read, it is therefore available anywhere in the application (and should therfore be used with care!) However, when I try to use public properties and methods in my program, they most definitely are not available anywhere other than from the class/object that instantiated them.
This leads me to conclude that even if objects (of different class) are instantiated from the same (say 'main') class, they are not able to communicate with each other at all, even through public members.
If so, then fair enough, but I've honestly not seen this explained properly anywhere. More to the point, how do different objects communicate with other then? and what does Public actually mean then, if it only works through a direct composition hierarchy? If one has to write applications based only on communication from composer class to it's own objects (and presumably use events for, er, everything else?) - isn't this incredibly restrictive?
I'm sure this is basic OOP stuff, so my apologies in advance!
Any quick tips or links would be massively appreciated.
There are different topics you are covering in your question. Let me clarify:
What does the modifier public mean?
How can instances of the same class communicate to each other?
--
1.
In OOP you organize your code with objects. An object needs to be instantiated to provide its functionality. The place where you instantiate the object can be considered as the "context". In Flash the context might be the first frame, in a pure AS3 movie, it might be the main class, in Flex it could be the main mxml file. In fact, the context is always an object, too. Class modifier of your object public class MyClass tells your context whether it is allowed to instantiate the object or not. If set to internal, the context must live in the same directory as the class of the object. Otherwise it is not allowed to create a new object of the class. Private or protected are not valid class modifiers. Public class ... means that any context may create an object of that class. Next: Not only instantiation is controlled by these modifiers but also the visibility of a type. If set to internal, you cannot use an expression like var obj : InternalType in a context that does not live in the same directory as Internal type.
What about methods and properties? Even if your context is allowed to access a type, certain properties and methods might be restricted internal/protected/private var/method and you perhaps are not able to invoke them.
Why we're having such restrictions? Answer is simple: Differnent developers may develop different parts of the same software. These parts should communicate only over defined interfaces. These interfaces should be as small as possible. The developer therefore declares as much code as possible to be hidden from outside and only the necessary types and properties publicly available.
Don't mix up with modifiers and global properties. The modifier only tells you if a context is allowed to see a type or method. The global variable is available throughout the code. So even if a class is declared to be public, instances of that class do not know each other by default. You can let them know by:
storing the instances in global variables
providing setter such as set obj1(obj1 : OBJ1) : void where each object needs to store the reference in an instance variable
passing the object as method arguments: doSomething(obj1 : OBJ1)
Hope this helps you to more understand OOP. I am happy to answer your follow up questions.
Jens
#Jens answer (disclaimer: I skimmed) appears to be completely correct.
However, I'm not sure it answers your question very directly, so I'll add a bit here.
A public property is a property of that class instance that is available for other objects to use(function: call, variable: access, etc). However, to use them you must have a reference (like a very basic pointer, if that helps?) to that object instance. The object that instantiates (creates, new ...) that object can take that reference by assigning it to a variable of that class type.
// Reference is now stored in 's'
public ExampleClass s = new ExampleClass();
If you'd like to, you do have the option of making a static property, which is available just by knowing the class name. That property will be shared by all instances of that class, and any external class can refer to it (assuming it's public static) by referring to the class name.
A public property is referred to by the reference you stored.
//public property access
s.foo
s.bar(var)
A static property is referred to by the class name.
//static property access
ExampleClass.foo
ExampleClass.bar(var)
Once you've created the instance, and stored the reference, to an object, you can pass it around as you'd like. The below object of type OtherExampleClass would receive the reference to 's' in its constructor, and would have to store it in a local variable of its own to keep the reference.
public OtherExampleClass s2 = new OtherExampleClass(s);