Whats the correct way of creating objects? - oop

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.

Related

Fastest way to invoke method handle fields

I'm generating bytecode roughly equivalent to a class like:
final class MyCls {
final MethodHandle handle1;
final MethodHandle handle2;
// and so on
// This needs to invoke `handle1`, `handle2`, etc. in it somehow
final static myMethod() {
// ...
}
}
The class is fairly long-lived and I wish to call the MethodHandles from inside other methods, with ideally as little overhead as possible. What would be the best way to do this? The two ideas that come to mind are:
Generating explicit MethodHandle.invokeExact calls on the fields
Using invokedynamic somehow (although I think I'd still need the exactInvoker?)
The handles will vary in signatures (although their use-sites should all use the right signatures - I can detect/enforce that at codegen time).
Update
Here's some extra context on what I'm actually doing. The classes represent compiled WASM modules, the method handles are imported functions, and each instance of the class in another instance of the WASM module.
Using MethodHandle to represent imported functions isn't a necessity here - I could also accept something like a java.util.function.Function or maybe even just a virtual method invocation. I do need a MethodHandle representation sometimes, but I could summon one up from a virtual method too (and I could implement a virtual method manually calling a Function too).
The module class instances themselves might end up being stored in static fields but that's not guaranteed. If there is a way to speed up that case, I could recommend users use that.
The simple answer is to just generate invokeExact calls. With the code shape you've shown, there's no need to use invokedynamic (in fact that doesn't seem possible, since invokedynamic calls a bootstrap method which supplies the implementation dynamically).
Since the handles are stored instance fields, they are not seen as constants, and so the calls will be out of line, which adds overhead, as well as missed optimization opportunities due to a lack of inlining.
If you really want this to be as fast as possible, you'd need to generate a new class per combination of method handles you want to use, and store the method handles in static final fields, or in the constant pool (for instance using constant pool patching, or hidden classes + class data + dynamic constants [1]).

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.

Singleton use within objects or passed as reference

I program in PHP but this is a general Object orientation question.
What do we feel about calling singleton classes from within an object vs calling one outside and passing the variable in?
Option one:
$instance = Singleton::getInstance();
$obj = new ClassName();
$obj->setSingleton($instance);
Option two:
class ClassName
{
public function __construct(){
$instance = Singleton::getInstance();
$instance->doSomething();
}
}
Is this just a "per-use" decision (i.e. singleton implementing interface, etc) or are there rules?
I can see passing objects VS singletons but one about singleton instances vs calling? Think typical code with lots of classes and many uses for the singleton instance... Are there any rules for this?
Either is fine, but when others will look at your code it might be less obvious they're dealing with a singleton in your option #1, especially if the code grows big. IMHO it's perfectly valid to keep a reference of your singleton in the body of a function when you need to call it a few times in a row, but I wouldn't keep it as member variable.
Keeping a member variable also implies your objects will be bigger for no apparent reason.

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.

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.