Should typed factory facility throw an exception when I request a component by name which is not registered? - castle-windsor

If I register a component with the container with a name (don't worry... contrived example!)
container.Register(Component.For<double>().Instance(Math.PI).Named("pi")
And ask to resolve that service type with a different name
container.Resolve<double>("e")
I get an ComponentNotFound exception. But now if I use the typed factory facility
interface IDoubleFactory { double GetDoubleByName(string name); }
container.Register(
Component.For<DoubleSelector, ITypedFactoryComponentSelector>()
Component.For<IDoubleFactory>().AsFactory(f => f.SelectedWith<DoubleSelector>())
Component.For<double>().Instance(Math.PI).Named("pi"))
public class DoubleSelector : DefaultTypedFactoryComponentSelector
{
protected override string GetComponentName(MethodInfo method, object[] arguments)
{
return arguments[0] as string;
}
}
and try to use the factory to resolve a bogus name
container.Resolve().GetDoubleByName("e")
I get pi back instead of an exception. It appears that having given a name to the ITypedFactoryComponentSelector which did not help, it has fallen back to just using the Type (in this case double) and grabbed the first thing registered against it.

The answer may be a bug in Windsor 2.5.1. The contract for ITypedFactoryComponentSelector suggests that if you return null for ComponentType but non-null for ComponentName, the lookup will be done by name, and not type. But two problems get in your way if you try to do that.
According to GitHub sources, code in DefaultTypedFactoryComponentSelector.BuildFactoryComponent calls GetCompatibleArrayItemType on what may be a null ComponentType pointer, which causes an exception. This seems like a bug, plain and simple.
If you find a way to monkey patch that, then it appears that TypedFactoryComponentResolver.Resolve method doesn't quite arrange to call the right overloads on the kernel to resolve in cases where ComponentType is null. I'm much less clear whether this is a bug or a lack in my understanding of which IWindsorContainer.Resolve methods do what. That said, a dispatch to the various methods (Resolve<object>(string key), for example) seems to do the trick.
Both classes are unsealed, so it's straightforward to fix with derived classes.

Related

Kotlin: Override (and specify) generic interface functions

I want use generic interfaces that will be specified by their implementing classes, and all in all this has been working fine, like:
interface Remove <E> { fun remove(entity: E) }
class MyHandler : Remove <MyClass> {
override fun remove(entity: MyClass) { */do stuff/* }
}
However, I have a case (so far, expecting more to come) where I want the function itself to be generic. Writing the interface is no problem at all:
interface FindByID <E> { fun <K : Serializable> findByID(id: K): E }
I need K to be serializable because that's a requirement of some function I need to call.
The compiler doesn't seem to agree with my implementation attempt. When I do this:
override fun <String> findByID(id: String): User {
return someFunction(User::class.java, id) as User
}
I get two compiler errors:
overrides nothing
id is not Serializable
However, when I remove override and <String> from the signature, it works fine. This means String is serializable, which my research shows as well.
What seems to be the problem here?
Also, yes, I know that I could work around this issue in a couple of ways, like
making the interface function accept Serializable instead of <K : Serializable>
not specifying K on override, but on call (myHandler.findByID<String>("myID"))
"rerouting" the call, implementing (not overriding) in MyHandler a function that accepts Strings and then internally calls the overriden function
Although open to suggestions, I'm less interested in workarounds, but would rather like to understand and (if possible) solve the actual problem or at least know it can't be done so I can take that into account for planning
The current problem
With your current declaration of <String>, you're not specializing the type parameter as you might think. What you're actually doing is declaring a type parameter that happens to be named String (nothing to do with the well-known String type, just an unfortunate name collision). With syntax coloring, you should see that String here is in the color of a type parameter, not the same color as the String type would be. Change this name to anything else, and you'll realize the confusion.
So if we rename this to K, the problems become obvious: problem 1 "overrides nothing" is because your generic type parameter doesn't have the same : Serializable constraint as the findByID method defined in the interface. And problem 2 stems from it.
Solutions
Also, yes, I know that I could work around this issue in a couple of ways, like
not specifying K on override, but on call (myHandler.findByID("myID"))
This point is actually the essence of the issue, not a workaround: defining a generic function in your interface actually makes it part of the contract for this function to be generic.
Implementations must have a generic type parameter here.
What to do to fix it depends on what you expect to happen.
If you're ok with having generic functions in your implementations, then leave the interface as you declared it, but accept that the implementations have to deal with all possible values of K, which is most likely not what you want here.
If you want to define a specific type in your implementations, K should be part of the interface definition (not the interface method), and the method should not have a type parameter itself, but simply accept the existing K from the interface:
interface FindByID<E, K : Serializable> {
fun findByID(id: K): E
}

Name of design pattern for method which does nothing but throw an exception upon a condition?

I've came across code with functions which do nothing except check a conditional and throw an exception or do nothing depending on the outcome of the evaluation of the conditional.
The code would look something like this:
public string MyMethod() {
var name = "foo";
EnsureSuccess(name);
return name;
}
// Throws an exception if name is not "bar"
public void EnsureSuccess(string name) {
if (name != "bar")
{
throw new ArgumentException("Not bar!");
}
}
What is this called? Is this a named design pattern?
Also is this considered a good practice or a bad practice?
Example of code in the wild that uses this is the EnsureSuccessStatusCode method in HttpResponseMessage.cs which is part of System.Net.Http by Microsoft. (code, documentation)
That's not a design pattern. It's called programming assertion.
In computer programming, an assertion is a predicate (a true–false
statement) placed in a program to indicate that the developer thinks
that the predicate is always true at that place. If an assertion
evaluates to false at run-time, an assertion failure results, which
typically causes execution to abort.
In addition to the #Chris Eelmaa answer, I'll say that also Don't_repeat_yourself principle is used. Seems that EnsureSuccess(string name) is being used a lot..otherwise I don't see the point of extracting 2 lines of code.
Another interesting thing in the example is not like you pointed
throw new Exception("Not bar!");
But according to the MSDN Best Practices for Exceptions - Don't throw new Exception()
So please note that should be
throw new SpecificException("Not bar!");
Exception is a too broad class, and it's hard to catch without side-effects. Derive your own exception class, but derive it from Exception. This way you could set a specialized exception handler for exceptions thrown by the framework and another for exceptions thrown by yourself.
In the code example they are:
throw new ArgumentOutOfRangeException ();
throw new ArgumentNullException ("......");
throw new HttpRequestException (string.Format ("{0} ({1})", (int) statusCode, ReasonPhrase));
Imagine the code of EnsureSuccess being in-line at MyMethod:
public string MyMethod() {
var name = "foo";
// Ensure success
if (name != "bar")
{
throw new ArgumentException("Not bar!");
}
return name;
}
First, it would require a comment to explain what it's doing. Second, as pointed out before, you'd be repeating this code at every place you need to check this condition.
There's a refactoring (which is like a coding pattern) called extract method that results in what you see here.
Extract method (in this case, 'Don't repeat yourself') is also an example of information hiding, since the details of EnsureSuccess are hidden away in that method. If ever a decision was made to change the logic of how EnsureSuccess works, one only changes the single method, and everywhere that calls the method will not need changing.
It might be Visitor, where you put the functions in a class.
So maybe that class EnsureSuccess would act as some kind of validator.
Maybe this class' jobs are to execute all the exception handlings?
It can also be a Facade pattern.
This pattern is very common used as a validator.
Thank you,

Test Failure Message in mockito : Argument(s) are different! Wanted:

I am testing a Restful endpoint in my JUnit and getting an exception as below in the
list which is present as an argument inside the save method,
**"Argument(s) are different! Wanted:"**
save(
"121",
[com.domain.PP#6809cf9d,
com.domain.PP#5925d603]
);
Actual invocation has different arguments:
save(
"121",
[com.domain.PP#5b6e23fd,
com.domain.PP#1791fe40]
);
When I debugged the code, the code broke at the verify line below and threw the
above exception. Looks like the arguments inside the "testpPList" within the save
method is different. I dont know how it becomes different as I construct them in my
JUNit properly and then RestFul URL is invoked.
Requesting your valuable inputs. Thanks.
Code:
#Test
public void testSelected() throws Exception {
mockMvc.perform(put("/endpointURL")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(testObject)))
.andExpect(status().isOk());
verify(programServiceMock, times(1)).save(id, testpPList);
verifyNoMoreInteractions(programServiceMock);
}
Controller method:
#RequestMapping(value = "/endpointURL", method = RequestMethod.PUT)
public #ResponseBody void uPP(#PathVariable String id, #RequestBody List<PPView> pPViews) {
// Code to construct the list which is passed into the save method below
save(id, pPList);
}
Implementing the Object#equals(Object) can solve it by the equality comparison. Nonetheless, sometimes the object you are validating cannot be changed or its equals function can not be implemented. For such cases, it's recommended using org.mockito.Matchers#refEq(T value, String... excludeFields). So you may use something like:
verify(programServiceMock, times(1)).save(id, refEq(testpPList));
Just wrapping the argument with refEq solves the problem.
Make sure you implement the equals method in com.domain.PP.
[Edit]
The reasoning for this conclusion is that your failed test message states that it expects this list of PP
[com.domain.PP#6809cf9d, com.domain.PP#5925d603]
but it's getting this list of PP
[com.domain.PP#5b6e23fd, com.domain.PP#1791fe40]
The hex values after the # symbol for each PP object is their hash codes. Because they are different, then it shows that they belong to different objects. So the default implementation of equals will say they're not equal, which is what verify() uses.
It's good practice to also implement hashCode() whenever you implement equals(): According to the definition of hashCode, two objects that are equal MUST have equal hashCodes. This ensures that objects like HashMap can use hashCode inequality as a shortcut for object inequality (here, placing objects with different hashCodes in different buckets).

How should a constructor act when given invalid parameters?

If a class has a constructor which takes some value object as parameter and relies on this to do its initialization. How should it react if this object is null?
class SomeClass
{
private SomeData _data;
public SomeClass(SomeValueObject obj)
{
_data = obj.Data;
}
}
This is one example, but in general: How should a constructor act if it is given invalid parameters and therefore cannot do the construction properly? Should it just return without doing any initialization? Set the parameters to some default values? Throw an exception? Something else?
I'm sure the answer to this is "It depends", but are there any best practices etc?
A programmer should be able to assume an object was successfully created, unless an exception is raised. The type of exception depends on the argument, but should nonetheless be unchecked. The last thing you want is the constructor fail to build a valid object and not tell the caller about it.
I think using default values in a constructor is a dangerous habit.
A lot depends on your business logic. If your business logic requires SomeValueObject to be not null, meaning SomeClass could not be instantiated without SomeValueObject then the constructor should definitely throw an Exception, probably IllegalArgumentException.
Seems like this is Java, but in C++ it should definitively throw ( a std::invalid_argument even ).
See C++ FAQ Lite 17.2.
I guess that for Java it's exactly the same.
In the rare cases where throwing exceptions presents a too big of a overhead, you should return, and set a flag in the object that it didn't construct properly. Afterwards check a isValid() member function.
Throw a null argument exception.
If field is critical it should cast an exception to indicate that object shouldnt be used. If its not critical you can assign default values.
If an object can have invalid default values, then it should initialize to the default values and wait for initialization. E.g., foo.set_values(...). In this case, there should be a query of is_ready() or is_valid() to allow checking before use.
If an object can absolutely not be in an invalid data-state, then it should throw an exception.
Both of these cases are things I've encounted.

Exception handling: Contract vs Exceptional approach

I know two approaches to Exception handling, lets have a look at them.
Contract approach.
When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception.
Exceptional approach.
Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach.
Lets use both approaches in different cases:
We have a Customer class that has a method called OrderProduct.
contract approach:
class Customer
{
public void OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
throw new NoCreditException("Not enough credit!");
// do stuff
}
}
exceptional approach:
class Customer
{
public bool OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
return false;
// do stuff
return true;
}
}
if !(customer.OrderProduct(product))
Console.WriteLine("Not enough credit!");
else
// go on with your life
Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery.
But here is a situation I err on the contract style.
Exceptional:
class CarController
{
// returns null if car creation failed.
public Car CreateCar(string model)
{
// something went wrong, wrong model
return null;
}
}
When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one:
class CarController
{
public Car CreateCar(string model)
{
// something went wrong, wrong model
throw new CarModelNotKnownException("Model unkown");
return new Car();
}
}
Which do style do you use? What do you think is best general approach to Exceptions?
I favor what you call the "contract" approach. Returning nulls or other special values to indicate errors isn't necessary in a language that supports exceptions. I find it much easier to understand code when it doesn't have a bunch of "if (result == NULL)" or "if (result == -1)" clauses mixed in with what could be very simple, straightforward logic.
My usual approach is to use contract to handle any kind of error due to "client" invocation, that is, due to an external error (i.e ArgumentNullException).
Every error on the arguments is not handled. An exception is raised and the "client" is in charge of handling it. On the other hand, for internal errors always try to correct them (as if you can't get a database connection for some reason) and only if you can't handle it reraise the exception.
It's important to keep in mind that most unhandled exception at such level will not be able to be handled by the client anyway so they will just probably go up to the most general exception handler, so if such an exception occurs you are probably FUBAR anyway.
I believe that if you are building a class which will be used by an external program (or will be reused by other programs) then you should use the contract approach. A good example of this is an API of any kind.
If you are actually interested in exceptions and want to think about how to use them to construct robust systems, consider reading Making reliable distributed systems in the presence of software errors.
Both approaches are right. What that means is that a contract should be written in such a way as to specify for all cases that are not truly exceptional a behavior that does not require throwing an exception.
Note that some situations may or may not be exceptional based upon what the caller of the code is expecting. If the caller is expecting that a dictionary will contain a certain item, and absence of that item would indicate a severe problem, then failure to find the item is an exceptional condition and should cause an exception to be thrown. If, however, the caller doesn't really know if an item exists, and is equally prepared to handle its presence or its absence, then absence of the item would be an expected condition and should not cause an exception. The best way to handle such variations in caller expectation is to have a contract specify two methods: a DoSomething method and a TryDoSomething method, e.g.
TValue GetValue(TKey Key);
bool TryGetValue(TKey Key, ref TValue value);
Note that, while the standard 'try' pattern is as illustrated above, some alternatives may also be helpful if one is designing an interface which produces items:
// In case of failure, set ok false and return default<TValue>.
TValue TryGetResult(ref bool ok, TParam param);
// In case of failure, indicate particular problem in GetKeyErrorInfo
// and return default<TValue>.
TValue TryGetResult(ref GetKeyErrorInfo errorInfo, ref TParam param);
Note that using something like the normal TryGetResult pattern within an interface will make the interface invariant with respect to the result type; using one of the patterns above will allow the interface to be covariant with respect to the result type. Also, it will allow the result to be used in a 'var' declaration:
var myThingResult = myThing.TryGetSomeValue(ref ok, whatever);
if (ok) { do_whatever }
Not quite the standard approach, but in some cases the advantages may justify it.