PROS and CONS on using one classPageObject for storing all xpath/css selectors and etc., using Java - selenium

What are the PROS and CONS on using onePageObject class for storing my all xpath/css selectors and etc., and then use them in other page object methods.
I'm thinking how lower the needless xpath's that are constantly is repeating in different pageObjects class.
Any suggestions?
Somebody already doing this? If yes, is it easyer or harder to find what you need?
I'm thinking to use the code something like this:
ObjectClass.java
Public class ObjectClass myXpaths {
#FindBy(xPath);
private button xPathButtonAdd;
#FindBy(xPath);
private button xPathButtonDelete;
#FindBy(xPath);
private button xPathButtonCancel;
}
ObjectClass2.java
import ObjectClass;
Public class void ObjectClass2 myPageObject {
ObjectClass smth = new ObjectClass();
smth.xPathButtonAdd.click();
smth.xPathButtonDelete.click();
smth.xPathButtonCancel.click();
}

CONS as I see it:
One huge class of selectors - huge classes are typical code smell.
Other page object class would inherit from or initialize an object
with a lot of selectors it doesn't need.
Violation of Single Responsibility Principle (SRP).
PROS:
Avoiding some repetitive code - you could avoid it by other means
(see example bellow)
....
If the reason why you think of doing this is minimizing repetitive code, you should rather think of how to extract that repetitive code to separate classes. For instance, given a application with multiple pages where every page has standart search section, you can extract it to separate class SearchSection or SearchBox and use it in pages where you need it.
If you gave an example of repetitive code or what do you want to do, it would be easier to suggest something.

Ok, I think I get now where you want to go. I would definitely recommend separating the selectors from the actual code. We organize our page objects in classes that more or less represent one screen of the application under test. Those classes are then again in a structure of packages representing the business process that is tested. That way we can easily reuse page elements and if something in the application under test changes we only have to touch this "repository" of page elements but not the script that does the action. We also use prefixes like "link", "button", "input" and so on that indicate the type of page element so that the action code is easier to understand and read.
But I would really advise against throwing all in one huge class, because you might have trouble finding things later on. :-)

Related

How to manage combinations of styles: multiple classes, specific classes, or context?

I'm not much of a web designer or programmer, but I seem to run into this issue with CSS classes: what's the best way of managing sets of CSS classes that share attributes in common?
For example, I'm currently working on an application with a status bar representing the status of a file transfer. It's used in three different locations, each of which is a different size. In addition, if the transfer fails, the bar should be a different color.
What's the best approach, in general:
Add "statusbar" and "transfer-failed" classes to the divs independently, and check for their combined existence?
Have "statusbar" and "statusbar-failed" classes, set the class appropriately, and use careful CSS structuring to avoid repeating code.
Have a "statusbar" class, then use context like the div being inside a "summary" table or a "transfer-failed" div to further specialise it.
Are there any general rules? Approach 3 seems fragile, because changing the name of a seemingly unrelated class could break stuff. Approach 1 feels strange somehow, having classes like "failed" that would be meaningless without another class, and could also mean different things in different contexts (eg, "failed" could also be applied to a failed form validation...) Approach 2 sometimes gets unwieldy, with lots of very specific classes with long names.
If there will always be only one "status bar" feel free to use an
id instead of a class for it.
If there will be multiple on the same page, and they look
anything alike, stick with class.
Assign a transfer-failed class when appropriate. In in your CSS,
under this class, should only have the properties that
differentiates it of the default "status bar". Personally, I like #3
(the context approach). WordPress and other CSMs assign the page
name and category (and anything else you'd like) as <body>
classes. Modernizr uses the <html> tag. More info here: http://perishablepress.com/dynamic-body-class-id-php-wordpress/
#Lokase's SMACSS is great. For more tips on organizing your CSS, check this out: http://coding.smashingmagazine.com/2007/05/10/70-expert-ideas-for-better-css-coding/
Take some time to look at a few CSS methodologies or frameworks, I am a fan of SMACSS
There are a lot examples of best practices out there, you just have to find them and go through the learning curve.

How to break up a large class

I have a large Shape class, instances of which can (should) be able to do lots of things. I have many "domain" shape classes which inherit from this class, but do not provide any different functionality other than drawing themselves.
I have tried subclassing the Shape class, but then all of the "domain" objects will still inherit this subclass.
How do I break up the class? (it is 300 text lines, C#)
300 lines seems reasonable to me.
post the code if you really want better help
A couple of ideas (more like heuristics):
1) Examine the fields of the class. If a group of fields is only used in a few methods, that might be a sign that that group of fields and the methods that use it might belong in another class.
2) Assuming a well-named class, compare the name of the class to what the class actually does. If you find methods that do things above and beyond what you'd expect from the class' name, that might be a sign that those methods belong in a different class. For example, if your class represents a Customer but also opens, closes, and writes to a log file, break out the log file code into a Logger class. See also: Single Responsibility Principle (PDF) for some interesting ideas .
3) If some of the methods primarily call methods on one other class, that could be a sign that those methods should be moved to the class they're frequently using (e.g. Feature Envy).
CAUTION: Like they say, breaking up is hard to do. If there is risk in breaking up the class, you may want to put some tests in place so that you know you're not breaking anything as you refactor. Consider reading "Working Effectively with Legacy Code" and the "Refactoring" book.
you could break up by delegating functions to other helper classes.
but I agree that 300 lines of code isn't terrible.
+1 for posting the code
Thanks for the code.
Here are a few things you might try:
1) Refactor duplicate code. This kind of code was duplicated about seven times:
Visio.Cell pinX = GetLayoutCell(Visio.VisCellIndices.visXFormPinX);
if (pinX != null)
{
pinX.set_Result("cm", value);
}
Note: PinY also calculates pinX but doesn't use its value.
Similar duplication exists in: Pos{X,Y}{Start,End}
What makes this class more challenging to break up is that it's a wrapper around an already complex class.
Not knowing the domain very well (although I'm an expert with the Shape, Circle, Square concept), I'd be tempted to break the class into several classes that each share the same core Shape object.
Here is a sketch:
class EnvironShape {
private ShapeProperties _properties; // contains property management code
private ShapeCollection _children; // contains code for acting on children
private Decorators _decorators; // code for accessing decorators
private Layers _layers; // layer management code
private Position _position; // code for working with the shape's position
// Other code omitted
}
I would not immediately and directly expose these objects (e.g. public ShapeCollection GetChildren()) but I would start off making the EnvironShape delegate to these objects.

Should a long method used only once be in its own class or in a function?

A lot of times in code on the internet or code from my co-workers I see them creating an Object with just one method which only gets used once in the whole application. Like this:
class iOnlyHaveOneMethod{
public function theOneMethod(){
//loads and loads of code, say 100's of lines
// but it only gets used once in the whole application
}
}
if($foo){
$bar = new iOnlyHaveOneMEthod;
$bar->theOneMethod();
}
Is that really better then:
if($foo){
//loads and loads of code which only gets used here and nowhere else
}
?
For readability it makes sense to move the loads and loads of code away, but shouldn't it just be in a function?
function loadsAndLoadsOfCode(){
//Loads and loads of code
}
if($foo){ loadsAndLoadsOfCode(); }
Is moving the code to a new object really better then just creating a function or putting the code in there directly?
To me the function part makes more sense and seems more readible then creating an object which hardly is of any use since it just holds one method.
The problem is not whether it's in a function or an object.
The problem is that you have hundreds of lines in one blob. Whether that mass of code is in a method of an object or just a class seems more or less irrelevant to me, just being minor syntatic sugar.
What are those hundreds of lines doing? That's the place to look to implement object oriented best practice.
If your other developers really think using an object instead of a function makes it significantly more "object oriented" but having a several-hundred line function/method isn't seen as a code smell, then I think organisationally you have some education to do.
Well, if there really is "loads and loads" of code in the method, then it should be broken down into several protected methods in that class, in which case the use of a class scope is justified.
Perhaps that code isn't reusable because it hasn't been factored well into several distinct methods. By moving it into a class and breaking it down, you might find it could be better reused elsewhere. At least it would be much more maintainable.
Whilst the function with hundreds of lines of code clearly indicates a problem (as others have already pointed out), placing it in a separate instance class rather than a static function does have advantages, which you can exploit by rejigging your example a fraction:
// let's instead assume that $bar was set earlier using a setter
if($foo){
$bar = getMyBar();
$bar->theOneMethod();
}
This gives you a couple of advantages now:
This is a simple example of the Strategy Pattern. if $bar implements an interface that provides theOneMethod() then you can dynamically switch implementations of that method;
Testing your class independently of $bar->theOneMethod() is dramatically easier, as you can replace $bar with a mock at testing time.
Neither of these advantages are available if you just use a static function.
I would argue that, whilst simple static functions have their place, non-trivial methods (as this clearly is by the 'hundreds of lines' comment) deserve their own instance anyway:
to separate concerns;
to aid testing;
to aid refactoring and reimplementation.
You are really asking two questions here:
Is just declaring a function better than creating an object to hold only this function?
Should any function contain "loads of code"?
The first part: If you want to be able to dynamically switch functions, you may need the explicit object encapsulation as a workaround in languages that cannot handle functions this way. Of course, having to allocate a new object, assign it to a variable, then call the function from that variable is a bit dumb when all you want to do is call a function.
The second part: Ideally not, but there is no clear definition of "loads", and it may be the appropriate thing to do in certain cases.
yes, the presences of loads and loads of code is a Code Smell.
I'd say you almost never want to have either a block or a method with loads of code in it -- doesn't matter if it's in it's own class or not.
Moving it to an object might be a first step in refactoring 'though - so it might make sense in that way. First move it to its own class and later split it down to several smaller methods.
Well, I'd say it depends on how tightly coupled the block of code is with the calling section of code.
If it's so tightly coupled, that I can't imagine it being used anywhere else, I'd prefer sticking it in a private method of the calling class. That way it won't be visible to other parts of your system, guaranteeing it won't be misused by others.
On the other hand, if the block of code is generic enough (email validation i.e.) to possibly be interesting in other parts of the system, I'd have no problem extracting that part into it's own class, and then consider that to be a utility class. Even if it means it will be a single-method class.
If your question was more in the lines of "what to do with hundreds and hundreds of lines of code", then you really need to be doing some refactoring.
As much as a single method with lots of code is a code smell. My first thought was to at least make the method static. No data in the class so no need for creating an object.
I think i would look to rephrase the question that you are asking. I think you want to ask the questions is my class supporting singles responsibility principle. Is there anyway to decompose the pieces of your class into seperate smaller pieces that might change independently of each other (data access and parsing, etc . .). Can you unit test your class easily . .
If you can say yes to the above items, i wouldn't worry about method versus new class as the whole point here is that you have readable, maintainable code.
In my team we have red flag if a class gets long (over x amount of lines) but that is just a heuristic as if you class has 2000 lines of codes it probably can get broken down and is probably not supporting SRP.
For testability, it is definitely better to break it out into a separate class with separate method(s). It is a whole lot easier to write unit tests for single methods than as part of an inline if statement in a code-behind file or whatnot.
That being said, I agree with everyone else that the method should be broken out into single responsibility methods instead of hundreds of lines of code. This too will make it more readable and easier to test. And hopefully, you might get some reuse out of some of the logic contained in that big mess of code.

Selecting the Correct View for an Object Type

I've had this problem many times before, and I've never had a solution I felt good about.
Let's say I have a Transaction base class and two derived classes AdjustmentTransaction and IssueTransaction.
I have a list of transactions in the UI, and each transaction is of the concrete type AdjustmentTransaction or IssueTransaction.
When I select a transaction, and click an "Edit" button, I need to decide whether to show an AdjustmentTransactionEditorForm or an IssueTransactionEditorForm.
The question is how do I go about doing this in an OO fashion without having to use a switch statement on the type of the selected transaction? The switch statement works but feels kludgy. I feel like I should be able to somehow exploit the parallel inheritance hierarchy between Transactions and TransactionEditors.
I could have an EditorForm property on my Transaction, but that is a horrible mixing of my UI peanut butter with my Model chocolate.
Thanks in advance.
You need to map your "EditorForm" to a transaction at some point. You have a couple options:
A switch statement...like you, I think this stinks, and scales poorly.
An abstract "EditorForm" property in base Transaction class, this scales better, but has poor seperation of concerns.
A Type -> Form mapper in your frontend. This scales fairly well, and keeps good seperation.
In C#, I'd implement a Type -> Form mapper like this:
Dictionary <Type,Type> typeMapper = new Dictionary<Type,Type>();
typeMapper.Add(typeof(AdjustTransaction), typeof(AdjustTransactionForm));
// etc, in this example, I'm populating it by hand,
// in real life, I'd use a key/value pair mapping config file,
// and populate it at runtime.
then, when edit is clicked:
Type formToGet;
if (typeMapper.TryGetValue(CurrentTransaction.GetType(), out formToGet))
{
Form newForm = (Form)Activator.CreateInstance(formToGet);
}
You probably don't want to tie it to the inheritance tree--that will bind you up pretty good later when you get a slight requirements change.
The relationship should be specified somewhere in an external file. Something that describes the relationship:
Editing AdujustmentTransaction = AdjustmentTransactionEditorForm
Editing IssueTransaction = IssueTransactionEditorForm
With a little bit of parsing and some better language than I've used here, this file could become very generalized and reusable--you could reuse forms for different objects if required, or change which form is used to edit an object without too much effort.
(You might want users named "Joe" to use "JoeIssueTransactionEditorForm" instead, this could pretty easily be worked into your "language")
This is essentially Dependency Injection--You can probably use Spring to solve the problem in more general terms.
Do I miss something in the question? I just ask because the obvious OO answer would be: Polymorph
Just execute Transaction.editWindow() (or however you want to call it), and
overwrite the method in AdjustmentTransaction and IssueTrasaction with the required functionality. The call to element.editWindow() then opens the right dialog for you.
An alternative to the Dictionary/Config File approach would be
1) to define a interface for each of the transaction editors.
2) In your EXE or UI assembly have each of the forms register itself with the assembly that creates the individual transaction.
3) The class controlling the registration should be a singleton so you don't have multiple form instances floating around.
3) When a individual transaction is created it pulls out the correct form variable from the registration object and assigns it do an internal variable.
4) When the Edit method is called it just uses the Show method of the internal method to start the chain of calls that will result in the display of that transacton editor.
This eliminates the need for config files and dictionaries. It continues to separate the UI from the object. Plus you don't need any switch statement
The downside is having to write the interface for each every form in addition to the form itself.
If you have a great deal of different types of editors (dozens) then in that case I recommend that you use the Command Pattern
You have a master command that contains the dictonary recommend by Jonathan. That commands in turns will use that dictornary to execute one of a number of other command that calls the correct form with the correct object. The forms continue to be separate from the object themselves. The forms reside in the Command assembly. In addition you don't have to update the EXE to add another editor only the Command assembly. Finally by putting things inside of Command you can implement Undo/Redo a lot easier. (Implement a Unexecute as well as a Execute)

How to prevent multiple classes for the same business object?

A lot of the time I will have a Business object that has a property for a user index or a set of indexes for some data. When I display this object in a form or some other view I need the users full name or some of the other properties of the data. Usually I create another class myObjectView or something similar. What is the best way to handle this case?
To further clarify:
If I had a class an issue tracker and my class for an issue has IxCreatedByUser as a property and a collection of IxAttachment values (indexes for attachment records). When I display this on a web page I want to show John Doe instead of the IxCreatedByUser and I want to show a link to the Attachment and the file name on the page. So usually I create a new class with a Collection of Attachment objects and a CreatedByUserFullName property or something of that nature. It just feels wrong creating this second class to display data on a page. Perhaps I am wrong?
The façade pattern.
I think your approach, creating a façade pattern to abstract the complexities with multiple datasources is often appropriate, and will make your code easy to understand.
Care should be taken to create too many layers of abstractions, because the level of indirection will ruin the initial attempt at making the code easier to read. Especially, if you feel you just write classes to match what you've done in other places. For intance if you have a myLoanView, doesn't necessarily you need to create a myView for every single dialogue in the system. Take 10-steps back from the code, and maybe make a façade which is a reusable and intuitive abstraction, you can use in several places.
Feel free to elaborate on the exact nature of your challenge.
One key principle is that each of your classes should have a defined purpose. If the purpose of your "Business object" class is to expose relevant data related to the business object, it may be entirely reasonable to create a property on the class that delegates the request for the lookup description to the related class that is responsible for that information. Any formatting that is specific to your class would be done in the property.
Here's some guidelines to help you with deciding how to handle this (pretty common, IMO) pattern:
If you all you need is a quickie link to a lookup table that does not change often (e.g. a table of addresses that links to a table of states and/or countries), you can keep a lazy-loaded, static copy of the lookup table.
If you have a really big class that would take a lot of joins or subqueries to load just for display purposes, you probably want to make a "view" or "info" class for display purposes like you've described above. Just make sure the XInfo class (for displaying) loads significantly faster than the X class (for editing). This is a situation where using a view on the database side may be a very good idea.