Which coding style is more common? - language-agnostic

In no way shape or form am i advertising/promoting my programming style, but as far as 'multiple variable declarations' are concerned, which case is more acceptable professionally and commonly:
case 1:
private $databaseURL = "localhost" ;
private $databaseUName = "root" ;
private $databasePWord = "" ;
private $databaseName = "AirAlliance";
case 2:
private $databaseURL = "localhost";
private $databaseUName = "root";
private $databasePWord = "";
private $databaseName = "AirAlliance";
The reason i like case 1 is because i can skim though it and see that all is correct way faster than case 2. Also i can visually get familiar with variable names witch makes it faster to work with them l latter on the program.

Whichever style the project is already using, so you don't end up spending all day fixing every file you touch.

case 1.5:
private $databaseURL = "localhost";
private $databaseUName = "root";
private $databasePWord = "";
private $databaseName = "AirAlliance";
I don't think aligning the semicolons makes it any more readable, it just makes it annoying to change the value of one of the strings and then have to add or delete spaces to line up the semicolons all over again.
In this case, it looks like the variable names are unlikely to change, so it should be OK to line up the equals signs. If it were possible that the variable names would change, however, I would go with case 2 because (again) it would be annoying to have to line everything up again. (Imagine the work involved in simply adding a new variable called $databaseLongVariableName.)

Case 2. When you add a new variable to your "group", or add/remove a character on one of those lines, you won't have to spend time fiddling around trying to make things line up.

If you change all their alignments when you add a new variable, then any diff tool will show up multiple changes there. Just a thought.
Also, I've done this once. It became a pain in the ass when I had to add a variable that was longer. Padding out all the existing ones with spaces to match turned me off this technique.

Interesting question. As far as I'm concerned, there's no good reason to use case 1. I've never seen that style before, except possibly in config files, and it costs extra time to format your code properly. As soon as you change the contents of the variable, you have to reset your semi-colon as well.
It only works if you use spaces as well... anyone using tabs might have different tab stops set, so it will look completely different opened in another editor.
I think the advantage of readability you mention is somewhat offset by the extra effort required to write it.

It's very tempting to nicely align stuff, I used to align my accessors in PHP as so
function getName() { return $this->name; }
function getAge() { return $this->age; }
function getHeight(){ return $this->height; }
The problem comes when you add in a longer line:
function getName() { return $this->name; }
function getAge() { return $this->age; }
function getNiNumber(){ return $this->ni_number; }
function getHeight(){ return $this->height; }
If I edit the three other lines, then when I commit my change it makes it harder to see who wrote a particular line, and in which revision they did it.

Aligning stuff like = and ; just invites a whole big mess of tab-space screw ups that get checked in, then have to be fixed later.
Most people will use tabs to the left of a line for indentation, then use spaces to align stuff to the right.
Beyond adding bloat to files, it just becomes a big, inconsistent soupy mess. To me, it does not make the code any more readable. To some editors, it makes the code even less readable.

Use case 2. That is far more standard: Google C++ Style
Really you shouldn't even concern yourself with this. Your editor should automatically autoformat your code. Try ctrl+shift+F in Eclipse.

Aligning the semicolons seems like wasted time to me, unless your IDE/text editor can do it for you. Especially if you later add another entry longer than the previous ones; you'll have to realign all of them.

I just fired up my editor and it just hit me. all the reasons i like case 1 for are in syntax highlighting without wasting time.

case 2. with anything else your version control will go crazy everytime you re-adjust the spacing. besides with IDEs that has highlighting and some also show a variable listing, its really a waste of time to align '=' and ';' in my opinion.

Case 2. If I leave out a semicolon, I have a program that tells me so. It's the compiler.

Going with what ever the project you are working on is the best option. (If the project doesn't have a set of coding guidelines, spending five minutes to define them is highly recommended).
A lot of the larger programs have tools which scan the code looking for things to sort and clean. Adding whitespace at the end of the variable could affect some of them.
Also regarding tabs, I've never worked on a project that didn't determine the tab spacing for the editing. You can always use your personal one and have a precommit hook to edit the file before it goes in, but messing with tab spacing will annoy people no end.

You can have a look at the book "Expert PHP 5 Tools" for better understanding the code styling in more detail way.
*There is e-book in net *

Related

Can anyone explain .split(''); in Razor?

I sitting here with a ton of code (that works) which I have to look through, and some of it happens to be in Razor. Not too hard to understand, yet not something I've tried before.
My problem is that the function .split(''); (notice the '') comes up several times and I don't understand neither the purpose nor what it does, cause I feel like it would just give an error to split on nothing.
I can't really test anything as the code is way too large for me to be able to just run to check such a minor thing, and there are no real places to test Razor unless I get enough understanding to just make a testpage from scratch.
The most simple example I can find is this:
function openbysetting(settingcookie)
{
var settingsarray = settingcookie.split('');
for (var i = 0; i < settingsarray.length; i++)
{
if (settingsarray[i] == 'f')
{
....
}
};
}
Mind you, settingcookie isn't defined or mentioned anywhere else in this entire code, so I don't even understand why a regular split function would be required.
Edit: Never mind, I'm told it's a javascript thing. Just ignore the previous sentence.
As for a result, I'd expect it to just simply not work, but it seems to be doing fine.
C# just gives an error if you do it, and this is a C# based language after all.
Hope someone can clarify. Thank you.
Edit: Okay, I understand now. It just splits between every single character. Thanks for the help.

WebdriverIO waitfor methods don't work as expected

I am working on a set of webdriverIO tests that use a lot of pauses. To make the framework more robust I want to get rid of the pauses and introduce waitfor statements
I have looked through some walkthroughs, and most of them suggest something in the line of this:
var decrease = browser.$("//*[#id='somebutton");
decrease.waitForExist(5000)
decrease.click()
This doesn't work in 90% of the times however, returning the error message:
An element could not be located on the page using the given search parameters ("//*[#id='somebutton'"). (pretty much the same message I get when I remove the wait altogether)
I have tried both waitForExist and waitForVisible without success
I have played around a but, and found out that the following way does work:
browser.$("//*[#id='somebutton").waitForVisible(5000);
browser.$("//*[#id='somebutton").click()
I am not fond of this solution though, because it requires replication of the locator, which will make support harder in the future.
Can anyone shed some light on why the first option might not be working for me?
This should do the trick:
var selector = "//*[#id='somebutton";
browser.waitForExist(selector, 5000);
browser.click(selector);
Also, an example in the api docs shows it being done like this. Notice they left off the browser. portion.
var notification = $('.notification');
notification.waitForExist(5000);
Perhaps that is your issue? Both ways should work though.
One last thing, you don't have to use the xpath for this element if you don't absolutely have to. It's easier to just use the css selector for id.
var decrease = $('#somebutton');

Better Practice for this example: Breaking up code with functions or using comments

Sometimes I get torn on whether I should leave the code in a bigger block or break them up into functions. Functions can make it more clear, as it separates the code, but I feel the clarity can sometimes be the same by using comments. My code below is a C# code where I'm initializing the Controls.
Here I can have it is a block or separate it into functions. Which of the 3 types would you prefer and why? Would your answer change if each section/category (Enable controls, Initial label values, control properties) of the code was much bigger? Maybe 5-15 lines each? Let's assume the code inside Initialize() won't be reused much except through the function Initialize(). Any other criticism is welcomed too. Thanks.
protected void Initialize()
{
for (int i = 0; i < numOfTrackBars; i++)
{
//Enable controls
trackBarList[i].Enabled = true;
trackBarLabelList[i].Enabled = true;
trackBarFieldList[i].Enabled = true;
//Initial label values
trackBarLabelList[i].Text = trackBarNames[i];
trackBarFieldList[i].Text = Convert.ToString(0);
//Control properties
trackBarList[i].Maximum = trackBarMaxValues[i];
trackBarList[i].Minimum = trackBarMinValues[i];
}
}
Or:
protected void Initialize()
{
for (int i = 0; i < numOfTrackBars; i++)
{
EnableControls(i);
InitializeLabelValues(i);
SetControlProperties(i);
}
}
private EnableControls(int i)
{
trackBarList[i].Enabled = true;
trackBarLabelList[i].Enabled = true;
trackBarFieldList[i].Enabled = true;
}
Or:
private void EnableControls()
{
for(int i = 0; i < numOfTrackBars; i++)
{
trackBarList[i].Enabled = true;
trackBarLabelList[i].Enabled = true;
trackBarFieldList[i].Enabled = true;
}
}
The others functions being the same, so 3 for loops.
Comments are evil. To quote R. Martin: "comments are your failure". If you need to write a comment, it means that you have failed to write your code in a readable way, and need some additional explanation.
Why comments are bad:
They are written in natural language, so inherently not as precise as code and usually ambiguous (especially in multi-language teams, or among non-native speakers at different level).
They get obsolete. Very rarely someone quickly fixing a bug will fix the comments as well. And there is no way to verify it.
They are noise - additional characters which distract you from reading the actual code.
They bring another degree of freedom to your application's code. Even if you waste a lot of time designing a commenting policy, establishing a format of comments, and introducing precise rules on when and where to put comments, they will vary between developers. One possible reason is mentioned in the first point, other is that it's hard to write precise rules for a natural language, which is inherently imprecise. Precise definition of commenting standard needs huge amount of rules and guidelines and imposes a huge burden on developers.
Sometimes it is really hard to write something in a readable way. Sometimes things are just complicated themselves and even the simplest possible code that implements them is not easy to understand. Sometimes you need to write some non-obvious hack to meet some strange requirements of a 3rd party library. Then you write a comment, knowing that this is a communication failure but there is no other way.
Such rare comments will have their value - if someone reads a clean and readable code without a single comment, and suddenly spots one then they will know that surely this is something important that needs their attention and they need to be cautious here.
When there are lots of comments, they are just being ignored, and you won't have the possibility to inform about something really important - your comment will be lost in the sea of other comments.
The difference between the second and third version of your code is IMHO meaningless. If none of these versions is better in terms of code duplication then it seems to me that it doesn't matter which one you'll use. You could use InitializeLabelValues instead of Initialize for example though.
My order of preference would be #2, #1, #3.
I find #2 the clearest because it shows exactly what you're doing: enabling, labeling, and setting properties for each item. It's easy to drill into each of those actions if you need the details, but you're not distracted by them.
#1 is next because it's also simple, straightforward, and easy to follow. You've visually separated each of the steps, so again, the details are available if you need them, but it's easy to skip over any section that isn't immediately relevant.
I find #3 both harder to read and less efficient. It's clearer to me to iterate through each item, initializing it completely, than to perform one action on all of the items, then the next action, and so on.

What does __ mean when it is part of a function name

I have been looking for a way to code the popup window to perform some action in the parent window here on SO. Somewhere in one of the posts I read a suggestion that the "inspect element" option in browsers is a good way to learn. With this option I got the code for the session timeout popup from my host. Here is the part that I am trying to understand:
function fireTimeoutEvent()
{
__doPostBack('','#####forceSessionTimeout');
}
function __doPostBack(eventTarget, eventArgument)
{
var theform = document.Form1;
theform.__EVENTTARGET.value = eventTarget;
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
What do the "__" mean in the four lines of the code? Do they have a special significance? Am I correct in thinking this is javascript? I ask because I am not familiar enough with the niceties of javascript, jquery and the rest to be able to recognize the difference.
Also, from this script, is it possible to tell what it is going to do? Though the popup is essentially meant to extend the session, it has some other functions besides this one, but none of the others have any under-scores in them.
Usually library writers use _ or __ to indicate private functions or methods. So this is probably something that the person didn't want people to call directly.

Force immediate layout and paint in Swing

I cannot seem to force a layout in Swing. I have a JComponent added to a JLayeredPane and I set a border on the JComponent. Then, I want to immediately re-draw everything - not in the sense of "please do this asap" like invalidate(), but synchronously and immediately. Any help? I cannot seem to find the right method of doing this, and all my reading about invalidate(), validate(), repaint(), doLayout(), etc is just confusing me more!
According to this (see the section titled "Synchronous Painting") the paintImmediately() method should work.
The most reliable way to get Swing to update a display is to use SwingUtilities.invokeLater. In your case, it would look something like
SwingUtilities.invokeLater(new Runnable {
public void run() {
somecomponent.repaint();
}
});
I realize the 'invokelater' does not exactly sound like it does anything immediate, but in practice, events posted in this way tend execute pretty quickly compared to just calling e.g. somecomponent.repaint() directly. If you absolutely must make your control code wait for the GUI to update, then there is also invokeAndWait, but my experience is that this is rarely necessary.
See also: document on event dispatch in Swing.
This is super old, but I found a simple solution, which I'll show with a JPasswordField:
var pw = new JPasswordField();
...
pw.paint(pw.getGraphics()); // paints immediately