"Fluent interfaces" that maintain order in the invokation chain - oop

Is there an elegant/convinient way (without creating many "empty" classes or at least they should be not annoying) to have fluent interfcaes that maintain order on compilation level.
Fluent interfaces:
http://en.wikipedia.org/wiki/Fluent_interface
with an idea to permit this compilation
var fluentConfig = new ConfigurationFluent().SetColor("blue")
.SetHeight(1)
.SetLength(2)
.SetDepth(3);
and decline this
var fluentConfig = new ConfigurationFluent().SetLength(2)
.SetColor("blue")
.SetHeight(1)
.SetDepth(3);

Each step in the chain needs to return an interface or class that only includes the methods that are valid to use after the current step. In other words, if SetColor must come first, ConfigurationFluent should only have a SetColor method. SetColor would then return an object that only has a SetHeight method, and so forth.
In reality, the return values could all be the same instance of ConfigurationFluent but cast to different interfaces explicitly implemented by that class.

I've got a set of three ways of doing this in C++ using essentially a compile time FSM to validate the actions. You can find the code on github.

The short answer is no, there is no elegant or convenient way to enforce an order of constructing a class that properly impelemnts the "Fluent Interface" as you've linked.
The longer answer starts with playing devil's advocate. If I had dependent properties (i.e. properties that required other properties to be set first), then I could implement them something like this:
method SetLength(int millimeters)
if color is null throw new ValidationException
length = millimeters
return this
end
(NOTE: the above does not map to any real language, it is just psuedocode)
So now I have exceptions to worry about. If I don't obey the rules, the fluent object will throw an exception. Now let's say I have a declaration like yours:
var config = new Fluent().SetLength(2).SetHeight(1).SetDepth(3).SetColor("blue");
When I catch the ValidationException because length depends on the color being set first, how am I as the user supposed to know what the correct order is? Even if I had each SetX method on a different line, the stacktrace will just give me the line where the config variable was declared in most languages. Furthermore, how am I supposed to keep the rules of this object straight in my head compared to other objects? It is a cocophony of conflicting ideals.
Such precedence checks violate the spirit of the "Fluent Interface" approach. That approach was designed for conveniently configure complex objects. You take the convenience out when you attempt to enforce order.
To properly and elegantly implement the fluent interface there are a couple of guidelines that are best observed to make consumers of your class thank you:
Provide meaningful default values: minimizes need to change values, and minimizes chances of creating an invalid object.
Do not perform configuration validation until explicitly asked to do so. That event can be when we use the configuration to create a new fully configured object, or when the consumer explicitly calls a Validate() method.
In any exceptions thrown, make sure the error message is clear and points out any inconsistencies.

maybe the compiler could check that methods are called in the same order as they are defined.
this could be a new feature for compilers.
Or maybe by means of annotations, something like:
class ConfigurationFluent {
#Called-before SetHeight
SetColor(..) {}
#Called-After SetColor
SetHeight(..) {}
#Called-After SetHeight
SetLength(..){ }
#Called-After SetLength
SetDepth(..) {}
}

You can implement a state machine of valid sequence of operations and on each method call the state machine and verify if the sequence of operation is allowed or throw an exception if not.
I will not suggest this approach for Configurations though, it can get very messy and not readable

Related

From a ByteBuddy-generated method, how do I set a (public) instance field in an object received as an argument to the return value of a MethodCall?

I am generating a class in ByteBuddy.
As part of one method implementation, I would like to set a (let's just say) public instance field in another object to the return value of a MethodCall invocation. (Keeping the example public means that access checks etc. are irrelevant.)
I thought I could use MethodCall#setsField(FieldDescription) to do this.
But from my prior question related to this I learned that MethodCall#setsField(FieldDescription) is intended to work only on fields of the instrumented type, and, looking at it now, I'm not entirely sure why or how I thought it was ever going to work.
So: is there a way for a ByteBuddy-generated method implementation to set an instance field of another object to the return value of a method invocation?
If it matters, the "instrumented method" (in ByteBuddy's terminology) accepts the object whose field I want to set as an argument. Naïvely I'd expect to be able to do something like:
MethodCall.invoke(someMethod).setsField(somePublicField).onArgument(2);
There may be problems here that I am not seeing but I was slightly surprised not to see this DSL option. (It may not exist for perfectly good reasons; I just don't know what they would be.)
This is not possible as of Byte Buddy 1.10.18, the mechanism was originally created to support getters/setters when defining beans, for example. That said, it would not be difficult to add; I think it would even be easiest to allow any custom byte code to be dispatched as a consumer of the method call.
I will look into how this can be done, but as a new feature, this will take some time before I find the empty space to do so. The change is tracked on GitHub.

Is overloading a method without throwing an exception an antipattern?

We are currently designing an API for storing settings and we are considering having these two types of methods:
public Object getSetting(String key) {
// return null if key does not exist
}
public Object getSettingExc(String key) {
// throw a runtime exception if key does not exist
}
Somehow I feel that this just isn't right, but I can't think of any disadvantages except for doubling the number of functions in the API and perhaps decreased code readability (if I know the setting MUST exist, I think I should throw an exception explicitly rather than relying on the get method).
What are your opinions on this?
Exceptions are for exceptional occurrences, when the code cannot continue to function according to its advertised function.
Requesting a setting that isn't set is hardly exception-worthy. If "you" (i.e. the calling code) "know" that setting "must" exist, call getSetting(), check the return value for null, and then throw an exception yourself out of the knowledge that it should have been there. Add a meaningful message about what setting in which context wasn't found. (This is something only the caller knows.)
Don't delegate the throwing of the exception to code that doesn't know the context of the query or that the setting should be there, and needs to be told explicitly (by getting called under a different name). Also, getSettingExc() will most likely be only a null-check-and-throw wrapper around getSetting() anyway, so why not do it at a point where you can make the exception message so much more helpful?
IMHO. (And this is the point where I realize I should have voted-to-close instead of writing an answer...)
This is introducing a weird kind of coupling between the object structure and the potential error conditions. Regarding your comment:
I'm just trying to gather arguments to persuade other guys in my team.
The onus should be on the proponent of this design to justify it, not on you to justify against it. Nobody else uses this in any design I've ever seen.
This does however remind me of another design that maybe is what your team intended? Consider these two methods:
public Object getSetting(String key) {
// return the setting or throw an exception
}
public Object getSettingOrDefault(String key) {
// return the setting or a pre-determined default
}
This aligns the methods more with the functionality than with the error conditions. getSetting() can advertise that it might throw an exception, whereas getSettingOrDefault() can advertise that it will default to a specific value if none can be found in the settings.
If Java has optional parameters or something akin to that, getSettingOrDefault() might even accept as an argument a default to use in the event of no such setting. That might get a little kludgy for consuming code though, just sort of thinking out loud on that one.
Either way, the API should reflect the functionality and not the error conditions. Ideally there should be only one method, but if there's a noticeable need to differentiate between a method that throws and a method that doesn't (and I could certainly see that being the case in a language with checked exceptions), those two should align with the functionality rather than with the exception.
IMHO having two methods to do precisely the same operation indicates that you as the API designer did not complete the job of 'designing' your API. Choose one way or another, publicize it via the API (javadocs) and then the consumers will be consistent in their usage (one way or the other).

Whats the correct way of creating objects?

For example, i see myself doing things like this latley, when i create an object, if it has a logical path of tasks then
public Class Link
{
public Link(String value)
{
callMethodA(value)
}
public void callMethodA(String data)
{
CallMethodB(doSomethingWithValue)
}
...
...
}
Here you can see, as soon as you instantiate the object, yours tasks get completed automatically.
The other way i can see of doing it is by creating an object, that doesnt link via the constructor, then calling methods individually.
Which was is right and why?
Thanks
Either way we can implement.
Recommended way is to do tasks like initialization stuffs within the constructor and rest of the things can be implemented by way of calling the method with its reference object.
for such scenario one should go for Factory pattern
for example:
Calendar.getInstance();
Constructor should do ALL that requires to make an object complete. That is, if without calling method callMethodA , if the object is incomplete then callMethodA must be called from constructor itself. If the callMethodA is optional API then the user of class Link can call the method when he wants.
I prefer second method. Constructor's job is to initialize the class members. Any modification to change the state of the object needs to be done seperately by member functions.
As long as the objects that are created do not have nothing in common the current way of creating them is fine. Factory Method or Abstract Factory pattern makes sense when there's similarity between created objects. They'll help you isolate the parts that are always the same and moving parts that define differences between objects.
It depends on business logic involved. Both ways are practical. If you want to simply initiate instance specific data, then better to do it in constructor method itself which is more logical and simple. It will save calling other methods explicitly unnecessarily. If instanciating your data is based on certain buisiness condition, then it is good to have main functionality in separate method and then conditionally call it from constructor. This is easy to manage in such scenario.
A constructor is meant to bring the object in the correct initial state. So use it for that purpose. As a general rule of thumb, only use a constructor to set properties. Basic calculations are also ok.
I would not recommend calling very time consuming methods, or methods that are likely to throw exceptions (like calling a webservice or access a file).
When you need to do very special things to bring the object in its initial state, make the constructor private and use a static method to create the object.

Use of Constructors - Odd Doubt

I'm reading about constructors,
When an object is instantiated for a class, c'tors (if explicitly written or a default one) are the starting points for execution. My doubts are
is a c'tor more like the main() in
C
Yes i understand the point that you
can set all the default values using
c'tor. I can also emulate the behavior
by writing a custom method. Then why a c'tor?
Example:
//The code below is written in C#.
public class Manipulate
{
public static int Main(string[] args) {
Provide provide = new Provide();
provide.Number(8);
provide.Square();
Console.ReadKey();
return 0;
}
}
public class Provide {
uint num;
public void Number(uint number)
{
num = number;
}
public void Square()
{
num *= num;
Console.WriteLine("{0}", num);
}
}
Am learning to program independently, so I'm depending on programming communities, can you also suggest me a good OOP's resource to get a better understanding. If am off topic please excuse me.
Head First OOA&D will be a good start.
Dont you feel calling a function for setting each and every member variable of your class is a bit overhead.
With a constructor you can initialize all your member variables at one go. Isnt this reason enough for you to have constructors.
Constructor and Destructor functionality may be emulated using regular methods. However, what makes those two type of methods unique is that the language treats them in a special way.
They are automatically called when an object is created or destroyed. This presents a uniform means to handle the most delicate operations that must take place during those two critical periods of an object's lifetime. It takes out the possibility of an end user of a class forgetting to call those at the appropriate times.
Furthermore, advanced OO features such as inheritance require that uniformity to even work.
First of all, most answers will depend at least a bit on the language you're using. Reasons that make great sense in one language don't necessarily have direct analogs in other languages. Just for example, in C++ there are quite a few situations where temporary objects are created automatically. The ctor is invoked as part of that process, but for most practical purposes it's impossible to explicitly invoke other member functions in the process. That doesn't necessarily apply to other OO languages though -- some won't create temporary objects implicitly at all.
Generally you should do all your initialization in the constructor. The constructor is the first thing called when an instance of your class is created, so you should setup any defaults here.
I think a good way to learn is comparing OOP between languages, it's like seeing the same picture from diferent angles.
Googling a while:
java (I prefer this, it's simple and full)- http://java.sun.com/docs/books/tutorial/java/concepts/
python - http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/
c# - http://cplus.about.com/od/learnc/ss/csharpclasses.htm
Why constructors?
The main diference between a simple function (that also could have functions inside) and an Object, is the way that an Object can be hosted inside a "variable", with all it functions inside, and that also can react completly diferent to an other "variable" with the same kind of "object" inside. The way to make them have the same structure with diferent behaviours depends on the arguments you gave to the class.
So here's a lazy example:
car() is now a class.
c1 = car()
c2 = car()
¿c1 is exactly c2? Yes.
c1 = car(volkswagen)
c2 = car(lamborghini)
C1 has the same functionalities than C2, but they are completly diferent kinds of car()
Variables volkswagen and lamborghini were passed directly to the constructor.
Why a -constructor-? why not any other function? The answer is: order.
That's my best shot, man, for this late hours. I hope i've helped somehow.
You can't emulate the constructor in a custom method as the custom method is not called when the object is created. Only the constructor is called. Well, of course you can then call your custom method after you create the object, but this is not convention and other people using your object will not know to do this.
A constructor is just a convention that is agreed upon as a way to setup your object once it is created.
One of the reasons we need constructor is 'encapsulation',the code do something initialization must invisible
You also can't force the passing of variables without using a constructor. If you only want to instantiate an object if you have say an int to pass to it, you can set the default constructor as private, and make your constructor take an int. This way, it's impossible to create an object of that class without having it take an int.
Sub-objects will be initialized in the constructor. In languages like C++, where sub-objects exist within the containing object (instead of as separate objects connected via pointers or handles), the constructor is your only chance to pass parameters to sub-object constructors. Even in Java and C#, any base class is directly contained, so parameters to its constructor must be provided by your constructor.
Lastly, any constant (or in C#, readonly) member variables can only be set from the constructor. Even helper functions called from the constructor are unable to change them.

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.