Difference between pagefactory.initelements and Class instance - instance

I am new to java.
I am not able to get my understanding around the difference between Pagefactory.initelements and Class instance. Can someone please help me on this ? Reason for this question is :
The only difference I can see is the webelement initialisation and nothing apart from that. Both can be used to access the class variables and methods.
Somename.class will do the same as 'new someclass()' ?

Page Factory uses Java Reflection API. It also has 2 public constructors for developers. One accepts already instantiated object as an argument. The second allows you to pass Object.class which is not an instance, it's more like a schema of a class.
PageFactory.initElements(driver, this);
The above method accepts the instance of Page Object, already created instance. Then, it gets it's a schema, reads fields and initializes them based on #FindBy annotations.
PageFactory.initElements(driver, PageObject.class)
The above class already has the schema so it initializes the fields and returns a newly created instance of PageObject class.

Related

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.

How to assign value to an implementation of an interface, but the interface doesn't have setter method?

I have an interface: Show, and i have the implementation class calls ShowImpl, and also i have a implementation class calls ManageShowImpl. I have completed all the methods inside ManageShowImpl. Now i am doing Junit testing. The method i defined in the ManageShowImpl, for example: addShows(Show... shows), now i want to assign values to the show array: Show[], but in the interface: Show, i don't have setter method(which is not supposed inside interface), can some expert tell me how can i add the value to Show[].
If I understood correctly your issue, I think you can simply set values in your constructor:
public class ShowImpl implements Show{
private Show[] shows;
public ShowImpl(Show... shows){
this.shows = shows;
}
#Override
public void someInterfaceMethod(){
// ...
}
}
(I am not a junit expert, or even a beginner, but maybe I can inspire a few to answer. I have done a fair amount of testing.)
Given a class with a constructor, you can always create an instance, fill it with whatever data you want, and test it any way you want. Interfaces are a lot more limited. Testing aside, this is a very good thing. It limits the damage someone can do if they get hold of an interface implementation; it safely encapulates the data. But you cannot test an interface in isolation. You need to create an instance of an implementing class first. At that point you should fill in your array. Then pass it to a test method as an interface instance to test the interface.

adapter pattern and dependency

I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.

No parameterless constructer defined for this object when putting EnabledDelete=true on LinqDataSource

If I have a LinqDataSource without EnabledDelete, EnabledUpdate, EnabledInsert, it works fine, but as soon as I add those properties to the data source, I get the error:
No parameterless constructor defined for this object.
Here is an answer that helped me solve the issue from the MSDN forums:
LinqDataSource requires a default constructor on the DataContext. If you are working in a web application or website project, the Linq to SQL designer should have created a default constructor and connection string for you when you dragged tables from the database onto the design surface.
Did you create your DataContext and drag tables onto the design surface from a webapp or website project? Open the Lib.NorthwindDataContext class that was generated and see if it has the default constructor.
If you really want, you could also use LinqDataSource without the default constructor by handling the ContextCreating event and providing your own context instance.
As the error indicates, you need to provide a parameterless constructor for the class.
public class MyClass
{
public MyClass()
{
// This is the parameterless constructor
}
// rest of the class members goes here.
}
The system requires a parameterless constructor when it is required to create instances of a class automatically. It cannot determine the meaning of the parameters of your other constructors so it depends on this constructor.
Even if your constructor does nothing it will still work, though you may want it to provide useful defaults for your class properties.

When should I use static methods in a class and what are the benefits?

I have concept of static variables but what are the benefits of static methods in a class. I have worked on some projects but I did not make a method static. Whenever I need to call a method of a class, I create an object of that class and call the desired method.
Q: Static variable in a method holds it's value even when method is executed but accessible only in its containing method but what is the best definition of static method?
Q: Is calling the static method without creating object of that class is the only benefit of static method?
Q: What is the accessible range for static method?
Thanks
Your description of a static variable is more fitting to that found in C. The concept of a static variable in Object Oriented terms is conceptually different. I'm drawing from Java experience here. Static methods and fields are useful when they conceptually don't belong to an instance of something.
Consider a Math class that contains some common values like Pi or e, and some useful functions like sin and cos. It really does not make sense to create separate instances to use this kind of functionality, thus they are better as statics:
// This makes little sense
Math m = new Math();
float answer = m.sin(45);
// This would make more sense
float answer = Math.sin(45);
In OO languages (again, from a Java perspective) functions, or better known as methods, cannot have static local variables. Only classes can have static members, which as I've said, resemble little compared to the idea of static in C.
Static methods don't pass a "this" pointer to an object, so they can't reference non-static variables or methods, but may consequently be more efficient at runtime (fewer parameters and no overhead to create and destroy an object).
They can be used to group cohesive methods into a single class, or to act upon objects of their class, such as in the factory pattern.
Syntax (php) for static methods:
<?php
class Number {
public static function multiply($a, $b) {
return $a * $b;
}
}
?>
Client code:
echo Number::multiply(1, 2);
Which makes more sense than:
$number = new Number();
echo $number->multiply(1, 2);
As the multiply() method does not use any class variables and as such does not require an instance of Number.
Essentially, static methods let you write procedural code in an object oriented language. It lets you call methods without having to create an object first.
The only time you want to use a static method in a class is when a given method does not require an instance of a class to be created. This could be when trying to return a shared data source (eg a Singleton) or performing an operation that doesn't modify the internal state of the object (String.format for example).
This wikipedia entry explains static methods pretty well: http://en.wikipedia.org/wiki/Method_(computer_science)#Static_methods
Static variables and static methods are bound to the class, and not an instance of the class.
Static methods should not contain a "state". Anything related to a state, should be bound to an instantiated object, and not the class.
One common usage of static methods is in the named constructor idiom. See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8.
Static Methods in PHP:
Can be called without creating a class object.
Can only call on static methods and function.
Static variable is used when you want to share some info between different objects of the class.As variable is shared each object can update it and the updated value be available for all other objects as well.
As static variable can be shared,these are often called as class variable.
static elements are accessible from any context (i.e. anywhere in your script), so you can access these methods without needing to pass an instance of the class from object to object.
Static elements are available in every instance of a class, so you can set values that you want to be available to all members of a type.
for further reading a link!