How to unit test HTML output with PHPUnit? - html

I'm new to PHPUnit, and I'm having some trouble with unit testing HTML output.
My test follows:
/**
* #covers Scrap::removeTags
*
*/
public function testRemoveTags() {
// Variables
$simple_parameter = 'script';
$array_parameter = array('script', 'div');
$html = '<div class="pubanunciomrec" style="background:#FFFFFF;"><script type="text/javascript"><!-- google_ad_slot = "9853257829"; google_ad_width = 300; google_ad_height = 250; //--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></div><table></table>';
// Expected HTML
$expected_html_whitout_script = new DOMDocument;
$expected_html_whitout_script->loadHTML('<div class="pubanunciomrec" style="background:#FFFFFF;"></div><table></table>');
$expected_html_without_script_div = new DOMDocument;
$expected_html_without_script_div->loadHTML('<table></table>');
// Actual HTML
$actual_whitout_script = new DOMDocument;
$actual_whitout_script->loadHTML($this->scrap->removeTags($html, $simple_parameter));
$actual_without_script_div = new DOMDocument;
$actual_without_script_div->loadHTML($this->scrap->removeTags($html, $array_parameter));
// Test
$this->assertEquals($expected_html_whitout_script, $actual_whitout_script);
$this->assertEquals($expected_html_without_script_div, $actual_without_script_div);
}
My problem is that the DOMDocument object generates some HTML code and I can't compare it. How can I print the DOMDocument object to see the output? Any clues on how to compare the HTML?
Sorry for my bad english.
Best Regards,

Since 2013, there is another way to test HTML Output using PHPUnit.
It is using assertTag() method that can be found in PHPUnit 3.7 and 3.8.
For example :
// Matcher that asserts that there is an element with an id="my_id".
$matcher = array('id' => 'my_id');
// Matcher that asserts that there is a "span" tag.
$matcher = array('tag' => 'span');
// Matcher that asserts that there is a "div", with an "ul" ancestor and a "li"
// parent (with class="enum"), and containing a "span" descendant that contains
// an element with id="my_test" and the text "Hello World".
$matcher = array(
'tag' => 'div',
'ancestor' => array('tag' => 'ul'),
'parent' => array(
'tag' => 'li',
'attributes' => array('class' => 'enum')
),
'descendant' => array(
'tag' => 'span',
'child' => array(
'id' => 'my_test',
'content' => 'Hello World'
)
)
);
// Use assertTag() to apply a $matcher to a piece of $html.
$this->assertTag($matcher, $html);
Read more in official PHPUnit Website.

You may want to consider looking at Selenium. It is a browser-based testing tool for doing functional tests for a web site.
You write scripts which involve loading a web browser and simulating clicks and other actions, and then doing asserts to check that, for example, specific page elements are present, in the correct place or contain the expected values.
The tests can be written using an IDE that runs as a plug-in for Firefox, but they can be run against all the major browsers.
We have a suite of Selenium tests that run as part of our CI process, allowing us to see very quickly if something has gone wrong with our HTML output.
All in all, its a very powerful testing tool.
Also, it integrates with PHPUnit (and other language-specific tools), so it does answer your question, although probably not in the way you were thinking of.

You should be a bit careful in comparing outputted HTML to a correct template. Your HTML will change a lot, and you can end up spending too much time on maintaining your tests.
See this post for an alternative approach.

You can use saveHtml method of DOMDocument and compare the output.

You can compare two HTML strings with PHPUnit assertXmlStringEqualsXmlString method:
$this->assertXmlStringEqualsXmlString($emailMarkup, $html);
where
$emailMarkup - expected HTML string
$html - current HTML string
Important! HTML strings must be XML-valid. For example use
<br/>
instead
<br>
Also tag attributes must have values, e.g. use
<hr noshade="true">
instead
<hr noshade>

It is best not to validate against a template (unless you want to make sure nothing changes, but that is a different condition / test that you may want). You will probably want to test that your HTML includes what the user should actually see, and not that the actual HTML that formats the output is exactly what is in a template. I would recommend sending your HTML through a converter that changes it into pure text, then testing to see if you get the right results. This accommodates future functionality and data related changes that are inevitable in software development. You don't want your tests failing because someone added a class somewhere. This is probably a custom type test you will want to code yourself to meet your needs.
It is also best to insure your HTML (and CSS) is correctly formatted, what ever it may be. Sometimes invalid HTML is parsed and displayed somewhat reasonably by the browser, but best not to rely on browsers knowing what do to with invalid HTML and CSS. I have seen many issues fixed just by correcting the HTML.
I developed a library that outputs HTML PHPFUI, and I could not find any recent or even supported HTML unit tests for PHPUnit. So I created https://packagist.org/packages/phpfui/html-unit-tester which is a modern HTML and CSS unit tester. It validates against w3.org standards, so will always be up to date with the latest.
Basically you can pass in HTML fragments, or entire pages, and it will check validity of your HTML. You can test strings, files or even live URLs. Really handy to make sure all the HTML and CSS you are generating is valid. I found so many issues with my code with this library, was definitely worth the time invested. Hope everyone can benefit from it as well.

Related

Gutenberg Templates: Core Block Attributes

The Gutenberg Handbook currently has a short entry for creating whole templates of blocks used e.g. for Custom Post Types or the like.
https://wordpress.org/gutenberg/handbook/templates/
It seems to be missing a comprehensive overview of the core/-Blocks though. Especially the available attributes are interesting here. Is there a reference-entry I am just missing?
To elaborate:
By playing around, I found out a few things. E.g. preformatted blocks do take the formatting of a php file like line breaks, indends and tabs, which makes them a bit sensitive..
array( 'core/preformatted', array(
'content' => 'Grundlegende Fakten:
Operator: Max Mustermann
Wo: City, Country
Wer: 99999 Kinder
Wieviel: 99999 Angestellte',
) ),
This does translate into:
(note that every tab or indent before later lines would have been taken over as well)
So - what other possibilities do i have to modify the 'content' and 'placeholder' attributes? Can I make use of the fact that they are arrays and insert selectors or other html like .. This does NOT work:
array( 'core/preformatted', array(
'content' => array('selector' => 'h1', 'content' => 'Does this do anything?'),
) ),
..But this DOES:
array( 'core/preformatted', array(
'content' => array('Does', 'this', 'do', 'anything?'),
) ),
And where can I find a comprehensive list of first order attributes, since e.g it's not always clear whether a core/block will take a 'text'-string or a 'content'-array and so on..
To partly answer my own question:
As mentioned in this git issue you can use
console.log(wp.blocks.getBlockTypes());
in the browser console after all the Gutenberg magic loaded (e.g. in the editor window of a post) to show all currently registered blocks, inluding their attributes.
Definitely a helpful tool!
Another Info-Source:
The Git-Project of Gutenberg holds all core blocks and their properties can be accessed by
Name-of-Block/index.js
Then find: const blockAttributes =

Render different partial templates in EpiServer

I have a page partial that is supposed to render inside a ContentArea when the page is added there. This works perfectly, but now I have two different ContentAreas on two different pages and I want the same child page added to those to render different on each parent page.
I get that I could in some way use a Tag when rendering the partial to differentiate between the ContentAreas:
#Html.PropertyFor(m => m.MyBlockProperty, new { Tag = RenderingTags.Sidebar })
#Html.PropertyFor(m => m.MyContentArea, new { Tag = RenderingTags.Sidebar })
But then, in my SomePage.cshtml (which is my partial view), do I get a varaible or something here so I know which Tag was asked for? Or is there some naming convention like SidebarSomePage.cshtml so that I can define multiple partial templates? Do I have to create a controller to deal with this? It seems unneccessary to me, I just want to change the html a bit depending on page...
Create a PartialContentController<T> and then use the TemplateDescriptorAttribute to specify the tags you wan't to use. Then use PropertyFor as Johan explained in the view.
From the EPiServer documentation
The template you choose to render a content instance depends on the specific context such as channel and tagging. For a template to be automatically registered it has to implement EPiServer.Web.IRenderTemplate (where T states which model it can render). If you use a base class for your template like PageBase, ContentControlBase, BlockControlBase, PageController, PartialContentController or BlockController, then you do not need to explicitly implement the interface because that is done by the base class. In addition, you can use the TemplateDescriptorAttribute to specify more details about the template such as tags and inheritance, more information on that topic later.
I'm pretty sure you can access the tag from the ViewData dictionary in your view (or controller) like this:
#ViewData["Tag"]
You can also pass any other setting to the view
#Html.PropertyFor(m => m.MyContentArea, new { Tag = RenderingTags.Sidebar, RenderThisPartialDifferently = true, ShowHeading = false })
And then access them:
#ViewData["RenderThisPartialDifferently"]
#ViewData["ShowHeading "]
And then you have the option to have a controller in between and render a completely different view.
Pretty sure there is a naming convention for tag views as well. What I do know for sure though, is that you can put a view with the same name as the tag in /shared/displaytemplates. But that's not what you're asking for now.
Also addition to all answers, you can use template registrator to register additional templates for specific tags.
[ServiceConfiguration(typeof(IViewTemplateModelRegistrator))]
public class TemplateCoordinator : IViewTemplateModelRegistrator
{
public void Register(TemplateModelCollection viewTemplateModelRegistrator)
{
viewTemplateModelRegistrator.Add(typeof(MyBlock), new TemplateModel
{
Tags = new[] { RenderingTags.Sidebar },
AvailableWithoutTag = false,
Path = BlockPath("Some-Other-Template.cshtml")
});
}
}
This will make sure that if block is rendered "inside" RenderingTags.Sidebar context (for instance via Html.PropertyFor(...., new { tag = RenderingTags.Sidebar })) file Some-Other-Template.cshtml will be used.
AlloyTech has sample code there.

Android ListView binding programmatically

There are many examples of doing this in axml, but I would like to have a complete binding using code behind. To be honest, I would like to have NO axml, but seems like creating all the controls programmatically is a nightmare.
I first tried the suggestions at:
MvxListView create binding for template layout from code
I have my list binding from code-behind, and I get six rows (so source binding is working); but the cells itself does not bind.
Then at the following url:
Odd issue with MvvmCross, MvxListViewItem on Android
Stuart has the following comment: Have looked through. In this case, I don't think you want to use DelayBind. DelayBind is used to delay the binding action until next time the DataContext is set. In Android's MvxAdapter/MvxListItemView case, the DataContext is passed in the ctor - so DataContext isn't set again until the cell is reused. (This is different to iOS MvxTableDataSource).
So in essence, the only example I see shows DelayBind, which shouldn't work.
Can someone please show me some examples... thanks in advance.
Added reply to Comments:
Cheesebaron, first of all, a huge thank you and respect for all your contributions;
Now, why not use axml? Well, as programmers, we all have our own preferences and way of doing stuff - I guess I am old school where we didn't have any gui designer (not really true).
Real reasons:
Common Style: I have a setup where Core has all the style details, including what all the colors would be. My idea is, each platform would get the style details from core and update accordingly. It's easy for me to create controls with the correct style this way.
Copy-Paste across platform (which then I can even have as linked files if I wanted). For example, I have a login screen with web-like verification, where a red error text appears under a control; overall on that screen I have around 10 items that needs binding. I have already got iOS version working - so starting on Droid, I copied the whole binding section from ios, and it worked perfectly. So, the whole binding, I can make it same across all platform... Any possible error in my way will stop at building, which I think is a major advantage over axml binding. Even the control creation is extremely similar, where I have helpers with same method name.
Ofcourse I understand all the additional layout that has to be handled; to be honest, it's not that bad if one really think it through; I have created a StackPanel for Droid which is based on WP - that internally handles all the layouts for child views; so for LinearLayout, all I do is setup some custom parameters, and let my panel deal with it. Relative is a different story; so far, I have only one screen that's relative, and I can even make it Linear to reduce my additional layout code.
So, from my humble point of view, for my style, code-behind creation allows me to completely copy all my bindings (I do have some custom binding factories to allow that), copy all my control create lines; then only adding those controls to the view is the only part that is different (then again, droid and WP are almost identical). So there is no way I can miss something on one platform and all are forced to be the same. It also allows me to change all the styles for every platform just by changing the core. Finally, any binding error is detected during compile - and I love that.
My original question wasn't about NOT using axml... it was on how to use MvxListView where all the binding is done in code-behind; as I have explained, I got the list binding, but not the item/cell binding working.
Thanks again in advance.
Here is part of my LoginScreen from droid; I think it's acceptable amount of code for being without axml file.
//======================================================================================================
// create and add all controls
//======================================================================================================
var usernameEntry = ControlHelper.GetUITextFieldCustom(this, "Username.", maxLength: 20);
var usernameError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Username);
var passwordEntry = ControlHelper.GetUITextFieldCustom(this, "Password.", maxLength: 40, secureTextEntry: true);
var passwordError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Password);
var loginButton = ControlHelper.GetUIButtonMain(this);
var rememberMe = new UISwitch(this);
var joinLink = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var copyRightText = ControlHelper.GetUILabel(this, textAlignment: UITextAlignment.Center);
var copyRightSite = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var layout = new StackPanel(this, Orientation.Vertical)
{
Spacing = 15,
SubViews = new View[]
{
ControlHelper.GetUIImageView(this, Resource.Drawable.logo),
usernameEntry,
usernameError,
passwordEntry,
passwordError,
loginButton,
rememberMe,
joinLink,
ControlHelper.GetSpacer(this, ViewGroup.LayoutParams.MatchParent, weight: 2),
copyRightText,
copyRightSite
}
};
I just came across a similar situation myself using Mvx4.
The first link you mentioned had it almost correct AND when you combine it from Staurts comment in the second link and just remove the surrounding DelayBind call, everything should work out ok -
public class CustomListItemView
: MvxListItemView
{
public MvxListItemView(Context context,
IMvxLayoutInflater layoutInflater,
object dataContext,
int templateId)
: base(context, layoutInflater, dataContext, templateId)
{
var control = this.FindViewById<TextView>(Resource.Id.list_complex_title);
var set = this.CreateBindingSet<CustomListViewItem, YourThing>();
set.Bind(control).To(vm => vm.Title);
set.Apply();
}
}
p.s. I have asked for an Edit to the original link to help others.

MATLAB: displaying markup (HTML or other format)

I'd like to display a table from a script in MATLAB. I can easily generate the <td> and other HTML elements, but as far as I know, I can only write them to a file.
Is there a way to display HTML (or some other markup) from MATLAB? Or am I stuck writing to a file and opening a browser?
You can display the HTML text in a PopupPanel as explained here: http://UndocumentedMatlab.com/blog/customizing-help-popup-contents/
Or in an integrated browser control that points to your HTML file or HTML text as explained here: http://UndocumentedMatlab.com/blog/gui-integrated-browser-control/
Use the Java Swing component inside a MATLAB figure, precisely JEditorPane using MATLAB's javacomponent() function. JEditorPane supports a good subset of HTML.
Here is a code sample:
mytext = '<html><body><table border="1"><tr><th>Month</th><th>Savings</th></tr><tr><td>January</td><td>$100</td></tr></table></body></html>';
hfig = figure();
je = javax.swing.JEditorPane( 'text/html', mytext );
jp = javax.swing.JScrollPane( je );
[hcomponent, hcontainer] = javacomponent( jp, [], hfig );
set( hcontainer, 'units', 'normalized', 'position', [0,0,1,1] );
%# Turn anti-aliasing on ( R2006a, java 5.0 )
java.lang.System.setProperty( 'awt.useSystemAAFontSettings', 'on' );
je.putClientProperty( javax.swing.JEditorPane.HONOR_DISPLAY_PROPERTIES, true );
je.putClientProperty( com.sun.java.swing.SwingUtilities2.AA_TEXT_PROPERTY_KEY, true );
je.setFont( java.awt.Font( 'Arial', java.awt.Font.PLAIN, 13 ) );
EDIT: see the discussion of this solution here,
One alternative is to display the table in a graphics window using the UITABLE control.
EDIT: Even though this is only an alternative (not a solution) to the problem in the question, I thought I'd include a sample for anyone who may be interested in this option:
hFigure = figure('Position',[100 100 300 220]);
hTable = uitable(hFigure,'Data',rand(10,3),...
'ColumnName',{'X' 'Y' 'Z'},...
'Position',[20 20 260 180]);
I ended up doing what I didn't quite want to do, namely to write HTML to a file. It requires me to open it in a browser and refresh every time I run my script, but that's not too bad for what I needed in the short term.

Stylistic Question: Use of White Space

I have a particularly stupid insecurity about the aesthetics of my code... my use of white space is, frankly, awkward. My code looks like a geek dancing; not quite frightening, but awkward enough that you feel bad staring, yet can't look away.
I'm just never sure when I should leave a blank line or use an end of line comment instead of an above line comment. I prefer to comment above my code, but sometimes it seems strange to break the flow for a three word comment. Sometimes throwing an empty line before and after a block of code is like putting a speed bump in an otherwise smooth section of code. For instance, in a nested loop separating a three or four line block of code in the center almost nullifies the visual effect of indentation (I've noticed K&R bracers are less prone to this problem than Allman/BSD/GNU styles).
My personal preference is dense code with very few "speed bumps" except between functions/methods/comment blocks. For tricky sections of code, I like to leave a large comment block telling you what I'm about to do and why, followed by a few 'marker' comments in that code section. Unfortunately, I've found that some other people generally enjoy generous vertical white space. On one hand I could have a higher information density that some others don't think flows very well, and on the other hand I could have a better flowing code base at the cost of a lower signal to noise ratio.
I know this is such a petty, stupid thing, but it's something I really want to work on as I improve the rest of my skill set.
Would anyone be willing to offer some hints? What do you consider to be well flowing code and where is it appropriate to use vertical white space? Any thoughts on end of line commenting for two or three words comments?
Thanks!
P.S.
Here's a method from a code base I've been working on. Not my best, but not my worst by far.
/**
* TODO Clean this up a bit. Nothing glaringly wrong, just a little messy.
* Packs all of the Options, correctly ordered, in a CommandThread for executing.
*/
public CommandThread[] generateCommands() throws Exception
{
OptionConstants[] notRegular = {OptionConstants.bucket, OptionConstants.fileLocation, OptionConstants.test, OptionConstants.executable, OptionConstants.mountLocation};
ArrayList<Option> nonRegularOptions = new ArrayList<Option>();
CommandLine cLine = new CommandLine(getValue(OptionConstants.executable));
for (OptionConstants constant : notRegular)
nonRegularOptions.add(getOption(constant));
// --test must be first
cLine.addOption(getOption(OptionConstants.test));
// and the regular options...
Option option;
for (OptionBox optionBox : optionBoxes.values())
{
option = optionBox.getOption();
if (!nonRegularOptions.contains(option))
cLine.addOption(option);
}
// bucket and fileLocation must be last
cLine.addOption(getOption(OptionConstants.bucket));
cLine.addOption(getOption(OptionConstants.fileLocation));
// Create, setup and deploy the CommandThread
GUIInteractiveCommand command = new GUIInteractiveCommand(cLine, console);
command.addComponentsToEnable(enableOnConnect);
command.addComponentsToDisable(disableOnConnect);
if (!getValue(OptionConstants.mountLocation).equals(""))
command.addComponentToEnable(mountButton);
// Piggy-back a Thread to start a StatReader if the call succeeds.
class PiggyBack extends Command
{
Configuration config = new Configuration("piggyBack");
OptionConstants fileLocation = OptionConstants.fileLocation;
OptionConstants statsFilename = OptionConstants.statsFilename;
OptionConstants mountLocation = OptionConstants.mountLocation;
PiggyBack()
{
config.put(OptionConstants.fileLocation, getOption(fileLocation));
config.put(OptionConstants.statsFilename, getOption(statsFilename));
}
#Override
public void doPostRunWork()
{
if (retVal == 0)
{
// TODO move this to the s3fronterSet or mounts or something. Take advantage of PiggyBack's scope.
connected = true;
statReader = new StatReader(eventHandler, config);
if (getValue(mountLocation).equals(""))
{
OptionBox optBox = getOptionBox(mountLocation);
optBox.getOption().setRequired(true);
optBox.requestFocusInWindow();
}
// UGLY HACK... Send a 'ps aux' to grab the parent PID.
setNextLink(new PSCommand(getValue(fileLocation), null));
fireNextLink();
}
}
}
PiggyBack piggyBack = new PiggyBack();
piggyBack.setConsole(console);
command.setNextLink(piggyBack);
return new CommandThread[]{command};
}
It doesn't matter.
1) Develop a style that is your own. Whatever it is that you find easiest and most comfortable, do it. Try to be as consistent as you can, but don't become a slave to consistency. Shoot for about 90%.
2) When you're modifying another developer's code, or working on a group project, use the stylistic conventions that exist in the codebase or that have been laid out in the style guide. Don't complain about it. If you are in a position to define the style, present your preferences but be willing to compromise.
If you follow both of those you'll be all set. Think of it as speaking the same language in two different ways. For example: speaking differently around your friends than you do with your grandfather.
It's not petty to make pretty code. When I write something I'm really proud of, I can usually take a step back, look at an entire method or class, and realize exactly what it does at a glance - even months later. Aesthetics play a part in that, though not as large of a part as good design. Also, realize you can't always write pretty code, (untyped ADO.NET anyone?) but when you can, please do.
Unfortunately, at this higher level at least, I'm not sure there are any hard rules you can adhere to to always produce aesthetically pleasing code. One piece of advice I can offer is to simply read code. Lots of it. In many different frameworks and languages.
I like to break up logical "phrases" of code with white space. This helps others easily visualize the logic in the the method - or remind me when I go back and look at old code. For example, I prefer
reader.MoveToContent();
if( reader.Name != "Limit" )
return false;
string type = reader.GetAttribute( "type" );
if( type == null )
throw new SecureLicenseException( "E_MissingXmlAttribute" );
if( String.Compare( type, GetLimitName(), false ) != 0 )
throw new SecureLicenseException( "E_LimitValueMismatch", type, "type" );
instead of
reader.MoveToContent();
if( reader.Name != "Limit" )
return false;
string type = reader.GetAttribute( "type" );
if( type == null )
throw new SecureLicenseException( "E_MissingXmlAttribute" );
if( String.Compare( type, GetLimitName(), false ) != 0 )
throw new SecureLicenseException( "E_LimitValueMismatch", type, "type" );
The same break can almost be accomplished with braces but I find that actually adds visual noise and reduces the amount of code that can be visually consumed simultaneously.
Commens on code line
As for comments at the end of the line - almost never. The're not really bad, just easy to miss when scanning through code. And they clutter up the line taking away from the code making it harder to read. Our brains are already wired to grok line by line. When the comment is at the end of the line we have to split the line into two concrete concepts - code and comment. I say if it's important enough to comment on, put it on the line proceeding the code.
That being said, I do find one or two line hint comments about the meaning of a specific value are sometimes OK.
I find code with very little whitespace hard to read and navigate in, since I need to actually read the code to find logical structure in it. Clever use of whitespace to separate logical parts in functions can increase the ease of understanding the code, not only for the author but also for others.
Keep in mind that if you are working in an environment where your code is likely to be maintained by others, they will have spent the majority of their time looking at code that was not written by you. If your style distinctly differs from what they are used to seeing, your smooth code may be a speed bump for them.
I minimize white space. I put the main comment block above the code block and Additional end of line comments on the Stuff that may not be obvious to another dveloper. I think you are doing that already
My preferred style is probably anathema to most developers, but I will add occasional blank lines to separate what seem like appropriate 'paragraphs' of code. It works for me, nobody has complained during code reviews (yet!), but I can imagine that it might seem arbitrary to others. If other people don't like it I'll probably stop.
The most important thing to remember is that when you join an existing code base (as you almost always will in your professional career) you need to adhere to the code style guide dictated by the project.
Many developers, when starting a project afresh, choose to use a style based on the Linux kernel coding-style document. The latest version of that doc can be viewed at http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blob;f=Documentation/CodingStyle;h=8bb37237ebd25b19759cc47874c63155406ea28f;hb=HEAD.
Likewise many maintainers insist that you use Checkpatch before submitting changes to version control. You can see the latest version that ships with the Linux kernel in same tree I linked to above at scripts/checkpatch.pl (I would link to it but I'm new and can only post one hyperlink per answer).
While Checkpatch is not specifically related to your question about whitespace usage, it will certainly help you eliminate trailing whitespace, spaces before tabs, etc.
Code Complete, by Steve McConnell (available in the usual locations) is my bible on this sort of thing. It has a whole chapter on layout and style that is just excellent. The whole book is just chock full of useful and practical advice.
I use exactly the same amount of whitespace as you :) Whitespace before methods, before comment blocks. In C, C++ the brackets also provide some "pseudo-whitespace" as there is only a single opening/closing brace on some lines, so this also serves to break up the code density.
Your code is fine, just do what you (and others you might work with) are comfortable with.
The only thing I see wrong with some (inexperienced) programmers about whitespace is that they can be afraid to use it, which is not true in this case.
I did however notice that you did not use more than one consecutive blank line in your sample code, which, in certain cases, you should use.
Here is how I would refactor that method. Things can surely still be improved and I did not yet refactor the PiggyBack class (I just moved it to an upper level).
By using the Composed Method pattern, the code becomes easier to read when it's divided into methods that each do one thing and work on a single level of abstraction. Also less comments are needed. Comments that answer to the question "what" are code smells (i.e. the code should be refactored to be more readable). Useful comments answer to the question "why", and even then it would be better to improve the code so that the reason will be obvious (sometimes that can be done by having a test that will fail without the inobvious code).
public CommandThread[] buildCommandsForExecution() {
CommandLine cLine = buildCommandLine();
CommandThread command = buildCommandThread(cLine);
initPiggyBack(command);
return new CommandThread[]{command};
}
private CommandLine buildCommandLine() {
CommandLine cLine = new CommandLine(getValue(OptionConstants.EXECUTABLE));
// "--test" must be first, and bucket and file location must be last,
// because [TODO: enter the reason]
cLine.addOption(getOption(OptionConstants.TEST));
for (Option regularOption : getRegularOptions()) {
cLine.addOption(regularOption);
}
cLine.addOption(getOption(OptionConstants.BUCKET));
cLine.addOption(getOption(OptionConstants.FILE_LOCATION));
return cLine;
}
private List<Option> getRegularOptions() {
List<Option> options = getAllOptions();
options.removeAll(getNonRegularOptions());
return options;
}
private List<Option> getAllOptions() {
List<Option> options = new ArrayList<Option>();
for (OptionBox optionBox : optionBoxes.values()) {
options.add(optionBox.getOption());
}
return options;
}
private List<Option> getNonRegularOptions() {
OptionConstants[] nonRegular = {
OptionConstants.BUCKET,
OptionConstants.FILE_LOCATION,
OptionConstants.TEST,
OptionConstants.EXECUTABLE,
OptionConstants.MOUNT_LOCATION
};
List<Option> options = new ArrayList<Option>();
for (OptionConstants c : nonRegular) {
options.add(getOption(c));
}
return options;
}
private CommandThread buildCommandThread(CommandLine cLine) {
GUIInteractiveCommand command = new GUIInteractiveCommand(cLine, console);
command.addComponentsToEnable(enableOnConnect);
command.addComponentsToDisable(disableOnConnect);
if (isMountLocationSet()) {
command.addComponentToEnable(mountButton);
}
return command;
}
private boolean isMountLocationSet() {
String mountLocation = getValue(OptionConstants.MOUNT_LOCATION);
return !mountLocation.equals("");
}
private void initPiggyBack(CommandThread command) {
PiggyBack piggyBack = new PiggyBack();
piggyBack.setConsole(console);
command.setNextLink(piggyBack);
}
For C#, I say "if" is just a word, while "if(" is code - a space after "if", "for", "try" etc. doesn't help readability at all, so I think it's better without the space.
Also: Visual Studio> Tools> Options> Text Editor> All Languages> Tabs> KEEP TABS!
If you're a software developer who insists upon using spaces where tabs belong, I'll insist that you're a slob - but whatever - in the end, it's all compiled. On the other hand, if you're a web developer with a bunch of consecutive spaces and other excess whitespace all over your HTML/CSS/JavaScript, then you're either clueless about client-side code, or you just don't give a crap. Client-side code is not compiled (and not compressed with IIS default settings) - pointless whitespace in client-side script is like adding pointless Thread.Sleep() calls in server-side code.
I like to maximize the amount of code that can be seen in a window, so I only use a single blank line between functions, and rarely within. Hopefully your functions are not too long. Looking at your example, I don't like a blank line for an open brace, but I'll have one for a close. Indentation and colorization should suffice to show the structure.